blob: 7fad69541b3ed902643906685de392df9ba2c3f7 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Larry Hastings61272b72014-01-07 12:41:53 -080050/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080051class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080052[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080053/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080054
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055/* --- Globals ------------------------------------------------------------
56
Serhiy Storchaka05997252013-01-26 12:14:02 +020057NOTE: In the interpreter's initialization phase, some globals are currently
58 initialized dynamically as needed. In the process Unicode objects may
59 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000060
61*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64#ifdef __cplusplus
65extern "C" {
66#endif
67
Victor Stinner8faf8212011-12-08 22:14:11 +010068/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
69#define MAX_UNICODE 0x10ffff
70
Victor Stinner910337b2011-10-03 03:20:16 +020071#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020072# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020073#else
74# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
75#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020076
Victor Stinnere90fe6a2011-10-01 16:48:13 +020077#define _PyUnicode_UTF8(op) \
78 (((PyCompactUnicodeObject*)(op))->utf8)
79#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020080 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 assert(PyUnicode_IS_READY(op)), \
82 PyUnicode_IS_COMPACT_ASCII(op) ? \
83 ((char*)((PyASCIIObject*)(op) + 1)) : \
84 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020085#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020086 (((PyCompactUnicodeObject*)(op))->utf8_length)
87#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020088 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 assert(PyUnicode_IS_READY(op)), \
90 PyUnicode_IS_COMPACT_ASCII(op) ? \
91 ((PyASCIIObject*)(op))->length : \
92 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020093#define _PyUnicode_WSTR(op) \
94 (((PyASCIIObject*)(op))->wstr)
95#define _PyUnicode_WSTR_LENGTH(op) \
96 (((PyCompactUnicodeObject*)(op))->wstr_length)
97#define _PyUnicode_LENGTH(op) \
98 (((PyASCIIObject *)(op))->length)
99#define _PyUnicode_STATE(op) \
100 (((PyASCIIObject *)(op))->state)
101#define _PyUnicode_HASH(op) \
102 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200103#define _PyUnicode_KIND(op) \
104 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200105 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_GET_LENGTH(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_DATA_ANY(op) \
110 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200130 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200131 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200132 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
133
Victor Stinner03490912011-10-03 23:45:12 +0200134/* true if the Unicode object has an allocated wstr memory block
135 (not shared with other data) */
136#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200137 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100148 to_type *_to = (to_type *)(to); \
149 const from_type *_iter = (from_type *)(begin); \
150 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200153 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Walter Dörwald16807132007-05-25 13:52:07 +0000165/* This dictionary holds all interned unicode strings. Note that references
166 to strings in this dictionary are *not* counted in the string's ob_refcnt.
167 When the interned string reaches a refcnt of 0 the string deallocation
168 function will delete the reference from this dictionary.
169
170 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000171 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000172*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200173static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000174
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000175/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200176static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200177
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179 do { \
180 if (unicode_empty != NULL) \
181 Py_INCREF(unicode_empty); \
182 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183 unicode_empty = PyUnicode_New(0, 0); \
184 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200185 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
187 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191#define _Py_RETURN_UNICODE_EMPTY() \
192 do { \
193 _Py_INCREF_UNICODE_EMPTY(); \
194 return unicode_empty; \
195 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200197/* Forward declaration */
198Py_LOCAL_INLINE(int)
199_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
200
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200206static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100242static int unicode_modifiable(PyObject *unicode);
243
Victor Stinnerfe226c02011-10-03 03:52:20 +0200244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100246_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200247static PyObject *
248_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
249static PyObject *
250_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
251
252static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100255 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
257
Alexander Belopolsky40018472011-02-26 01:02:56 +0000258static void
259raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300260 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100261 PyObject *unicode,
262 Py_ssize_t startpos, Py_ssize_t endpos,
263 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Same for linebreaks */
266static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000268/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* 0x000B, * LINE TABULATION */
270/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x001C, * FILE SEPARATOR */
275/* 0x001D, * GROUP SEPARATOR */
276/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 1, 1, 1, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000282
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000291};
292
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300293/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
294 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000296PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000298#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 /* This is actually an illegal character, so it should
302 not be passed to unichr. */
303 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000304#endif
305}
306
Victor Stinner910337b2011-10-03 03:20:16 +0200307#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200308int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100309_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200310{
311 PyASCIIObject *ascii;
312 unsigned int kind;
313
314 assert(PyUnicode_Check(op));
315
316 ascii = (PyASCIIObject *)op;
317 kind = ascii->state.kind;
318
Victor Stinnera3b334d2011-10-03 13:53:37 +0200319 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200325 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200326
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 if (ascii->state.compact == 1) {
328 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(kind == PyUnicode_1BYTE_KIND
330 || kind == PyUnicode_2BYTE_KIND
331 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200333 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100335 }
336 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
338
339 data = unicode->data.any;
340 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->length == 0);
342 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100346 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200347 assert(ascii->wstr != NULL);
348 assert(data == NULL);
349 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200391 void *data;
392 Py_UCS4 ch;
393
394 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 for (i=0; i < ascii->length; i++)
396 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 if (ch > maxchar)
399 maxchar = ch;
400 }
401 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100402 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 255);
405 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 else
407 assert(maxchar < 128);
408 }
Victor Stinner77faf692011-11-20 18:56:05 +0100409 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 assert(maxchar <= 0xFFFF);
412 }
413 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200414 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100415 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100416 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200417 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200418 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100423static PyObject*
424unicode_result_wchar(PyObject *unicode)
425{
426#ifndef Py_DEBUG
427 Py_ssize_t len;
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 len = _PyUnicode_WSTR_LENGTH(unicode);
430 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200432 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 }
434
435 if (len == 1) {
436 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100437 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
439 Py_DECREF(unicode);
440 return latin1_char;
441 }
442 }
443
444 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200445 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 return NULL;
447 }
448#else
Victor Stinneraa771272012-10-04 02:32:58 +0200449 assert(Py_REFCNT(unicode) == 1);
450
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100451 /* don't make the result ready in debug mode to ensure that the caller
452 makes the string ready before using it */
453 assert(_PyUnicode_CheckConsistency(unicode, 1));
454#endif
455 return unicode;
456}
457
458static PyObject*
459unicode_result_ready(PyObject *unicode)
460{
461 Py_ssize_t length;
462
463 length = PyUnicode_GET_LENGTH(unicode);
464 if (length == 0) {
465 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200467 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 }
469 return unicode_empty;
470 }
471
472 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200473 void *data = PyUnicode_DATA(unicode);
474 int kind = PyUnicode_KIND(unicode);
475 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 if (ch < 256) {
477 PyObject *latin1_char = unicode_latin1[ch];
478 if (latin1_char != NULL) {
479 if (unicode != latin1_char) {
480 Py_INCREF(latin1_char);
481 Py_DECREF(unicode);
482 }
483 return latin1_char;
484 }
485 else {
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 Py_INCREF(unicode);
488 unicode_latin1[ch] = unicode;
489 return unicode;
490 }
491 }
492 }
493
494 assert(_PyUnicode_CheckConsistency(unicode, 1));
495 return unicode;
496}
497
498static PyObject*
499unicode_result(PyObject *unicode)
500{
501 assert(_PyUnicode_CHECK(unicode));
502 if (PyUnicode_IS_READY(unicode))
503 return unicode_result_ready(unicode);
504 else
505 return unicode_result_wchar(unicode);
506}
507
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508static PyObject*
509unicode_result_unchanged(PyObject *unicode)
510{
511 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500512 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100513 return NULL;
514 Py_INCREF(unicode);
515 return unicode;
516 }
517 else
518 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100519 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100520}
521
Victor Stinner3a50e702011-10-18 21:21:00 +0200522#ifdef HAVE_MBCS
523static OSVERSIONINFOEX winver;
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526/* --- Bloom Filters ----------------------------------------------------- */
527
528/* stuff to implement simple "bloom filters" for Unicode characters.
529 to keep things simple, we use a single bitmask, using the least 5
530 bits from each unicode characters as the bit index. */
531
532/* the linebreak mask is set up by Unicode_Init below */
533
Antoine Pitrouf068f942010-01-13 14:19:12 +0000534#if LONG_BIT >= 128
535#define BLOOM_WIDTH 128
536#elif LONG_BIT >= 64
537#define BLOOM_WIDTH 64
538#elif LONG_BIT >= 32
539#define BLOOM_WIDTH 32
540#else
541#error "LONG_BIT is smaller than 32"
542#endif
543
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544#define BLOOM_MASK unsigned long
545
Serhiy Storchaka05997252013-01-26 12:14:02 +0200546static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Antoine Pitrouf068f942010-01-13 14:19:12 +0000548#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Benjamin Peterson29060642009-01-31 22:14:21 +0000550#define BLOOM_LINEBREAK(ch) \
551 ((ch) < 128U ? ascii_linebreak[(ch)] : \
552 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
Alexander Belopolsky40018472011-02-26 01:02:56 +0000554Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556{
Victor Stinnera85af502013-04-09 21:53:54 +0200557#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
558 do { \
559 TYPE *data = (TYPE *)PTR; \
560 TYPE *end = data + LEN; \
561 Py_UCS4 ch; \
562 for (; data != end; data++) { \
563 ch = *data; \
564 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
565 } \
566 break; \
567 } while (0)
568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 /* calculate simple bloom-style bitmask for a given unicode string */
570
Antoine Pitrouf068f942010-01-13 14:19:12 +0000571 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200574 switch (kind) {
575 case PyUnicode_1BYTE_KIND:
576 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
577 break;
578 case PyUnicode_2BYTE_KIND:
579 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
580 break;
581 case PyUnicode_4BYTE_KIND:
582 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
583 break;
584 default:
585 assert(0);
586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200588
589#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590}
591
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200592/* Compilation of templated routines */
593
594#include "stringlib/asciilib.h"
595#include "stringlib/fastsearch.h"
596#include "stringlib/partition.h"
597#include "stringlib/split.h"
598#include "stringlib/count.h"
599#include "stringlib/find.h"
600#include "stringlib/find_max_char.h"
601#include "stringlib/localeutil.h"
602#include "stringlib/undef.h"
603
604#include "stringlib/ucs1lib.h"
605#include "stringlib/fastsearch.h"
606#include "stringlib/partition.h"
607#include "stringlib/split.h"
608#include "stringlib/count.h"
609#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300610#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200611#include "stringlib/find_max_char.h"
612#include "stringlib/localeutil.h"
613#include "stringlib/undef.h"
614
615#include "stringlib/ucs2lib.h"
616#include "stringlib/fastsearch.h"
617#include "stringlib/partition.h"
618#include "stringlib/split.h"
619#include "stringlib/count.h"
620#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300621#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200622#include "stringlib/find_max_char.h"
623#include "stringlib/localeutil.h"
624#include "stringlib/undef.h"
625
626#include "stringlib/ucs4lib.h"
627#include "stringlib/fastsearch.h"
628#include "stringlib/partition.h"
629#include "stringlib/split.h"
630#include "stringlib/count.h"
631#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300632#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200633#include "stringlib/find_max_char.h"
634#include "stringlib/localeutil.h"
635#include "stringlib/undef.h"
636
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637#include "stringlib/unicodedefs.h"
638#include "stringlib/fastsearch.h"
639#include "stringlib/count.h"
640#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100641#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* --- Unicode Object ----------------------------------------------------- */
644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200646fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
649 Py_ssize_t size, Py_UCS4 ch,
650 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200652 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
653
654 switch (kind) {
655 case PyUnicode_1BYTE_KIND:
656 {
657 Py_UCS1 ch1 = (Py_UCS1) ch;
658 if (ch1 == ch)
659 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
660 else
661 return -1;
662 }
663 case PyUnicode_2BYTE_KIND:
664 {
665 Py_UCS2 ch2 = (Py_UCS2) ch;
666 if (ch2 == ch)
667 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
668 else
669 return -1;
670 }
671 case PyUnicode_4BYTE_KIND:
672 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
673 default:
674 assert(0);
675 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677}
678
Victor Stinnerafffce42012-10-03 23:03:17 +0200679#ifdef Py_DEBUG
680/* Fill the data of an Unicode string with invalid characters to detect bugs
681 earlier.
682
683 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
684 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
685 invalid character in Unicode 6.0. */
686static void
687unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
688{
689 int kind = PyUnicode_KIND(unicode);
690 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
691 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
692 if (length <= old_length)
693 return;
694 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
695}
696#endif
697
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698static PyObject*
699resize_compact(PyObject *unicode, Py_ssize_t length)
700{
701 Py_ssize_t char_size;
702 Py_ssize_t struct_size;
703 Py_ssize_t new_size;
704 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100705 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200706#ifdef Py_DEBUG
707 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
708#endif
709
Victor Stinner79891572012-05-03 13:43:07 +0200710 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100712 assert(PyUnicode_IS_COMPACT(unicode));
713
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200714 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100715 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 struct_size = sizeof(PyASCIIObject);
717 else
718 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200719 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
722 PyErr_NoMemory();
723 return NULL;
724 }
725 new_size = (struct_size + (length + 1) * char_size);
726
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200727 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
728 PyObject_DEL(_PyUnicode_UTF8(unicode));
729 _PyUnicode_UTF8(unicode) = NULL;
730 _PyUnicode_UTF8_LENGTH(unicode) = 0;
731 }
Victor Stinner84def372011-12-11 20:04:56 +0100732 _Py_DEC_REFTOTAL;
733 _Py_ForgetReference(unicode);
734
735 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
736 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100737 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 PyErr_NoMemory();
739 return NULL;
740 }
Victor Stinner84def372011-12-11 20:04:56 +0100741 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100743
Victor Stinnerfe226c02011-10-03 03:52:20 +0200744 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200745 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200746 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100747 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200748 _PyUnicode_WSTR_LENGTH(unicode) = length;
749 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100750 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
751 PyObject_DEL(_PyUnicode_WSTR(unicode));
752 _PyUnicode_WSTR(unicode) = NULL;
753 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200754#ifdef Py_DEBUG
755 unicode_fill_invalid(unicode, old_length);
756#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200757 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
758 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200759 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 return unicode;
761}
762
Alexander Belopolsky40018472011-02-26 01:02:56 +0000763static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200764resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000765{
Victor Stinner95663112011-10-04 01:03:50 +0200766 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100767 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200768 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000770
Victor Stinnerfe226c02011-10-03 03:52:20 +0200771 if (PyUnicode_IS_READY(unicode)) {
772 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200773 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200775#ifdef Py_DEBUG
776 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
777#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200778
779 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200780 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200781 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
782 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200783
784 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
785 PyErr_NoMemory();
786 return -1;
787 }
788 new_size = (length + 1) * char_size;
789
Victor Stinner7a9105a2011-12-12 00:13:42 +0100790 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
791 {
792 PyObject_DEL(_PyUnicode_UTF8(unicode));
793 _PyUnicode_UTF8(unicode) = NULL;
794 _PyUnicode_UTF8_LENGTH(unicode) = 0;
795 }
796
Victor Stinnerfe226c02011-10-03 03:52:20 +0200797 data = (PyObject *)PyObject_REALLOC(data, new_size);
798 if (data == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200803 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200804 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200805 _PyUnicode_WSTR_LENGTH(unicode) = length;
806 }
807 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200808 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200809 _PyUnicode_UTF8_LENGTH(unicode) = length;
810 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200811 _PyUnicode_LENGTH(unicode) = length;
812 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200813#ifdef Py_DEBUG
814 unicode_fill_invalid(unicode, old_length);
815#endif
Victor Stinner95663112011-10-04 01:03:50 +0200816 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200817 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200818 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200819 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200820 }
Victor Stinner95663112011-10-04 01:03:50 +0200821 assert(_PyUnicode_WSTR(unicode) != NULL);
822
823 /* check for integer overflow */
824 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
825 PyErr_NoMemory();
826 return -1;
827 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100828 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200829 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100830 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200831 if (!wstr) {
832 PyErr_NoMemory();
833 return -1;
834 }
835 _PyUnicode_WSTR(unicode) = wstr;
836 _PyUnicode_WSTR(unicode)[length] = 0;
837 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200838 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000839 return 0;
840}
841
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842static PyObject*
843resize_copy(PyObject *unicode, Py_ssize_t length)
844{
845 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100846 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200847 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100848
Benjamin Petersonbac79492012-01-14 13:34:47 -0500849 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100850 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200851
852 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
853 if (copy == NULL)
854 return NULL;
855
856 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200857 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200858 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200859 }
860 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200861 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100862
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200863 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200864 if (w == NULL)
865 return NULL;
866 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
867 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200868 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
869 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200870 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200871 }
872}
873
Guido van Rossumd57fd912000-03-10 22:53:23 +0000874/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000875 Ux0000 terminated; some code (e.g. new_identifier)
876 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000877
878 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000879 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880
881*/
882
Alexander Belopolsky40018472011-02-26 01:02:56 +0000883static PyUnicodeObject *
884_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200886 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200887 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888
Thomas Wouters477c8d52006-05-27 19:21:47 +0000889 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000890 if (length == 0 && unicode_empty != NULL) {
891 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200892 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000893 }
894
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000895 /* Ensure we won't overflow the size. */
896 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
897 return (PyUnicodeObject *)PyErr_NoMemory();
898 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200899 if (length < 0) {
900 PyErr_SetString(PyExc_SystemError,
901 "Negative size passed to _PyUnicode_New");
902 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000903 }
904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
906 if (unicode == NULL)
907 return NULL;
908 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100909
910 _PyUnicode_WSTR_LENGTH(unicode) = length;
911 _PyUnicode_HASH(unicode) = -1;
912 _PyUnicode_STATE(unicode).interned = 0;
913 _PyUnicode_STATE(unicode).kind = 0;
914 _PyUnicode_STATE(unicode).compact = 0;
915 _PyUnicode_STATE(unicode).ready = 0;
916 _PyUnicode_STATE(unicode).ascii = 0;
917 _PyUnicode_DATA_ANY(unicode) = NULL;
918 _PyUnicode_LENGTH(unicode) = 0;
919 _PyUnicode_UTF8(unicode) = NULL;
920 _PyUnicode_UTF8_LENGTH(unicode) = 0;
921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
923 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100924 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000925 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100926 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000927 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200928
Jeremy Hyltond8082792003-09-16 19:41:39 +0000929 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000930 * the caller fails before initializing str -- unicode_resize()
931 * reads str[0], and the Keep-Alive optimization can keep memory
932 * allocated for str alive across a call to unicode_dealloc(unicode).
933 * We don't want unicode_resize to read uninitialized memory in
934 * that case.
935 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200936 _PyUnicode_WSTR(unicode)[0] = 0;
937 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100938
Victor Stinner7931d9a2011-11-04 00:22:48 +0100939 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000940 return unicode;
941}
942
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943static const char*
944unicode_kind_name(PyObject *unicode)
945{
Victor Stinner42dfd712011-10-03 14:41:45 +0200946 /* don't check consistency: unicode_kind_name() is called from
947 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 if (!PyUnicode_IS_COMPACT(unicode))
949 {
950 if (!PyUnicode_IS_READY(unicode))
951 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600952 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200953 {
954 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200955 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200956 return "legacy ascii";
957 else
958 return "legacy latin1";
959 case PyUnicode_2BYTE_KIND:
960 return "legacy UCS2";
961 case PyUnicode_4BYTE_KIND:
962 return "legacy UCS4";
963 default:
964 return "<legacy invalid kind>";
965 }
966 }
967 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600968 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 return "ascii";
972 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200973 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200974 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200975 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200976 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200977 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200978 default:
979 return "<invalid compact kind>";
980 }
981}
982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984/* Functions wrapping macros for use in debugger */
985char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200986 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987}
988
989void *_PyUnicode_compact_data(void *unicode) {
990 return _PyUnicode_COMPACT_DATA(unicode);
991}
992void *_PyUnicode_data(void *unicode){
993 printf("obj %p\n", unicode);
994 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
995 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
996 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
997 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
998 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
999 return PyUnicode_DATA(unicode);
1000}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001001
1002void
1003_PyUnicode_Dump(PyObject *op)
1004{
1005 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001006 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1007 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1008 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001009
Victor Stinnera849a4b2011-10-03 12:12:11 +02001010 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001011 {
1012 if (ascii->state.ascii)
1013 data = (ascii + 1);
1014 else
1015 data = (compact + 1);
1016 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001017 else
1018 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001019 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1020 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001021
Victor Stinnera849a4b2011-10-03 12:12:11 +02001022 if (ascii->wstr == data)
1023 printf("shared ");
1024 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001025
Victor Stinnera3b334d2011-10-03 13:53:37 +02001026 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001027 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001028 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1029 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001030 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1031 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001032 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001033 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001034}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035#endif
1036
1037PyObject *
1038PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1039{
1040 PyObject *obj;
1041 PyCompactUnicodeObject *unicode;
1042 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001043 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001044 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001045 Py_ssize_t char_size;
1046 Py_ssize_t struct_size;
1047
1048 /* Optimization for empty strings */
1049 if (size == 0 && unicode_empty != NULL) {
1050 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001051 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 }
1053
Victor Stinner9e9d6892011-10-04 01:02:02 +02001054 is_ascii = 0;
1055 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 struct_size = sizeof(PyCompactUnicodeObject);
1057 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001058 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059 char_size = 1;
1060 is_ascii = 1;
1061 struct_size = sizeof(PyASCIIObject);
1062 }
1063 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001064 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001065 char_size = 1;
1066 }
1067 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001068 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 char_size = 2;
1070 if (sizeof(wchar_t) == 2)
1071 is_sharing = 1;
1072 }
1073 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001074 if (maxchar > MAX_UNICODE) {
1075 PyErr_SetString(PyExc_SystemError,
1076 "invalid maximum character passed to PyUnicode_New");
1077 return NULL;
1078 }
Victor Stinner8f825062012-04-27 13:55:39 +02001079 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001080 char_size = 4;
1081 if (sizeof(wchar_t) == 4)
1082 is_sharing = 1;
1083 }
1084
1085 /* Ensure we won't overflow the size. */
1086 if (size < 0) {
1087 PyErr_SetString(PyExc_SystemError,
1088 "Negative size passed to PyUnicode_New");
1089 return NULL;
1090 }
1091 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1092 return PyErr_NoMemory();
1093
1094 /* Duplicated allocation code from _PyObject_New() instead of a call to
1095 * PyObject_New() so we are able to allocate space for the object and
1096 * it's data buffer.
1097 */
1098 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1099 if (obj == NULL)
1100 return PyErr_NoMemory();
1101 obj = PyObject_INIT(obj, &PyUnicode_Type);
1102 if (obj == NULL)
1103 return NULL;
1104
1105 unicode = (PyCompactUnicodeObject *)obj;
1106 if (is_ascii)
1107 data = ((PyASCIIObject*)obj) + 1;
1108 else
1109 data = unicode + 1;
1110 _PyUnicode_LENGTH(unicode) = size;
1111 _PyUnicode_HASH(unicode) = -1;
1112 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001113 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001114 _PyUnicode_STATE(unicode).compact = 1;
1115 _PyUnicode_STATE(unicode).ready = 1;
1116 _PyUnicode_STATE(unicode).ascii = is_ascii;
1117 if (is_ascii) {
1118 ((char*)data)[size] = 0;
1119 _PyUnicode_WSTR(unicode) = NULL;
1120 }
Victor Stinner8f825062012-04-27 13:55:39 +02001121 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001122 ((char*)data)[size] = 0;
1123 _PyUnicode_WSTR(unicode) = NULL;
1124 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001126 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001127 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128 else {
1129 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001130 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001131 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001132 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001133 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134 ((Py_UCS4*)data)[size] = 0;
1135 if (is_sharing) {
1136 _PyUnicode_WSTR_LENGTH(unicode) = size;
1137 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1138 }
1139 else {
1140 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1141 _PyUnicode_WSTR(unicode) = NULL;
1142 }
1143 }
Victor Stinner8f825062012-04-27 13:55:39 +02001144#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001145 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001146#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001147 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148 return obj;
1149}
1150
1151#if SIZEOF_WCHAR_T == 2
1152/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1153 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001154 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001155
1156 This function assumes that unicode can hold one more code point than wstr
1157 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001158static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001160 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161{
1162 const wchar_t *iter;
1163 Py_UCS4 *ucs4_out;
1164
Victor Stinner910337b2011-10-03 03:20:16 +02001165 assert(unicode != NULL);
1166 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1168 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1169
1170 for (iter = begin; iter < end; ) {
1171 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1172 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001173 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1174 && (iter+1) < end
1175 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176 {
Victor Stinner551ac952011-11-29 22:58:13 +01001177 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 iter += 2;
1179 }
1180 else {
1181 *ucs4_out++ = *iter;
1182 iter++;
1183 }
1184 }
1185 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1186 _PyUnicode_GET_LENGTH(unicode)));
1187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001188}
1189#endif
1190
Victor Stinnercd9950f2011-10-02 00:34:53 +02001191static int
Victor Stinner488fa492011-12-12 00:01:39 +01001192unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001193{
Victor Stinner488fa492011-12-12 00:01:39 +01001194 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001195 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001196 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001197 return -1;
1198 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001199 return 0;
1200}
1201
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001202static int
1203_copy_characters(PyObject *to, Py_ssize_t to_start,
1204 PyObject *from, Py_ssize_t from_start,
1205 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001207 unsigned int from_kind, to_kind;
1208 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209
Victor Stinneree4544c2012-05-09 22:24:08 +02001210 assert(0 <= how_many);
1211 assert(0 <= from_start);
1212 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001213 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001214 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001215 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216
Victor Stinnerd3f08822012-05-29 12:57:52 +02001217 assert(PyUnicode_Check(to));
1218 assert(PyUnicode_IS_READY(to));
1219 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1220
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001221 if (how_many == 0)
1222 return 0;
1223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001225 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001226 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001227 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228
Victor Stinnerf1852262012-06-16 16:38:26 +02001229#ifdef Py_DEBUG
1230 if (!check_maxchar
1231 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1232 {
1233 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1234 Py_UCS4 ch;
1235 Py_ssize_t i;
1236 for (i=0; i < how_many; i++) {
1237 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1238 assert(ch <= to_maxchar);
1239 }
1240 }
1241#endif
1242
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001243 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001244 if (check_maxchar
1245 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1246 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001247 /* Writing Latin-1 characters into an ASCII string requires to
1248 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001249 Py_UCS4 max_char;
1250 max_char = ucs1lib_find_max_char(from_data,
1251 (Py_UCS1*)from_data + how_many);
1252 if (max_char >= 128)
1253 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001254 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001255 Py_MEMCPY((char*)to_data + to_kind * to_start,
1256 (char*)from_data + from_kind * from_start,
1257 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001259 else if (from_kind == PyUnicode_1BYTE_KIND
1260 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001261 {
1262 _PyUnicode_CONVERT_BYTES(
1263 Py_UCS1, Py_UCS2,
1264 PyUnicode_1BYTE_DATA(from) + from_start,
1265 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1266 PyUnicode_2BYTE_DATA(to) + to_start
1267 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001268 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001269 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001270 && to_kind == PyUnicode_4BYTE_KIND)
1271 {
1272 _PyUnicode_CONVERT_BYTES(
1273 Py_UCS1, Py_UCS4,
1274 PyUnicode_1BYTE_DATA(from) + from_start,
1275 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1276 PyUnicode_4BYTE_DATA(to) + to_start
1277 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001278 }
1279 else if (from_kind == PyUnicode_2BYTE_KIND
1280 && to_kind == PyUnicode_4BYTE_KIND)
1281 {
1282 _PyUnicode_CONVERT_BYTES(
1283 Py_UCS2, Py_UCS4,
1284 PyUnicode_2BYTE_DATA(from) + from_start,
1285 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1286 PyUnicode_4BYTE_DATA(to) + to_start
1287 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001288 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001289 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001290 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1291
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001292 if (!check_maxchar) {
1293 if (from_kind == PyUnicode_2BYTE_KIND
1294 && to_kind == PyUnicode_1BYTE_KIND)
1295 {
1296 _PyUnicode_CONVERT_BYTES(
1297 Py_UCS2, Py_UCS1,
1298 PyUnicode_2BYTE_DATA(from) + from_start,
1299 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1300 PyUnicode_1BYTE_DATA(to) + to_start
1301 );
1302 }
1303 else if (from_kind == PyUnicode_4BYTE_KIND
1304 && to_kind == PyUnicode_1BYTE_KIND)
1305 {
1306 _PyUnicode_CONVERT_BYTES(
1307 Py_UCS4, Py_UCS1,
1308 PyUnicode_4BYTE_DATA(from) + from_start,
1309 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1310 PyUnicode_1BYTE_DATA(to) + to_start
1311 );
1312 }
1313 else if (from_kind == PyUnicode_4BYTE_KIND
1314 && to_kind == PyUnicode_2BYTE_KIND)
1315 {
1316 _PyUnicode_CONVERT_BYTES(
1317 Py_UCS4, Py_UCS2,
1318 PyUnicode_4BYTE_DATA(from) + from_start,
1319 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1320 PyUnicode_2BYTE_DATA(to) + to_start
1321 );
1322 }
1323 else {
1324 assert(0);
1325 return -1;
1326 }
1327 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001328 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001329 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001330 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001331 Py_ssize_t i;
1332
Victor Stinnera0702ab2011-09-29 14:14:38 +02001333 for (i=0; i < how_many; i++) {
1334 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001335 if (ch > to_maxchar)
1336 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001337 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1338 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001339 }
1340 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001341 return 0;
1342}
1343
Victor Stinnerd3f08822012-05-29 12:57:52 +02001344void
1345_PyUnicode_FastCopyCharacters(
1346 PyObject *to, Py_ssize_t to_start,
1347 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001348{
1349 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1350}
1351
1352Py_ssize_t
1353PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1354 PyObject *from, Py_ssize_t from_start,
1355 Py_ssize_t how_many)
1356{
1357 int err;
1358
1359 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1360 PyErr_BadInternalCall();
1361 return -1;
1362 }
1363
Benjamin Petersonbac79492012-01-14 13:34:47 -05001364 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001365 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001366 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001367 return -1;
1368
Victor Stinnerd3f08822012-05-29 12:57:52 +02001369 if (from_start < 0) {
1370 PyErr_SetString(PyExc_IndexError, "string index out of range");
1371 return -1;
1372 }
1373 if (to_start < 0) {
1374 PyErr_SetString(PyExc_IndexError, "string index out of range");
1375 return -1;
1376 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1378 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1379 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001380 "Cannot write %zi characters at %zi "
1381 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001382 how_many, to_start, PyUnicode_GET_LENGTH(to));
1383 return -1;
1384 }
1385
1386 if (how_many == 0)
1387 return 0;
1388
Victor Stinner488fa492011-12-12 00:01:39 +01001389 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001390 return -1;
1391
1392 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1393 if (err) {
1394 PyErr_Format(PyExc_SystemError,
1395 "Cannot copy %s characters "
1396 "into a string of %s characters",
1397 unicode_kind_name(from),
1398 unicode_kind_name(to));
1399 return -1;
1400 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001401 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402}
1403
Victor Stinner17222162011-09-28 22:15:37 +02001404/* Find the maximum code point and count the number of surrogate pairs so a
1405 correct string length can be computed before converting a string to UCS4.
1406 This function counts single surrogates as a character and not as a pair.
1407
1408 Return 0 on success, or -1 on error. */
1409static int
1410find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1411 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412{
1413 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001414 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415
Victor Stinnerc53be962011-10-02 21:33:54 +02001416 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001417 *num_surrogates = 0;
1418 *maxchar = 0;
1419
1420 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001422 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1423 && (iter+1) < end
1424 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1425 {
1426 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1427 ++(*num_surrogates);
1428 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429 }
1430 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001431#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001432 {
1433 ch = *iter;
1434 iter++;
1435 }
1436 if (ch > *maxchar) {
1437 *maxchar = ch;
1438 if (*maxchar > MAX_UNICODE) {
1439 PyErr_Format(PyExc_ValueError,
1440 "character U+%x is not in range [U+0000; U+10ffff]",
1441 ch);
1442 return -1;
1443 }
1444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445 }
1446 return 0;
1447}
1448
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001449int
1450_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001451{
1452 wchar_t *end;
1453 Py_UCS4 maxchar = 0;
1454 Py_ssize_t num_surrogates;
1455#if SIZEOF_WCHAR_T == 2
1456 Py_ssize_t length_wo_surrogates;
1457#endif
1458
Georg Brandl7597add2011-10-05 16:36:47 +02001459 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001460 strings were created using _PyObject_New() and where no canonical
1461 representation (the str field) has been set yet aka strings
1462 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001463 assert(_PyUnicode_CHECK(unicode));
1464 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001466 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001467 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001468 /* Actually, it should neither be interned nor be anything else: */
1469 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001471 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001472 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001473 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001475
1476 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001477 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1478 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001479 PyErr_NoMemory();
1480 return -1;
1481 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001482 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001483 _PyUnicode_WSTR(unicode), end,
1484 PyUnicode_1BYTE_DATA(unicode));
1485 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1486 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1487 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1488 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001489 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001490 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001491 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 }
1493 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001494 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001495 _PyUnicode_UTF8(unicode) = NULL;
1496 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001497 }
1498 PyObject_FREE(_PyUnicode_WSTR(unicode));
1499 _PyUnicode_WSTR(unicode) = NULL;
1500 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1501 }
1502 /* In this case we might have to convert down from 4-byte native
1503 wchar_t to 2-byte unicode. */
1504 else if (maxchar < 65536) {
1505 assert(num_surrogates == 0 &&
1506 "FindMaxCharAndNumSurrogatePairs() messed up");
1507
Victor Stinner506f5922011-09-28 22:34:18 +02001508#if SIZEOF_WCHAR_T == 2
1509 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001510 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001511 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1512 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1513 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001514 _PyUnicode_UTF8(unicode) = NULL;
1515 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001516#else
1517 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001518 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001519 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001520 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001521 PyErr_NoMemory();
1522 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001523 }
Victor Stinner506f5922011-09-28 22:34:18 +02001524 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1525 _PyUnicode_WSTR(unicode), end,
1526 PyUnicode_2BYTE_DATA(unicode));
1527 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1528 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1529 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001530 _PyUnicode_UTF8(unicode) = NULL;
1531 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001532 PyObject_FREE(_PyUnicode_WSTR(unicode));
1533 _PyUnicode_WSTR(unicode) = NULL;
1534 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1535#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001536 }
1537 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1538 else {
1539#if SIZEOF_WCHAR_T == 2
1540 /* in case the native representation is 2-bytes, we need to allocate a
1541 new normalized 4-byte version. */
1542 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001543 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1544 PyErr_NoMemory();
1545 return -1;
1546 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001547 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1548 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001549 PyErr_NoMemory();
1550 return -1;
1551 }
1552 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1553 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001554 _PyUnicode_UTF8(unicode) = NULL;
1555 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001556 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1557 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001558 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001559 PyObject_FREE(_PyUnicode_WSTR(unicode));
1560 _PyUnicode_WSTR(unicode) = NULL;
1561 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1562#else
1563 assert(num_surrogates == 0);
1564
Victor Stinnerc3c74152011-10-02 20:39:55 +02001565 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001567 _PyUnicode_UTF8(unicode) = NULL;
1568 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001569 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1570#endif
1571 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1572 }
1573 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001574 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001575 return 0;
1576}
1577
Alexander Belopolsky40018472011-02-26 01:02:56 +00001578static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001579unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001580{
Walter Dörwald16807132007-05-25 13:52:07 +00001581 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001582 case SSTATE_NOT_INTERNED:
1583 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001584
Benjamin Peterson29060642009-01-31 22:14:21 +00001585 case SSTATE_INTERNED_MORTAL:
1586 /* revive dead object temporarily for DelItem */
1587 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001588 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001589 Py_FatalError(
1590 "deletion of interned string failed");
1591 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001592
Benjamin Peterson29060642009-01-31 22:14:21 +00001593 case SSTATE_INTERNED_IMMORTAL:
1594 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001595
Benjamin Peterson29060642009-01-31 22:14:21 +00001596 default:
1597 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001598 }
1599
Victor Stinner03490912011-10-03 23:45:12 +02001600 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001602 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001603 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001604 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1605 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001607 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001608}
1609
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001610#ifdef Py_DEBUG
1611static int
1612unicode_is_singleton(PyObject *unicode)
1613{
1614 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1615 if (unicode == unicode_empty)
1616 return 1;
1617 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1618 {
1619 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1620 if (ch < 256 && unicode_latin1[ch] == unicode)
1621 return 1;
1622 }
1623 return 0;
1624}
1625#endif
1626
Alexander Belopolsky40018472011-02-26 01:02:56 +00001627static int
Victor Stinner488fa492011-12-12 00:01:39 +01001628unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001629{
Victor Stinner488fa492011-12-12 00:01:39 +01001630 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001631 if (Py_REFCNT(unicode) != 1)
1632 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001633 if (_PyUnicode_HASH(unicode) != -1)
1634 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001635 if (PyUnicode_CHECK_INTERNED(unicode))
1636 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001637 if (!PyUnicode_CheckExact(unicode))
1638 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001639#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001640 /* singleton refcount is greater than 1 */
1641 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001642#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001643 return 1;
1644}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001645
Victor Stinnerfe226c02011-10-03 03:52:20 +02001646static int
1647unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1648{
1649 PyObject *unicode;
1650 Py_ssize_t old_length;
1651
1652 assert(p_unicode != NULL);
1653 unicode = *p_unicode;
1654
1655 assert(unicode != NULL);
1656 assert(PyUnicode_Check(unicode));
1657 assert(0 <= length);
1658
Victor Stinner910337b2011-10-03 03:20:16 +02001659 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001660 old_length = PyUnicode_WSTR_LENGTH(unicode);
1661 else
1662 old_length = PyUnicode_GET_LENGTH(unicode);
1663 if (old_length == length)
1664 return 0;
1665
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001666 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001667 _Py_INCREF_UNICODE_EMPTY();
1668 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001670 Py_DECREF(*p_unicode);
1671 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001672 return 0;
1673 }
1674
Victor Stinner488fa492011-12-12 00:01:39 +01001675 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001676 PyObject *copy = resize_copy(unicode, length);
1677 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001678 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001679 Py_DECREF(*p_unicode);
1680 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001681 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001682 }
1683
Victor Stinnerfe226c02011-10-03 03:52:20 +02001684 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001685 PyObject *new_unicode = resize_compact(unicode, length);
1686 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001687 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001688 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001689 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001690 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001691 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001692}
1693
Alexander Belopolsky40018472011-02-26 01:02:56 +00001694int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001696{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001697 PyObject *unicode;
1698 if (p_unicode == NULL) {
1699 PyErr_BadInternalCall();
1700 return -1;
1701 }
1702 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001703 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001704 {
1705 PyErr_BadInternalCall();
1706 return -1;
1707 }
1708 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001709}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001710
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001711/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001712
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001713 WARNING: The function doesn't copy the terminating null character and
1714 doesn't check the maximum character (may write a latin1 character in an
1715 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001716static void
1717unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1718 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001719{
1720 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1721 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001722 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001723
1724 switch (kind) {
1725 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001726 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001727#ifdef Py_DEBUG
1728 if (PyUnicode_IS_ASCII(unicode)) {
1729 Py_UCS4 maxchar = ucs1lib_find_max_char(
1730 (const Py_UCS1*)str,
1731 (const Py_UCS1*)str + len);
1732 assert(maxchar < 128);
1733 }
1734#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001735 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001736 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001737 }
1738 case PyUnicode_2BYTE_KIND: {
1739 Py_UCS2 *start = (Py_UCS2 *)data + index;
1740 Py_UCS2 *ucs2 = start;
1741 assert(index <= PyUnicode_GET_LENGTH(unicode));
1742
Victor Stinner184252a2012-06-16 02:57:41 +02001743 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001744 *ucs2 = (Py_UCS2)*str;
1745
1746 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001747 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001748 }
1749 default: {
1750 Py_UCS4 *start = (Py_UCS4 *)data + index;
1751 Py_UCS4 *ucs4 = start;
1752 assert(kind == PyUnicode_4BYTE_KIND);
1753 assert(index <= PyUnicode_GET_LENGTH(unicode));
1754
Victor Stinner184252a2012-06-16 02:57:41 +02001755 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001756 *ucs4 = (Py_UCS4)*str;
1757
1758 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001759 }
1760 }
1761}
1762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001763static PyObject*
1764get_latin1_char(unsigned char ch)
1765{
Victor Stinnera464fc12011-10-02 20:39:30 +02001766 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001768 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 if (!unicode)
1770 return NULL;
1771 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001772 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 unicode_latin1[ch] = unicode;
1774 }
1775 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001776 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001777}
1778
Victor Stinner985a82a2014-01-03 12:53:47 +01001779static PyObject*
1780unicode_char(Py_UCS4 ch)
1781{
1782 PyObject *unicode;
1783
1784 assert(ch <= MAX_UNICODE);
1785
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001786 if (ch < 256)
1787 return get_latin1_char(ch);
1788
Victor Stinner985a82a2014-01-03 12:53:47 +01001789 unicode = PyUnicode_New(1, ch);
1790 if (unicode == NULL)
1791 return NULL;
1792 switch (PyUnicode_KIND(unicode)) {
1793 case PyUnicode_1BYTE_KIND:
1794 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1795 break;
1796 case PyUnicode_2BYTE_KIND:
1797 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1798 break;
1799 default:
1800 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1801 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1802 }
1803 assert(_PyUnicode_CheckConsistency(unicode, 1));
1804 return unicode;
1805}
1806
Alexander Belopolsky40018472011-02-26 01:02:56 +00001807PyObject *
1808PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001809{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001810 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 Py_UCS4 maxchar = 0;
1812 Py_ssize_t num_surrogates;
1813
1814 if (u == NULL)
1815 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001816
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001817 /* If the Unicode data is known at construction time, we can apply
1818 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001820 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001821 if (size == 0)
1822 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001823
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 /* Single character Unicode objects in the Latin-1 range are
1825 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001826 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001827 return get_latin1_char((unsigned char)*u);
1828
1829 /* If not empty and not single character, copy the Unicode data
1830 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001831 if (find_maxchar_surrogates(u, u + size,
1832 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 return NULL;
1834
Victor Stinner8faf8212011-12-08 22:14:11 +01001835 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001836 if (!unicode)
1837 return NULL;
1838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001839 switch (PyUnicode_KIND(unicode)) {
1840 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001841 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001842 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1843 break;
1844 case PyUnicode_2BYTE_KIND:
1845#if Py_UNICODE_SIZE == 2
1846 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1847#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001848 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1850#endif
1851 break;
1852 case PyUnicode_4BYTE_KIND:
1853#if SIZEOF_WCHAR_T == 2
1854 /* This is the only case which has to process surrogates, thus
1855 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001856 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857#else
1858 assert(num_surrogates == 0);
1859 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1860#endif
1861 break;
1862 default:
1863 assert(0 && "Impossible state");
1864 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001865
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001866 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001867}
1868
Alexander Belopolsky40018472011-02-26 01:02:56 +00001869PyObject *
1870PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001871{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001872 if (size < 0) {
1873 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001874 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001875 return NULL;
1876 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001877 if (u != NULL)
1878 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1879 else
1880 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001881}
1882
Alexander Belopolsky40018472011-02-26 01:02:56 +00001883PyObject *
1884PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001885{
1886 size_t size = strlen(u);
1887 if (size > PY_SSIZE_T_MAX) {
1888 PyErr_SetString(PyExc_OverflowError, "input too long");
1889 return NULL;
1890 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001891 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001892}
1893
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001894PyObject *
1895_PyUnicode_FromId(_Py_Identifier *id)
1896{
1897 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001898 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1899 strlen(id->string),
1900 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001901 if (!id->object)
1902 return NULL;
1903 PyUnicode_InternInPlace(&id->object);
1904 assert(!id->next);
1905 id->next = static_strings;
1906 static_strings = id;
1907 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001908 return id->object;
1909}
1910
1911void
1912_PyUnicode_ClearStaticStrings()
1913{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001914 _Py_Identifier *tmp, *s = static_strings;
1915 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001916 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001917 tmp = s->next;
1918 s->next = NULL;
1919 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001920 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001921 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001922}
1923
Benjamin Peterson0df54292012-03-26 14:50:32 -04001924/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001925
Victor Stinnerd3f08822012-05-29 12:57:52 +02001926PyObject*
1927_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001928{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001929 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001930 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001931 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001932#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001933 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001934#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001935 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001936 }
Victor Stinner785938e2011-12-11 20:09:03 +01001937 unicode = PyUnicode_New(size, 127);
1938 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001939 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001940 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1941 assert(_PyUnicode_CheckConsistency(unicode, 1));
1942 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001943}
1944
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001945static Py_UCS4
1946kind_maxchar_limit(unsigned int kind)
1947{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001948 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001949 case PyUnicode_1BYTE_KIND:
1950 return 0x80;
1951 case PyUnicode_2BYTE_KIND:
1952 return 0x100;
1953 case PyUnicode_4BYTE_KIND:
1954 return 0x10000;
1955 default:
1956 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001957 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001958 }
1959}
1960
Victor Stinnere6abb482012-05-02 01:15:40 +02001961Py_LOCAL_INLINE(Py_UCS4)
1962align_maxchar(Py_UCS4 maxchar)
1963{
1964 if (maxchar <= 127)
1965 return 127;
1966 else if (maxchar <= 255)
1967 return 255;
1968 else if (maxchar <= 65535)
1969 return 65535;
1970 else
1971 return MAX_UNICODE;
1972}
1973
Victor Stinner702c7342011-10-05 13:50:52 +02001974static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001975_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001978 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001979
Serhiy Storchaka678db842013-01-26 12:16:36 +02001980 if (size == 0)
1981 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001982 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001983 if (size == 1)
1984 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001985
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001986 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001987 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988 if (!res)
1989 return NULL;
1990 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001991 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001993}
1994
Victor Stinnere57b1c02011-09-28 22:20:48 +02001995static PyObject*
1996_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997{
1998 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001999 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002000
Serhiy Storchaka678db842013-01-26 12:16:36 +02002001 if (size == 0)
2002 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002003 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002004 if (size == 1)
2005 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002006
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002007 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002008 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 if (!res)
2010 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002011 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002013 else {
2014 _PyUnicode_CONVERT_BYTES(
2015 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2016 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002017 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 return res;
2019}
2020
Victor Stinnere57b1c02011-09-28 22:20:48 +02002021static PyObject*
2022_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002023{
2024 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002025 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002026
Serhiy Storchaka678db842013-01-26 12:16:36 +02002027 if (size == 0)
2028 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002029 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002030 if (size == 1)
2031 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002032
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002033 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002034 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 if (!res)
2036 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002037 if (max_char < 256)
2038 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2039 PyUnicode_1BYTE_DATA(res));
2040 else if (max_char < 0x10000)
2041 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2042 PyUnicode_2BYTE_DATA(res));
2043 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002045 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002046 return res;
2047}
2048
2049PyObject*
2050PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2051{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002052 if (size < 0) {
2053 PyErr_SetString(PyExc_ValueError, "size must be positive");
2054 return NULL;
2055 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002056 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002058 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002060 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002062 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002063 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002064 PyErr_SetString(PyExc_SystemError, "invalid kind");
2065 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002067}
2068
Victor Stinnerece58de2012-04-23 23:36:38 +02002069Py_UCS4
2070_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2071{
2072 enum PyUnicode_Kind kind;
2073 void *startptr, *endptr;
2074
2075 assert(PyUnicode_IS_READY(unicode));
2076 assert(0 <= start);
2077 assert(end <= PyUnicode_GET_LENGTH(unicode));
2078 assert(start <= end);
2079
2080 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2081 return PyUnicode_MAX_CHAR_VALUE(unicode);
2082
2083 if (start == end)
2084 return 127;
2085
Victor Stinner94d558b2012-04-27 22:26:58 +02002086 if (PyUnicode_IS_ASCII(unicode))
2087 return 127;
2088
Victor Stinnerece58de2012-04-23 23:36:38 +02002089 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002090 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002091 endptr = (char *)startptr + end * kind;
2092 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002093 switch(kind) {
2094 case PyUnicode_1BYTE_KIND:
2095 return ucs1lib_find_max_char(startptr, endptr);
2096 case PyUnicode_2BYTE_KIND:
2097 return ucs2lib_find_max_char(startptr, endptr);
2098 case PyUnicode_4BYTE_KIND:
2099 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002100 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002101 assert(0);
2102 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002103 }
2104}
2105
Victor Stinner25a4b292011-10-06 12:31:55 +02002106/* Ensure that a string uses the most efficient storage, if it is not the
2107 case: create a new string with of the right kind. Write NULL into *p_unicode
2108 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002109static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002110unicode_adjust_maxchar(PyObject **p_unicode)
2111{
2112 PyObject *unicode, *copy;
2113 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002114 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002115 unsigned int kind;
2116
2117 assert(p_unicode != NULL);
2118 unicode = *p_unicode;
2119 assert(PyUnicode_IS_READY(unicode));
2120 if (PyUnicode_IS_ASCII(unicode))
2121 return;
2122
2123 len = PyUnicode_GET_LENGTH(unicode);
2124 kind = PyUnicode_KIND(unicode);
2125 if (kind == PyUnicode_1BYTE_KIND) {
2126 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002127 max_char = ucs1lib_find_max_char(u, u + len);
2128 if (max_char >= 128)
2129 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 }
2131 else if (kind == PyUnicode_2BYTE_KIND) {
2132 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002133 max_char = ucs2lib_find_max_char(u, u + len);
2134 if (max_char >= 256)
2135 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002136 }
2137 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002138 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002139 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002140 max_char = ucs4lib_find_max_char(u, u + len);
2141 if (max_char >= 0x10000)
2142 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002143 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002144 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002145 if (copy != NULL)
2146 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002147 Py_DECREF(unicode);
2148 *p_unicode = copy;
2149}
2150
Victor Stinner034f6cf2011-09-30 02:26:44 +02002151PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002152_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153{
Victor Stinner87af4f22011-11-21 23:03:47 +01002154 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002155 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002156
Victor Stinner034f6cf2011-09-30 02:26:44 +02002157 if (!PyUnicode_Check(unicode)) {
2158 PyErr_BadInternalCall();
2159 return NULL;
2160 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002161 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002162 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002163
Victor Stinner87af4f22011-11-21 23:03:47 +01002164 length = PyUnicode_GET_LENGTH(unicode);
2165 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002166 if (!copy)
2167 return NULL;
2168 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2169
Victor Stinner87af4f22011-11-21 23:03:47 +01002170 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2171 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002172 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002173 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002174}
2175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176
Victor Stinnerbc603d12011-10-02 01:00:40 +02002177/* Widen Unicode objects to larger buffers. Don't write terminating null
2178 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002179
2180void*
2181_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2182{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002183 Py_ssize_t len;
2184 void *result;
2185 unsigned int skind;
2186
Benjamin Petersonbac79492012-01-14 13:34:47 -05002187 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002188 return NULL;
2189
2190 len = PyUnicode_GET_LENGTH(s);
2191 skind = PyUnicode_KIND(s);
2192 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002193 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002194 return NULL;
2195 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002196 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002197 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002198 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 if (!result)
2200 return PyErr_NoMemory();
2201 assert(skind == PyUnicode_1BYTE_KIND);
2202 _PyUnicode_CONVERT_BYTES(
2203 Py_UCS1, Py_UCS2,
2204 PyUnicode_1BYTE_DATA(s),
2205 PyUnicode_1BYTE_DATA(s) + len,
2206 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002208 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002209 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 if (!result)
2211 return PyErr_NoMemory();
2212 if (skind == PyUnicode_2BYTE_KIND) {
2213 _PyUnicode_CONVERT_BYTES(
2214 Py_UCS2, Py_UCS4,
2215 PyUnicode_2BYTE_DATA(s),
2216 PyUnicode_2BYTE_DATA(s) + len,
2217 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 else {
2220 assert(skind == PyUnicode_1BYTE_KIND);
2221 _PyUnicode_CONVERT_BYTES(
2222 Py_UCS1, Py_UCS4,
2223 PyUnicode_1BYTE_DATA(s),
2224 PyUnicode_1BYTE_DATA(s) + len,
2225 result);
2226 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002228 default:
2229 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002230 }
Victor Stinner01698042011-10-04 00:04:26 +02002231 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 return NULL;
2233}
2234
2235static Py_UCS4*
2236as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2237 int copy_null)
2238{
2239 int kind;
2240 void *data;
2241 Py_ssize_t len, targetlen;
2242 if (PyUnicode_READY(string) == -1)
2243 return NULL;
2244 kind = PyUnicode_KIND(string);
2245 data = PyUnicode_DATA(string);
2246 len = PyUnicode_GET_LENGTH(string);
2247 targetlen = len;
2248 if (copy_null)
2249 targetlen++;
2250 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002251 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252 if (!target) {
2253 PyErr_NoMemory();
2254 return NULL;
2255 }
2256 }
2257 else {
2258 if (targetsize < targetlen) {
2259 PyErr_Format(PyExc_SystemError,
2260 "string is longer than the buffer");
2261 if (copy_null && 0 < targetsize)
2262 target[0] = 0;
2263 return NULL;
2264 }
2265 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002266 if (kind == PyUnicode_1BYTE_KIND) {
2267 Py_UCS1 *start = (Py_UCS1 *) data;
2268 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002269 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002270 else if (kind == PyUnicode_2BYTE_KIND) {
2271 Py_UCS2 *start = (Py_UCS2 *) data;
2272 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2273 }
2274 else {
2275 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002277 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 if (copy_null)
2279 target[len] = 0;
2280 return target;
2281}
2282
2283Py_UCS4*
2284PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2285 int copy_null)
2286{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002287 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002288 PyErr_BadInternalCall();
2289 return NULL;
2290 }
2291 return as_ucs4(string, target, targetsize, copy_null);
2292}
2293
2294Py_UCS4*
2295PyUnicode_AsUCS4Copy(PyObject *string)
2296{
2297 return as_ucs4(string, NULL, 0, 1);
2298}
2299
2300#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002301
Alexander Belopolsky40018472011-02-26 01:02:56 +00002302PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002303PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002305 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002306 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002307 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002308 PyErr_BadInternalCall();
2309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002310 }
2311
Martin v. Löwis790465f2008-04-05 20:41:37 +00002312 if (size == -1) {
2313 size = wcslen(w);
2314 }
2315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002316 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002317}
2318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002319#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002320
Walter Dörwald346737f2007-05-31 10:44:43 +00002321static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002322makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002323 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002324{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002325 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002326 if (longflag)
2327 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002328 else if (longlongflag) {
2329 /* longlongflag should only ever be nonzero on machines with
2330 HAVE_LONG_LONG defined */
2331#ifdef HAVE_LONG_LONG
2332 char *f = PY_FORMAT_LONG_LONG;
2333 while (*f)
2334 *fmt++ = *f++;
2335#else
2336 /* we shouldn't ever get here */
2337 assert(0);
2338 *fmt++ = 'l';
2339#endif
2340 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002341 else if (size_tflag) {
2342 char *f = PY_FORMAT_SIZE_T;
2343 while (*f)
2344 *fmt++ = *f++;
2345 }
2346 *fmt++ = c;
2347 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002348}
2349
Victor Stinner15a11362012-10-06 23:48:20 +02002350/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002351 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2352 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2353#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002354
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002355static int
2356unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2357 Py_ssize_t width, Py_ssize_t precision)
2358{
2359 Py_ssize_t length, fill, arglen;
2360 Py_UCS4 maxchar;
2361
2362 if (PyUnicode_READY(str) == -1)
2363 return -1;
2364
2365 length = PyUnicode_GET_LENGTH(str);
2366 if ((precision == -1 || precision >= length)
2367 && width <= length)
2368 return _PyUnicodeWriter_WriteStr(writer, str);
2369
2370 if (precision != -1)
2371 length = Py_MIN(precision, length);
2372
2373 arglen = Py_MAX(length, width);
2374 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2375 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2376 else
2377 maxchar = writer->maxchar;
2378
2379 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2380 return -1;
2381
2382 if (width > length) {
2383 fill = width - length;
2384 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2385 return -1;
2386 writer->pos += fill;
2387 }
2388
2389 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2390 str, 0, length);
2391 writer->pos += length;
2392 return 0;
2393}
2394
2395static int
2396unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2397 Py_ssize_t width, Py_ssize_t precision)
2398{
2399 /* UTF-8 */
2400 Py_ssize_t length;
2401 PyObject *unicode;
2402 int res;
2403
2404 length = strlen(str);
2405 if (precision != -1)
2406 length = Py_MIN(length, precision);
2407 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2408 if (unicode == NULL)
2409 return -1;
2410
2411 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2412 Py_DECREF(unicode);
2413 return res;
2414}
2415
Victor Stinner96865452011-03-01 23:44:09 +00002416static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002417unicode_fromformat_arg(_PyUnicodeWriter *writer,
2418 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002419{
Victor Stinnere215d962012-10-06 23:03:36 +02002420 const char *p;
2421 Py_ssize_t len;
2422 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002423 Py_ssize_t width;
2424 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002425 int longflag;
2426 int longlongflag;
2427 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002428 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002429
2430 p = f;
2431 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002432 zeropad = 0;
2433 if (*f == '0') {
2434 zeropad = 1;
2435 f++;
2436 }
Victor Stinner96865452011-03-01 23:44:09 +00002437
2438 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 width = -1;
2440 if (Py_ISDIGIT((unsigned)*f)) {
2441 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002442 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002443 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002444 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002445 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002446 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002447 return NULL;
2448 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002449 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002450 f++;
2451 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002452 }
2453 precision = -1;
2454 if (*f == '.') {
2455 f++;
2456 if (Py_ISDIGIT((unsigned)*f)) {
2457 precision = (*f - '0');
2458 f++;
2459 while (Py_ISDIGIT((unsigned)*f)) {
2460 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2461 PyErr_SetString(PyExc_ValueError,
2462 "precision too big");
2463 return NULL;
2464 }
2465 precision = (precision * 10) + (*f - '0');
2466 f++;
2467 }
2468 }
Victor Stinner96865452011-03-01 23:44:09 +00002469 if (*f == '%') {
2470 /* "%.3%s" => f points to "3" */
2471 f--;
2472 }
2473 }
2474 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002475 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002476 f--;
2477 }
Victor Stinner96865452011-03-01 23:44:09 +00002478
2479 /* Handle %ld, %lu, %lld and %llu. */
2480 longflag = 0;
2481 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002482 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002483 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002484 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002485 longflag = 1;
2486 ++f;
2487 }
2488#ifdef HAVE_LONG_LONG
2489 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002490 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002491 longlongflag = 1;
2492 f += 2;
2493 }
2494#endif
2495 }
2496 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002497 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002498 size_tflag = 1;
2499 ++f;
2500 }
Victor Stinnere215d962012-10-06 23:03:36 +02002501
2502 if (f[1] == '\0')
2503 writer->overallocate = 0;
2504
2505 switch (*f) {
2506 case 'c':
2507 {
2508 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002509 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002510 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002511 "character argument not in range(0x110000)");
2512 return NULL;
2513 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002514 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002515 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002516 break;
2517 }
2518
2519 case 'i':
2520 case 'd':
2521 case 'u':
2522 case 'x':
2523 {
2524 /* used by sprintf */
2525 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002526 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002527 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002528
2529 if (*f == 'u') {
2530 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2531
2532 if (longflag)
2533 len = sprintf(buffer, fmt,
2534 va_arg(*vargs, unsigned long));
2535#ifdef HAVE_LONG_LONG
2536 else if (longlongflag)
2537 len = sprintf(buffer, fmt,
2538 va_arg(*vargs, unsigned PY_LONG_LONG));
2539#endif
2540 else if (size_tflag)
2541 len = sprintf(buffer, fmt,
2542 va_arg(*vargs, size_t));
2543 else
2544 len = sprintf(buffer, fmt,
2545 va_arg(*vargs, unsigned int));
2546 }
2547 else if (*f == 'x') {
2548 makefmt(fmt, 0, 0, 0, 'x');
2549 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2550 }
2551 else {
2552 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2553
2554 if (longflag)
2555 len = sprintf(buffer, fmt,
2556 va_arg(*vargs, long));
2557#ifdef HAVE_LONG_LONG
2558 else if (longlongflag)
2559 len = sprintf(buffer, fmt,
2560 va_arg(*vargs, PY_LONG_LONG));
2561#endif
2562 else if (size_tflag)
2563 len = sprintf(buffer, fmt,
2564 va_arg(*vargs, Py_ssize_t));
2565 else
2566 len = sprintf(buffer, fmt,
2567 va_arg(*vargs, int));
2568 }
2569 assert(len >= 0);
2570
Victor Stinnere215d962012-10-06 23:03:36 +02002571 if (precision < len)
2572 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002573
2574 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002575 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2576 return NULL;
2577
Victor Stinnere215d962012-10-06 23:03:36 +02002578 if (width > precision) {
2579 Py_UCS4 fillchar;
2580 fill = width - precision;
2581 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002582 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2583 return NULL;
2584 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002585 }
Victor Stinner15a11362012-10-06 23:48:20 +02002586 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002587 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002588 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2589 return NULL;
2590 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002591 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002592
Victor Stinner4a587072013-11-19 12:54:53 +01002593 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2594 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002595 break;
2596 }
2597
2598 case 'p':
2599 {
2600 char number[MAX_LONG_LONG_CHARS];
2601
2602 len = sprintf(number, "%p", va_arg(*vargs, void*));
2603 assert(len >= 0);
2604
2605 /* %p is ill-defined: ensure leading 0x. */
2606 if (number[1] == 'X')
2607 number[1] = 'x';
2608 else if (number[1] != 'x') {
2609 memmove(number + 2, number,
2610 strlen(number) + 1);
2611 number[0] = '0';
2612 number[1] = 'x';
2613 len += 2;
2614 }
2615
Victor Stinner4a587072013-11-19 12:54:53 +01002616 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002617 return NULL;
2618 break;
2619 }
2620
2621 case 's':
2622 {
2623 /* UTF-8 */
2624 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002625 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002626 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002627 break;
2628 }
2629
2630 case 'U':
2631 {
2632 PyObject *obj = va_arg(*vargs, PyObject *);
2633 assert(obj && _PyUnicode_CHECK(obj));
2634
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002635 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002636 return NULL;
2637 break;
2638 }
2639
2640 case 'V':
2641 {
2642 PyObject *obj = va_arg(*vargs, PyObject *);
2643 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002644 if (obj) {
2645 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002646 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002647 return NULL;
2648 }
2649 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002650 assert(str != NULL);
2651 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002652 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002653 }
2654 break;
2655 }
2656
2657 case 'S':
2658 {
2659 PyObject *obj = va_arg(*vargs, PyObject *);
2660 PyObject *str;
2661 assert(obj);
2662 str = PyObject_Str(obj);
2663 if (!str)
2664 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002665 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002666 Py_DECREF(str);
2667 return NULL;
2668 }
2669 Py_DECREF(str);
2670 break;
2671 }
2672
2673 case 'R':
2674 {
2675 PyObject *obj = va_arg(*vargs, PyObject *);
2676 PyObject *repr;
2677 assert(obj);
2678 repr = PyObject_Repr(obj);
2679 if (!repr)
2680 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002681 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002682 Py_DECREF(repr);
2683 return NULL;
2684 }
2685 Py_DECREF(repr);
2686 break;
2687 }
2688
2689 case 'A':
2690 {
2691 PyObject *obj = va_arg(*vargs, PyObject *);
2692 PyObject *ascii;
2693 assert(obj);
2694 ascii = PyObject_ASCII(obj);
2695 if (!ascii)
2696 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002697 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002698 Py_DECREF(ascii);
2699 return NULL;
2700 }
2701 Py_DECREF(ascii);
2702 break;
2703 }
2704
2705 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002706 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002707 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002708 break;
2709
2710 default:
2711 /* if we stumble upon an unknown formatting code, copy the rest
2712 of the format string to the output string. (we cannot just
2713 skip the code, since there's no way to know what's in the
2714 argument list) */
2715 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002716 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002717 return NULL;
2718 f = p+len;
2719 return f;
2720 }
2721
2722 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002723 return f;
2724}
2725
Walter Dörwaldd2034312007-05-18 16:29:38 +00002726PyObject *
2727PyUnicode_FromFormatV(const char *format, va_list vargs)
2728{
Victor Stinnere215d962012-10-06 23:03:36 +02002729 va_list vargs2;
2730 const char *f;
2731 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002732
Victor Stinner8f674cc2013-04-17 23:02:17 +02002733 _PyUnicodeWriter_Init(&writer);
2734 writer.min_length = strlen(format) + 100;
2735 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002736
2737 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2738 Copy it to be able to pass a reference to a subfunction. */
2739 Py_VA_COPY(vargs2, vargs);
2740
2741 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002742 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002743 f = unicode_fromformat_arg(&writer, f, &vargs2);
2744 if (f == NULL)
2745 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002746 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002747 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002748 const char *p;
2749 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002750
Victor Stinnere215d962012-10-06 23:03:36 +02002751 p = f;
2752 do
2753 {
2754 if ((unsigned char)*p > 127) {
2755 PyErr_Format(PyExc_ValueError,
2756 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2757 "string, got a non-ASCII byte: 0x%02x",
2758 (unsigned char)*p);
2759 return NULL;
2760 }
2761 p++;
2762 }
2763 while (*p != '\0' && *p != '%');
2764 len = p - f;
2765
2766 if (*p == '\0')
2767 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002768
2769 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002770 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002771
2772 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002773 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002774 }
Victor Stinnere215d962012-10-06 23:03:36 +02002775 return _PyUnicodeWriter_Finish(&writer);
2776
2777 fail:
2778 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002779 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002780}
2781
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782PyObject *
2783PyUnicode_FromFormat(const char *format, ...)
2784{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002785 PyObject* ret;
2786 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002787
2788#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002789 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002790#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002791 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002792#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002793 ret = PyUnicode_FromFormatV(format, vargs);
2794 va_end(vargs);
2795 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002796}
2797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002798#ifdef HAVE_WCHAR_H
2799
Victor Stinner5593d8a2010-10-02 11:11:27 +00002800/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2801 convert a Unicode object to a wide character string.
2802
Victor Stinnerd88d9832011-09-06 02:00:05 +02002803 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002804 character) required to convert the unicode object. Ignore size argument.
2805
Victor Stinnerd88d9832011-09-06 02:00:05 +02002806 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002807 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002808 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002809static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002810unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002811 wchar_t *w,
2812 Py_ssize_t size)
2813{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002814 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002815 const wchar_t *wstr;
2816
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002817 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002818 if (wstr == NULL)
2819 return -1;
2820
Victor Stinner5593d8a2010-10-02 11:11:27 +00002821 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002822 if (size > res)
2823 size = res + 1;
2824 else
2825 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002826 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002827 return res;
2828 }
2829 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002831}
2832
2833Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002834PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002835 wchar_t *w,
2836 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002837{
2838 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002839 PyErr_BadInternalCall();
2840 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002841 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002842 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002843}
2844
Victor Stinner137c34c2010-09-29 10:25:54 +00002845wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002846PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002847 Py_ssize_t *size)
2848{
2849 wchar_t* buffer;
2850 Py_ssize_t buflen;
2851
2852 if (unicode == NULL) {
2853 PyErr_BadInternalCall();
2854 return NULL;
2855 }
2856
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002857 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002858 if (buflen == -1)
2859 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002860 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002861 if (buffer == NULL) {
2862 PyErr_NoMemory();
2863 return NULL;
2864 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002865 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002866 if (buflen == -1) {
2867 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002869 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002870 if (size != NULL)
2871 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002872 return buffer;
2873}
2874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002875#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002879{
Victor Stinner8faf8212011-12-08 22:14:11 +01002880 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 PyErr_SetString(PyExc_ValueError,
2882 "chr() arg not in range(0x110000)");
2883 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002884 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002885
Victor Stinner985a82a2014-01-03 12:53:47 +01002886 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002887}
2888
Alexander Belopolsky40018472011-02-26 01:02:56 +00002889PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002890PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002892 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002893 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002895 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002896 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002897 Py_INCREF(obj);
2898 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002899 }
2900 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002901 /* For a Unicode subtype that's not a Unicode object,
2902 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002903 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002904 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002905 PyErr_Format(PyExc_TypeError,
2906 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002907 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002908 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002909}
2910
Alexander Belopolsky40018472011-02-26 01:02:56 +00002911PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002912PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002913 const char *encoding,
2914 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002915{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002916 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002917 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002918
Guido van Rossumd57fd912000-03-10 22:53:23 +00002919 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 PyErr_BadInternalCall();
2921 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002923
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002924 /* Decoding bytes objects is the most common case and should be fast */
2925 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002926 if (PyBytes_GET_SIZE(obj) == 0)
2927 _Py_RETURN_UNICODE_EMPTY();
2928 v = PyUnicode_Decode(
2929 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2930 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002931 return v;
2932 }
2933
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002934 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002935 PyErr_SetString(PyExc_TypeError,
2936 "decoding str is not supported");
2937 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002939
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002940 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2941 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2942 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002943 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002944 Py_TYPE(obj)->tp_name);
2945 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002946 }
Tim Petersced69f82003-09-16 20:30:58 +00002947
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002948 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002949 PyBuffer_Release(&buffer);
2950 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002952
Serhiy Storchaka05997252013-01-26 12:14:02 +02002953 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002954 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002955 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002956}
2957
Victor Stinner600d3be2010-06-10 12:00:55 +00002958/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002959 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2960 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002961int
2962_Py_normalize_encoding(const char *encoding,
2963 char *lower,
2964 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002965{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002966 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002967 char *l;
2968 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002969
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002970 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002971 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002972 if (lower_len < 6)
2973 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002974 strcpy(lower, "utf-8");
2975 return 1;
2976 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002977 e = encoding;
2978 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002979 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002980 while (*e) {
2981 if (l == l_end)
2982 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002983 if (Py_ISUPPER(*e)) {
2984 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002985 }
2986 else if (*e == '_') {
2987 *l++ = '-';
2988 e++;
2989 }
2990 else {
2991 *l++ = *e++;
2992 }
2993 }
2994 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002995 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002996}
2997
Alexander Belopolsky40018472011-02-26 01:02:56 +00002998PyObject *
2999PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003000 Py_ssize_t size,
3001 const char *encoding,
3002 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003003{
3004 PyObject *buffer = NULL, *unicode;
3005 Py_buffer info;
3006 char lower[11]; /* Enough for any encoding shortcut */
3007
Fred Drakee4315f52000-05-09 19:53:39 +00003008 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003009 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003010 if ((strcmp(lower, "utf-8") == 0) ||
3011 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003012 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003013 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003014 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003015 (strcmp(lower, "iso-8859-1") == 0) ||
3016 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003017 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003018#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003019 else if (strcmp(lower, "mbcs") == 0)
3020 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003021#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003022 else if (strcmp(lower, "ascii") == 0)
3023 return PyUnicode_DecodeASCII(s, size, errors);
3024 else if (strcmp(lower, "utf-16") == 0)
3025 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3026 else if (strcmp(lower, "utf-32") == 0)
3027 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3028 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003029
3030 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003031 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003032 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003033 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003034 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003035 if (buffer == NULL)
3036 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003037 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003038 if (unicode == NULL)
3039 goto onError;
3040 if (!PyUnicode_Check(unicode)) {
3041 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003042 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3043 "use codecs.decode() to decode to arbitrary types",
3044 encoding,
3045 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 Py_DECREF(unicode);
3047 goto onError;
3048 }
3049 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003050 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003051
Benjamin Peterson29060642009-01-31 22:14:21 +00003052 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003053 Py_XDECREF(buffer);
3054 return NULL;
3055}
3056
Alexander Belopolsky40018472011-02-26 01:02:56 +00003057PyObject *
3058PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003059 const char *encoding,
3060 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003062 if (!PyUnicode_Check(unicode)) {
3063 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003064 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003065 }
3066
3067 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003069
3070 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003071 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003072}
3073
Alexander Belopolsky40018472011-02-26 01:02:56 +00003074PyObject *
3075PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003076 const char *encoding,
3077 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003078{
3079 PyObject *v;
3080
3081 if (!PyUnicode_Check(unicode)) {
3082 PyErr_BadArgument();
3083 goto onError;
3084 }
3085
3086 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003087 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003088
3089 /* Decode via the codec registry */
3090 v = PyCodec_Decode(unicode, encoding, errors);
3091 if (v == NULL)
3092 goto onError;
3093 if (!PyUnicode_Check(v)) {
3094 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003095 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3096 "use codecs.decode() to decode to arbitrary types",
3097 encoding,
3098 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003099 Py_DECREF(v);
3100 goto onError;
3101 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003102 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003103
Benjamin Peterson29060642009-01-31 22:14:21 +00003104 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003105 return NULL;
3106}
3107
Alexander Belopolsky40018472011-02-26 01:02:56 +00003108PyObject *
3109PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003110 Py_ssize_t size,
3111 const char *encoding,
3112 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003113{
3114 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003115
Guido van Rossumd57fd912000-03-10 22:53:23 +00003116 unicode = PyUnicode_FromUnicode(s, size);
3117 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003118 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003119 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3120 Py_DECREF(unicode);
3121 return v;
3122}
3123
Alexander Belopolsky40018472011-02-26 01:02:56 +00003124PyObject *
3125PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003126 const char *encoding,
3127 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003128{
3129 PyObject *v;
3130
3131 if (!PyUnicode_Check(unicode)) {
3132 PyErr_BadArgument();
3133 goto onError;
3134 }
3135
3136 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003137 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003138
3139 /* Encode via the codec registry */
3140 v = PyCodec_Encode(unicode, encoding, errors);
3141 if (v == NULL)
3142 goto onError;
3143 return v;
3144
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003146 return NULL;
3147}
3148
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003149static size_t
3150wcstombs_errorpos(const wchar_t *wstr)
3151{
3152 size_t len;
3153#if SIZEOF_WCHAR_T == 2
3154 wchar_t buf[3];
3155#else
3156 wchar_t buf[2];
3157#endif
3158 char outbuf[MB_LEN_MAX];
3159 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003160
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003161#if SIZEOF_WCHAR_T == 2
3162 buf[2] = 0;
3163#else
3164 buf[1] = 0;
3165#endif
3166 start = wstr;
3167 while (*wstr != L'\0')
3168 {
3169 previous = wstr;
3170#if SIZEOF_WCHAR_T == 2
3171 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3172 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3173 {
3174 buf[0] = wstr[0];
3175 buf[1] = wstr[1];
3176 wstr += 2;
3177 }
3178 else {
3179 buf[0] = *wstr;
3180 buf[1] = 0;
3181 wstr++;
3182 }
3183#else
3184 buf[0] = *wstr;
3185 wstr++;
3186#endif
3187 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003188 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003189 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003190 }
3191
3192 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003193 return 0;
3194}
3195
Victor Stinner1b579672011-12-17 05:47:23 +01003196static int
3197locale_error_handler(const char *errors, int *surrogateescape)
3198{
3199 if (errors == NULL) {
3200 *surrogateescape = 0;
3201 return 0;
3202 }
3203
3204 if (strcmp(errors, "strict") == 0) {
3205 *surrogateescape = 0;
3206 return 0;
3207 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003208 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003209 *surrogateescape = 1;
3210 return 0;
3211 }
3212 PyErr_Format(PyExc_ValueError,
3213 "only 'strict' and 'surrogateescape' error handlers "
3214 "are supported, not '%s'",
3215 errors);
3216 return -1;
3217}
3218
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003219PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003220PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003221{
3222 Py_ssize_t wlen, wlen2;
3223 wchar_t *wstr;
3224 PyObject *bytes = NULL;
3225 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003226 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003227 PyObject *exc;
3228 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003229 int surrogateescape;
3230
3231 if (locale_error_handler(errors, &surrogateescape) < 0)
3232 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003233
3234 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3235 if (wstr == NULL)
3236 return NULL;
3237
3238 wlen2 = wcslen(wstr);
3239 if (wlen2 != wlen) {
3240 PyMem_Free(wstr);
3241 PyErr_SetString(PyExc_TypeError, "embedded null character");
3242 return NULL;
3243 }
3244
3245 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003246 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003247 char *str;
3248
3249 str = _Py_wchar2char(wstr, &error_pos);
3250 if (str == NULL) {
3251 if (error_pos == (size_t)-1) {
3252 PyErr_NoMemory();
3253 PyMem_Free(wstr);
3254 return NULL;
3255 }
3256 else {
3257 goto encode_error;
3258 }
3259 }
3260 PyMem_Free(wstr);
3261
3262 bytes = PyBytes_FromString(str);
3263 PyMem_Free(str);
3264 }
3265 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003266 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003267 size_t len, len2;
3268
3269 len = wcstombs(NULL, wstr, 0);
3270 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003271 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003272 goto encode_error;
3273 }
3274
3275 bytes = PyBytes_FromStringAndSize(NULL, len);
3276 if (bytes == NULL) {
3277 PyMem_Free(wstr);
3278 return NULL;
3279 }
3280
3281 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3282 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003283 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003284 goto encode_error;
3285 }
3286 PyMem_Free(wstr);
3287 }
3288 return bytes;
3289
3290encode_error:
3291 errmsg = strerror(errno);
3292 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003293
3294 if (error_pos == (size_t)-1)
3295 error_pos = wcstombs_errorpos(wstr);
3296
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003297 PyMem_Free(wstr);
3298 Py_XDECREF(bytes);
3299
Victor Stinner2f197072011-12-17 07:08:30 +01003300 if (errmsg != NULL) {
3301 size_t errlen;
3302 wstr = _Py_char2wchar(errmsg, &errlen);
3303 if (wstr != NULL) {
3304 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003305 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003306 } else
3307 errmsg = NULL;
3308 }
3309 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003310 reason = PyUnicode_FromString(
3311 "wcstombs() encountered an unencodable "
3312 "wide character");
3313 if (reason == NULL)
3314 return NULL;
3315
3316 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3317 "locale", unicode,
3318 (Py_ssize_t)error_pos,
3319 (Py_ssize_t)(error_pos+1),
3320 reason);
3321 Py_DECREF(reason);
3322 if (exc != NULL) {
3323 PyCodec_StrictErrors(exc);
3324 Py_XDECREF(exc);
3325 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003326 return NULL;
3327}
3328
Victor Stinnerad158722010-10-27 00:25:46 +00003329PyObject *
3330PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003331{
Victor Stinner99b95382011-07-04 14:23:54 +02003332#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003333 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003334#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003335 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003336#else
Victor Stinner793b5312011-04-27 00:24:21 +02003337 PyInterpreterState *interp = PyThreadState_GET()->interp;
3338 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3339 cannot use it to encode and decode filenames before it is loaded. Load
3340 the Python codec requires to encode at least its own filename. Use the C
3341 version of the locale codec until the codec registry is initialized and
3342 the Python codec is loaded.
3343
3344 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3345 cannot only rely on it: check also interp->fscodec_initialized for
3346 subinterpreters. */
3347 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003348 return PyUnicode_AsEncodedString(unicode,
3349 Py_FileSystemDefaultEncoding,
3350 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003351 }
3352 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003353 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003354 }
Victor Stinnerad158722010-10-27 00:25:46 +00003355#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003356}
3357
Alexander Belopolsky40018472011-02-26 01:02:56 +00003358PyObject *
3359PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003360 const char *encoding,
3361 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003362{
3363 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003364 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003365
Guido van Rossumd57fd912000-03-10 22:53:23 +00003366 if (!PyUnicode_Check(unicode)) {
3367 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003368 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003369 }
Fred Drakee4315f52000-05-09 19:53:39 +00003370
Fred Drakee4315f52000-05-09 19:53:39 +00003371 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003372 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003373 if ((strcmp(lower, "utf-8") == 0) ||
3374 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003375 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003376 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003377 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003378 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003380 }
Victor Stinner37296e82010-06-10 13:36:23 +00003381 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003382 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003383 (strcmp(lower, "iso-8859-1") == 0) ||
3384 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003385 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003386#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003387 else if (strcmp(lower, "mbcs") == 0)
3388 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003389#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003390 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003391 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003392 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003393
3394 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003395 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003396 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003397 return NULL;
3398
3399 /* The normal path */
3400 if (PyBytes_Check(v))
3401 return v;
3402
3403 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003404 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003405 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003406 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003407
3408 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003409 "encoder %s returned bytearray instead of bytes; "
3410 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003411 encoding);
3412 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003413 Py_DECREF(v);
3414 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003415 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003416
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003417 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3418 Py_DECREF(v);
3419 return b;
3420 }
3421
3422 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003423 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3424 "use codecs.encode() to encode to arbitrary types",
3425 encoding,
3426 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003427 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003428 return NULL;
3429}
3430
Alexander Belopolsky40018472011-02-26 01:02:56 +00003431PyObject *
3432PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003433 const char *encoding,
3434 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003435{
3436 PyObject *v;
3437
3438 if (!PyUnicode_Check(unicode)) {
3439 PyErr_BadArgument();
3440 goto onError;
3441 }
3442
3443 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003444 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003445
3446 /* Encode via the codec registry */
3447 v = PyCodec_Encode(unicode, encoding, errors);
3448 if (v == NULL)
3449 goto onError;
3450 if (!PyUnicode_Check(v)) {
3451 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003452 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3453 "use codecs.encode() to encode to arbitrary types",
3454 encoding,
3455 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003456 Py_DECREF(v);
3457 goto onError;
3458 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003459 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003460
Benjamin Peterson29060642009-01-31 22:14:21 +00003461 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003462 return NULL;
3463}
3464
Victor Stinner2f197072011-12-17 07:08:30 +01003465static size_t
3466mbstowcs_errorpos(const char *str, size_t len)
3467{
3468#ifdef HAVE_MBRTOWC
3469 const char *start = str;
3470 mbstate_t mbs;
3471 size_t converted;
3472 wchar_t ch;
3473
3474 memset(&mbs, 0, sizeof mbs);
3475 while (len)
3476 {
3477 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3478 if (converted == 0)
3479 /* Reached end of string */
3480 break;
3481 if (converted == (size_t)-1 || converted == (size_t)-2) {
3482 /* Conversion error or incomplete character */
3483 return str - start;
3484 }
3485 else {
3486 str += converted;
3487 len -= converted;
3488 }
3489 }
3490 /* failed to find the undecodable byte sequence */
3491 return 0;
3492#endif
3493 return 0;
3494}
3495
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003496PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003497PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003498 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499{
3500 wchar_t smallbuf[256];
3501 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3502 wchar_t *wstr;
3503 size_t wlen, wlen2;
3504 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003505 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003506 size_t error_pos;
3507 char *errmsg;
3508 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003509
3510 if (locale_error_handler(errors, &surrogateescape) < 0)
3511 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003512
3513 if (str[len] != '\0' || len != strlen(str)) {
3514 PyErr_SetString(PyExc_TypeError, "embedded null character");
3515 return NULL;
3516 }
3517
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003518 if (surrogateescape) {
3519 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003520 wstr = _Py_char2wchar(str, &wlen);
3521 if (wstr == NULL) {
3522 if (wlen == (size_t)-1)
3523 PyErr_NoMemory();
3524 else
3525 PyErr_SetFromErrno(PyExc_OSError);
3526 return NULL;
3527 }
3528
3529 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003530 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003531 }
3532 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003533 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003534#ifndef HAVE_BROKEN_MBSTOWCS
3535 wlen = mbstowcs(NULL, str, 0);
3536#else
3537 wlen = len;
3538#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003539 if (wlen == (size_t)-1)
3540 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003541 if (wlen+1 <= smallbuf_len) {
3542 wstr = smallbuf;
3543 }
3544 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003545 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003546 if (!wstr)
3547 return PyErr_NoMemory();
3548 }
3549
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003550 wlen2 = mbstowcs(wstr, str, wlen+1);
3551 if (wlen2 == (size_t)-1) {
3552 if (wstr != smallbuf)
3553 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003554 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003555 }
3556#ifdef HAVE_BROKEN_MBSTOWCS
3557 assert(wlen2 == wlen);
3558#endif
3559 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3560 if (wstr != smallbuf)
3561 PyMem_Free(wstr);
3562 }
3563 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003564
3565decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003566 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003567 errmsg = strerror(errno);
3568 assert(errmsg != NULL);
3569
3570 error_pos = mbstowcs_errorpos(str, len);
3571 if (errmsg != NULL) {
3572 size_t errlen;
3573 wstr = _Py_char2wchar(errmsg, &errlen);
3574 if (wstr != NULL) {
3575 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003576 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003577 }
Victor Stinner2f197072011-12-17 07:08:30 +01003578 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003579 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003580 reason = PyUnicode_FromString(
3581 "mbstowcs() encountered an invalid multibyte sequence");
3582 if (reason == NULL)
3583 return NULL;
3584
3585 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3586 "locale", str, len,
3587 (Py_ssize_t)error_pos,
3588 (Py_ssize_t)(error_pos+1),
3589 reason);
3590 Py_DECREF(reason);
3591 if (exc != NULL) {
3592 PyCodec_StrictErrors(exc);
3593 Py_XDECREF(exc);
3594 }
3595 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003596}
3597
3598PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003599PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003600{
3601 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003602 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003603}
3604
3605
3606PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003607PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003608 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003609 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3610}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003611
Christian Heimes5894ba72007-11-04 11:43:14 +00003612PyObject*
3613PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3614{
Victor Stinner99b95382011-07-04 14:23:54 +02003615#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003616 return PyUnicode_DecodeMBCS(s, size, NULL);
3617#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003618 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003619#else
Victor Stinner793b5312011-04-27 00:24:21 +02003620 PyInterpreterState *interp = PyThreadState_GET()->interp;
3621 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3622 cannot use it to encode and decode filenames before it is loaded. Load
3623 the Python codec requires to encode at least its own filename. Use the C
3624 version of the locale codec until the codec registry is initialized and
3625 the Python codec is loaded.
3626
3627 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3628 cannot only rely on it: check also interp->fscodec_initialized for
3629 subinterpreters. */
3630 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003631 return PyUnicode_Decode(s, size,
3632 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003633 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003634 }
3635 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003636 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003637 }
Victor Stinnerad158722010-10-27 00:25:46 +00003638#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003639}
3640
Martin v. Löwis011e8422009-05-05 04:43:17 +00003641
3642int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003643_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003644{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003645 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003646
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003647 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003648 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003649 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3650 PyUnicode_GET_LENGTH(str), '\0', 1);
3651 if (pos == -1)
3652 return 0;
3653 else
3654 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003655}
3656
Antoine Pitrou13348842012-01-29 18:36:34 +01003657int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003658PyUnicode_FSConverter(PyObject* arg, void* addr)
3659{
3660 PyObject *output = NULL;
3661 Py_ssize_t size;
3662 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003663 if (arg == NULL) {
3664 Py_DECREF(*(PyObject**)addr);
3665 return 1;
3666 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003667 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003668 output = arg;
3669 Py_INCREF(output);
3670 }
3671 else {
3672 arg = PyUnicode_FromObject(arg);
3673 if (!arg)
3674 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003675 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003676 Py_DECREF(arg);
3677 if (!output)
3678 return 0;
3679 if (!PyBytes_Check(output)) {
3680 Py_DECREF(output);
3681 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3682 return 0;
3683 }
3684 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003685 size = PyBytes_GET_SIZE(output);
3686 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003687 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003688 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003689 Py_DECREF(output);
3690 return 0;
3691 }
3692 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003693 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003694}
3695
3696
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003697int
3698PyUnicode_FSDecoder(PyObject* arg, void* addr)
3699{
3700 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003701 if (arg == NULL) {
3702 Py_DECREF(*(PyObject**)addr);
3703 return 1;
3704 }
3705 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003706 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003707 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003708 output = arg;
3709 Py_INCREF(output);
3710 }
3711 else {
3712 arg = PyBytes_FromObject(arg);
3713 if (!arg)
3714 return 0;
3715 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3716 PyBytes_GET_SIZE(arg));
3717 Py_DECREF(arg);
3718 if (!output)
3719 return 0;
3720 if (!PyUnicode_Check(output)) {
3721 Py_DECREF(output);
3722 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3723 return 0;
3724 }
3725 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003726 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003727 Py_DECREF(output);
3728 return 0;
3729 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003730 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003731 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003732 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3733 Py_DECREF(output);
3734 return 0;
3735 }
3736 *(PyObject**)addr = output;
3737 return Py_CLEANUP_SUPPORTED;
3738}
3739
3740
Martin v. Löwis5b222132007-06-10 09:51:05 +00003741char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003743{
Christian Heimesf3863112007-11-22 07:46:41 +00003744 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003745
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003746 if (!PyUnicode_Check(unicode)) {
3747 PyErr_BadArgument();
3748 return NULL;
3749 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003750 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003751 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003752
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003753 if (PyUnicode_UTF8(unicode) == NULL) {
3754 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003755 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3756 if (bytes == NULL)
3757 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003758 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3759 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003760 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761 Py_DECREF(bytes);
3762 return NULL;
3763 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003764 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3765 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3766 PyBytes_AS_STRING(bytes),
3767 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003768 Py_DECREF(bytes);
3769 }
3770
3771 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003772 *psize = PyUnicode_UTF8_LENGTH(unicode);
3773 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003774}
3775
3776char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3780}
3781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003782Py_UNICODE *
3783PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3784{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785 const unsigned char *one_byte;
3786#if SIZEOF_WCHAR_T == 4
3787 const Py_UCS2 *two_bytes;
3788#else
3789 const Py_UCS4 *four_bytes;
3790 const Py_UCS4 *ucs4_end;
3791 Py_ssize_t num_surrogates;
3792#endif
3793 wchar_t *w;
3794 wchar_t *wchar_end;
3795
3796 if (!PyUnicode_Check(unicode)) {
3797 PyErr_BadArgument();
3798 return NULL;
3799 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003800 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003802 assert(_PyUnicode_KIND(unicode) != 0);
3803 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003804
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003805 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003806#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003807 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3808 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003809 num_surrogates = 0;
3810
3811 for (; four_bytes < ucs4_end; ++four_bytes) {
3812 if (*four_bytes > 0xFFFF)
3813 ++num_surrogates;
3814 }
3815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3817 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3818 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819 PyErr_NoMemory();
3820 return NULL;
3821 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003822 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003824 w = _PyUnicode_WSTR(unicode);
3825 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3826 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003827 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3828 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003829 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003831 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3832 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833 }
3834 else
3835 *w = *four_bytes;
3836
3837 if (w > wchar_end) {
3838 assert(0 && "Miscalculated string end");
3839 }
3840 }
3841 *w = 0;
3842#else
3843 /* sizeof(wchar_t) == 4 */
3844 Py_FatalError("Impossible unicode object state, wstr and str "
3845 "should share memory already.");
3846 return NULL;
3847#endif
3848 }
3849 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003850 if ((size_t)_PyUnicode_LENGTH(unicode) >
3851 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3852 PyErr_NoMemory();
3853 return NULL;
3854 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003855 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3856 (_PyUnicode_LENGTH(unicode) + 1));
3857 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858 PyErr_NoMemory();
3859 return NULL;
3860 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003861 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3862 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3863 w = _PyUnicode_WSTR(unicode);
3864 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003866 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3867 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 for (; w < wchar_end; ++one_byte, ++w)
3869 *w = *one_byte;
3870 /* null-terminate the wstr */
3871 *w = 0;
3872 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003875 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003876 for (; w < wchar_end; ++two_bytes, ++w)
3877 *w = *two_bytes;
3878 /* null-terminate the wstr */
3879 *w = 0;
3880#else
3881 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 PyObject_FREE(_PyUnicode_WSTR(unicode));
3883 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884 Py_FatalError("Impossible unicode object state, wstr "
3885 "and str should share memory already.");
3886 return NULL;
3887#endif
3888 }
3889 else {
3890 assert(0 && "This should never happen.");
3891 }
3892 }
3893 }
3894 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003895 *size = PyUnicode_WSTR_LENGTH(unicode);
3896 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003897}
3898
Alexander Belopolsky40018472011-02-26 01:02:56 +00003899Py_UNICODE *
3900PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003903}
3904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003905
Alexander Belopolsky40018472011-02-26 01:02:56 +00003906Py_ssize_t
3907PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003908{
3909 if (!PyUnicode_Check(unicode)) {
3910 PyErr_BadArgument();
3911 goto onError;
3912 }
3913 return PyUnicode_GET_SIZE(unicode);
3914
Benjamin Peterson29060642009-01-31 22:14:21 +00003915 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003916 return -1;
3917}
3918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003919Py_ssize_t
3920PyUnicode_GetLength(PyObject *unicode)
3921{
Victor Stinner07621332012-06-16 04:53:46 +02003922 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923 PyErr_BadArgument();
3924 return -1;
3925 }
Victor Stinner07621332012-06-16 04:53:46 +02003926 if (PyUnicode_READY(unicode) == -1)
3927 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003928 return PyUnicode_GET_LENGTH(unicode);
3929}
3930
3931Py_UCS4
3932PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3933{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003934 void *data;
3935 int kind;
3936
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003937 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3938 PyErr_BadArgument();
3939 return (Py_UCS4)-1;
3940 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003941 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003942 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003943 return (Py_UCS4)-1;
3944 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003945 data = PyUnicode_DATA(unicode);
3946 kind = PyUnicode_KIND(unicode);
3947 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948}
3949
3950int
3951PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3952{
3953 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003954 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955 return -1;
3956 }
Victor Stinner488fa492011-12-12 00:01:39 +01003957 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003958 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003959 PyErr_SetString(PyExc_IndexError, "string index out of range");
3960 return -1;
3961 }
Victor Stinner488fa492011-12-12 00:01:39 +01003962 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003963 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003964 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3965 PyErr_SetString(PyExc_ValueError, "character out of range");
3966 return -1;
3967 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003968 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3969 index, ch);
3970 return 0;
3971}
3972
Alexander Belopolsky40018472011-02-26 01:02:56 +00003973const char *
3974PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003975{
Victor Stinner42cb4622010-09-01 19:39:01 +00003976 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003977}
3978
Victor Stinner554f3f02010-06-16 23:33:54 +00003979/* create or adjust a UnicodeDecodeError */
3980static void
3981make_decode_exception(PyObject **exceptionObject,
3982 const char *encoding,
3983 const char *input, Py_ssize_t length,
3984 Py_ssize_t startpos, Py_ssize_t endpos,
3985 const char *reason)
3986{
3987 if (*exceptionObject == NULL) {
3988 *exceptionObject = PyUnicodeDecodeError_Create(
3989 encoding, input, length, startpos, endpos, reason);
3990 }
3991 else {
3992 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3993 goto onError;
3994 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3995 goto onError;
3996 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3997 goto onError;
3998 }
3999 return;
4000
4001onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004002 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004003}
4004
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004005#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006/* error handling callback helper:
4007 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004008 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004009 and adjust various state variables.
4010 return 0 on success, -1 on error
4011*/
4012
Alexander Belopolsky40018472011-02-26 01:02:56 +00004013static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004014unicode_decode_call_errorhandler_wchar(
4015 const char *errors, PyObject **errorHandler,
4016 const char *encoding, const char *reason,
4017 const char **input, const char **inend, Py_ssize_t *startinpos,
4018 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4019 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004020{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004021 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004022
4023 PyObject *restuple = NULL;
4024 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004025 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004026 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004027 Py_ssize_t requiredsize;
4028 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004029 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004030 wchar_t *repwstr;
4031 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004032
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004033 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4034 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004035
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004036 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 *errorHandler = PyCodec_LookupError(errors);
4038 if (*errorHandler == NULL)
4039 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004040 }
4041
Victor Stinner554f3f02010-06-16 23:33:54 +00004042 make_decode_exception(exceptionObject,
4043 encoding,
4044 *input, *inend - *input,
4045 *startinpos, *endinpos,
4046 reason);
4047 if (*exceptionObject == NULL)
4048 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004049
4050 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4051 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004052 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004053 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004054 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056 }
4057 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004058 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004059
4060 /* Copy back the bytes variables, which might have been modified by the
4061 callback */
4062 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4063 if (!inputobj)
4064 goto onError;
4065 if (!PyBytes_Check(inputobj)) {
4066 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4067 }
4068 *input = PyBytes_AS_STRING(inputobj);
4069 insize = PyBytes_GET_SIZE(inputobj);
4070 *inend = *input + insize;
4071 /* we can DECREF safely, as the exception has another reference,
4072 so the object won't go away. */
4073 Py_DECREF(inputobj);
4074
4075 if (newpos<0)
4076 newpos = insize+newpos;
4077 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004078 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004079 goto onError;
4080 }
4081
4082 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4083 if (repwstr == NULL)
4084 goto onError;
4085 /* need more space? (at least enough for what we
4086 have+the replacement+the rest of the string (starting
4087 at the new input position), so we won't have to check space
4088 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004089 requiredsize = *outpos;
4090 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4091 goto overflow;
4092 requiredsize += repwlen;
4093 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4094 goto overflow;
4095 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004096 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004097 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004098 requiredsize = 2*outsize;
4099 if (unicode_resize(output, requiredsize) < 0)
4100 goto onError;
4101 }
4102 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4103 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004104 *endinpos = newpos;
4105 *inptr = *input + newpos;
4106
4107 /* we made it! */
4108 Py_XDECREF(restuple);
4109 return 0;
4110
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004111 overflow:
4112 PyErr_SetString(PyExc_OverflowError,
4113 "decoded result is too long for a Python string");
4114
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004115 onError:
4116 Py_XDECREF(restuple);
4117 return -1;
4118}
4119#endif /* HAVE_MBCS */
4120
4121static int
4122unicode_decode_call_errorhandler_writer(
4123 const char *errors, PyObject **errorHandler,
4124 const char *encoding, const char *reason,
4125 const char **input, const char **inend, Py_ssize_t *startinpos,
4126 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4127 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4128{
4129 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4130
4131 PyObject *restuple = NULL;
4132 PyObject *repunicode = NULL;
4133 Py_ssize_t insize;
4134 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004135 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004136 PyObject *inputobj = NULL;
4137
4138 if (*errorHandler == NULL) {
4139 *errorHandler = PyCodec_LookupError(errors);
4140 if (*errorHandler == NULL)
4141 goto onError;
4142 }
4143
4144 make_decode_exception(exceptionObject,
4145 encoding,
4146 *input, *inend - *input,
4147 *startinpos, *endinpos,
4148 reason);
4149 if (*exceptionObject == NULL)
4150 goto onError;
4151
4152 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4153 if (restuple == NULL)
4154 goto onError;
4155 if (!PyTuple_Check(restuple)) {
4156 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4157 goto onError;
4158 }
4159 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004160 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004161
4162 /* Copy back the bytes variables, which might have been modified by the
4163 callback */
4164 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4165 if (!inputobj)
4166 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004167 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004168 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004169 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004170 *input = PyBytes_AS_STRING(inputobj);
4171 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004172 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004173 /* we can DECREF safely, as the exception has another reference,
4174 so the object won't go away. */
4175 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004176
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004177 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004179 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004180 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004181 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004182 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004183
Victor Stinner8f674cc2013-04-17 23:02:17 +02004184 if (PyUnicode_READY(repunicode) < 0)
4185 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004186 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004187 if (replen > 1) {
4188 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004189 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004190 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4191 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4192 goto onError;
4193 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004194 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004195 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004196
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004198 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004199
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004201 Py_XDECREF(restuple);
4202 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004203
Benjamin Peterson29060642009-01-31 22:14:21 +00004204 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004205 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004206 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004207}
4208
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004209/* --- UTF-7 Codec -------------------------------------------------------- */
4210
Antoine Pitrou244651a2009-05-04 18:56:13 +00004211/* See RFC2152 for details. We encode conservatively and decode liberally. */
4212
4213/* Three simple macros defining base-64. */
4214
4215/* Is c a base-64 character? */
4216
4217#define IS_BASE64(c) \
4218 (((c) >= 'A' && (c) <= 'Z') || \
4219 ((c) >= 'a' && (c) <= 'z') || \
4220 ((c) >= '0' && (c) <= '9') || \
4221 (c) == '+' || (c) == '/')
4222
4223/* given that c is a base-64 character, what is its base-64 value? */
4224
4225#define FROM_BASE64(c) \
4226 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4227 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4228 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4229 (c) == '+' ? 62 : 63)
4230
4231/* What is the base-64 character of the bottom 6 bits of n? */
4232
4233#define TO_BASE64(n) \
4234 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4235
4236/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4237 * decoded as itself. We are permissive on decoding; the only ASCII
4238 * byte not decoding to itself is the + which begins a base64
4239 * string. */
4240
4241#define DECODE_DIRECT(c) \
4242 ((c) <= 127 && (c) != '+')
4243
4244/* The UTF-7 encoder treats ASCII characters differently according to
4245 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4246 * the above). See RFC2152. This array identifies these different
4247 * sets:
4248 * 0 : "Set D"
4249 * alphanumeric and '(),-./:?
4250 * 1 : "Set O"
4251 * !"#$%&*;<=>@[]^_`{|}
4252 * 2 : "whitespace"
4253 * ht nl cr sp
4254 * 3 : special (must be base64 encoded)
4255 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4256 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004257
Tim Petersced69f82003-09-16 20:30:58 +00004258static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004259char utf7_category[128] = {
4260/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4261 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4262/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4263 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4264/* sp ! " # $ % & ' ( ) * + , - . / */
4265 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4266/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4267 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4268/* @ A B C D E F G H I J K L M N O */
4269 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4270/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4272/* ` a b c d e f g h i j k l m n o */
4273 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4274/* p q r s t u v w x y z { | } ~ del */
4275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004276};
4277
Antoine Pitrou244651a2009-05-04 18:56:13 +00004278/* ENCODE_DIRECT: this character should be encoded as itself. The
4279 * answer depends on whether we are encoding set O as itself, and also
4280 * on whether we are encoding whitespace as itself. RFC2152 makes it
4281 * clear that the answers to these questions vary between
4282 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004283
Antoine Pitrou244651a2009-05-04 18:56:13 +00004284#define ENCODE_DIRECT(c, directO, directWS) \
4285 ((c) < 128 && (c) > 0 && \
4286 ((utf7_category[(c)] == 0) || \
4287 (directWS && (utf7_category[(c)] == 2)) || \
4288 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289
Alexander Belopolsky40018472011-02-26 01:02:56 +00004290PyObject *
4291PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004292 Py_ssize_t size,
4293 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004294{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004295 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4296}
4297
Antoine Pitrou244651a2009-05-04 18:56:13 +00004298/* The decoder. The only state we preserve is our read position,
4299 * i.e. how many characters we have consumed. So if we end in the
4300 * middle of a shift sequence we have to back off the read position
4301 * and the output to the beginning of the sequence, otherwise we lose
4302 * all the shift state (seen bits, number of bits seen, high
4303 * surrogate). */
4304
Alexander Belopolsky40018472011-02-26 01:02:56 +00004305PyObject *
4306PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004307 Py_ssize_t size,
4308 const char *errors,
4309 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004310{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004311 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004312 Py_ssize_t startinpos;
4313 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316 const char *errmsg = "";
4317 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004318 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004319 unsigned int base64bits = 0;
4320 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004321 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004322 PyObject *errorHandler = NULL;
4323 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004325 if (size == 0) {
4326 if (consumed)
4327 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004328 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004329 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004331 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004332 _PyUnicodeWriter_Init(&writer);
4333 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334
4335 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336 e = s + size;
4337
4338 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004339 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004341 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004342
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343 if (inShift) { /* in a base-64 section */
4344 if (IS_BASE64(ch)) { /* consume a base-64 character */
4345 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4346 base64bits += 6;
4347 s++;
4348 if (base64bits >= 16) {
4349 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004350 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004351 base64bits -= 16;
4352 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004353 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 if (surrogate) {
4355 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004356 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4357 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004358 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004359 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004361 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 }
4363 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004364 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004365 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 }
4368 }
Victor Stinner551ac952011-11-29 22:58:13 +01004369 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 /* first surrogate */
4371 surrogate = outCh;
4372 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004374 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 }
4377 }
4378 }
4379 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (base64bits > 0) { /* left-over bits */
4382 if (base64bits >= 6) {
4383 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004384 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 errmsg = "partial character in shift sequence";
4386 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 else {
4389 /* Some bits remain; they should be zero */
4390 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004391 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004392 errmsg = "non-zero padding bits in shift sequence";
4393 goto utf7Error;
4394 }
4395 }
4396 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004397 if (surrogate && DECODE_DIRECT(ch)) {
4398 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4399 goto onError;
4400 }
4401 surrogate = 0;
4402 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 /* '-' is absorbed; other terminating
4404 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004405 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 }
4408 }
4409 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004410 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 s++; /* consume '+' */
4412 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004413 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004414 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004415 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 }
4417 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004418 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004419 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004421 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004422 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004423 }
4424 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004427 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004428 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430 else {
4431 startinpos = s-starts;
4432 s++;
4433 errmsg = "unexpected special character";
4434 goto utf7Error;
4435 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004436 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004438 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004439 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004440 errors, &errorHandler,
4441 "utf7", errmsg,
4442 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004443 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004444 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445 }
4446
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 /* end of string */
4448
4449 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4450 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004451 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004452 if (surrogate ||
4453 (base64bits >= 6) ||
4454 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004456 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 errors, &errorHandler,
4458 "utf7", "unterminated shift sequence",
4459 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004460 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 goto onError;
4462 if (s < e)
4463 goto restart;
4464 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004465 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004466
4467 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004468 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004469 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004470 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004471 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004472 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004473 writer.kind, writer.data, shiftOutStart);
4474 Py_XDECREF(errorHandler);
4475 Py_XDECREF(exc);
4476 _PyUnicodeWriter_Dealloc(&writer);
4477 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004478 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004479 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 }
4481 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004482 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004483 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004484 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004486 Py_XDECREF(errorHandler);
4487 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004488 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004491 Py_XDECREF(errorHandler);
4492 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004493 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 return NULL;
4495}
4496
4497
Alexander Belopolsky40018472011-02-26 01:02:56 +00004498PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004499_PyUnicode_EncodeUTF7(PyObject *str,
4500 int base64SetO,
4501 int base64WhiteSpace,
4502 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004504 int kind;
4505 void *data;
4506 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004507 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004509 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004510 unsigned int base64bits = 0;
4511 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512 char * out;
4513 char * start;
4514
Benjamin Petersonbac79492012-01-14 13:34:47 -05004515 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 return NULL;
4517 kind = PyUnicode_KIND(str);
4518 data = PyUnicode_DATA(str);
4519 len = PyUnicode_GET_LENGTH(str);
4520
4521 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004522 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004523
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004524 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004525 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004526 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004527 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 if (v == NULL)
4529 return NULL;
4530
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004531 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004532 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004533 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 if (inShift) {
4536 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4537 /* shifting out */
4538 if (base64bits) { /* output remaining bits */
4539 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4540 base64buffer = 0;
4541 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
4543 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004544 /* Characters not in the BASE64 set implicitly unshift the sequence
4545 so no '-' is required, except if the character is itself a '-' */
4546 if (IS_BASE64(ch) || ch == '-') {
4547 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 *out++ = (char) ch;
4550 }
4551 else {
4552 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004553 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004555 else { /* not in a shift sequence */
4556 if (ch == '+') {
4557 *out++ = '+';
4558 *out++ = '-';
4559 }
4560 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4561 *out++ = (char) ch;
4562 }
4563 else {
4564 *out++ = '+';
4565 inShift = 1;
4566 goto encode_char;
4567 }
4568 }
4569 continue;
4570encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004572 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004573
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 /* code first surrogate */
4575 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004576 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 while (base64bits >= 6) {
4578 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4579 base64bits -= 6;
4580 }
4581 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004582 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 base64bits += 16;
4585 base64buffer = (base64buffer << 16) | ch;
4586 while (base64bits >= 6) {
4587 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4588 base64bits -= 6;
4589 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004590 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004591 if (base64bits)
4592 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4593 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004594 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004595 if (_PyBytes_Resize(&v, out - start) < 0)
4596 return NULL;
4597 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004599PyObject *
4600PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4601 Py_ssize_t size,
4602 int base64SetO,
4603 int base64WhiteSpace,
4604 const char *errors)
4605{
4606 PyObject *result;
4607 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4608 if (tmp == NULL)
4609 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004610 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004611 base64WhiteSpace, errors);
4612 Py_DECREF(tmp);
4613 return result;
4614}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615
Antoine Pitrou244651a2009-05-04 18:56:13 +00004616#undef IS_BASE64
4617#undef FROM_BASE64
4618#undef TO_BASE64
4619#undef DECODE_DIRECT
4620#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621
Guido van Rossumd57fd912000-03-10 22:53:23 +00004622/* --- UTF-8 Codec -------------------------------------------------------- */
4623
Alexander Belopolsky40018472011-02-26 01:02:56 +00004624PyObject *
4625PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004626 Py_ssize_t size,
4627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004628{
Walter Dörwald69652032004-09-07 20:24:22 +00004629 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4630}
4631
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004632#include "stringlib/asciilib.h"
4633#include "stringlib/codecs.h"
4634#include "stringlib/undef.h"
4635
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004636#include "stringlib/ucs1lib.h"
4637#include "stringlib/codecs.h"
4638#include "stringlib/undef.h"
4639
4640#include "stringlib/ucs2lib.h"
4641#include "stringlib/codecs.h"
4642#include "stringlib/undef.h"
4643
4644#include "stringlib/ucs4lib.h"
4645#include "stringlib/codecs.h"
4646#include "stringlib/undef.h"
4647
Antoine Pitrouab868312009-01-10 15:40:25 +00004648/* Mask to quickly check whether a C 'long' contains a
4649 non-ASCII, UTF8-encoded char. */
4650#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004651# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004652#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004653# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004654#else
4655# error C 'long' size should be either 4 or 8!
4656#endif
4657
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004658static Py_ssize_t
4659ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004660{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004662 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004663
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004664 /*
4665 * Issue #17237: m68k is a bit different from most architectures in
4666 * that objects do not use "natural alignment" - for example, int and
4667 * long are only aligned at 2-byte boundaries. Therefore the assert()
4668 * won't work; also, tests have shown that skipping the "optimised
4669 * version" will even speed up m68k.
4670 */
4671#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004673 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4674 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675 /* Fast path, see in STRINGLIB(utf8_decode) for
4676 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004677 /* Help allocation */
4678 const char *_p = p;
4679 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 while (_p < aligned_end) {
4681 unsigned long value = *(const unsigned long *) _p;
4682 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004683 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004684 *((unsigned long *)q) = value;
4685 _p += SIZEOF_LONG;
4686 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 p = _p;
4689 while (p < end) {
4690 if ((unsigned char)*p & 0x80)
4691 break;
4692 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004693 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004695 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004697#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698 while (p < end) {
4699 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4700 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004701 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004702 /* Help allocation */
4703 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704 while (_p < aligned_end) {
4705 unsigned long value = *(unsigned long *) _p;
4706 if (value & ASCII_CHAR_MASK)
4707 break;
4708 _p += SIZEOF_LONG;
4709 }
4710 p = _p;
4711 if (_p == end)
4712 break;
4713 }
4714 if ((unsigned char)*p & 0x80)
4715 break;
4716 ++p;
4717 }
4718 memcpy(dest, start, p - start);
4719 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004720}
Antoine Pitrouab868312009-01-10 15:40:25 +00004721
Victor Stinner785938e2011-12-11 20:09:03 +01004722PyObject *
4723PyUnicode_DecodeUTF8Stateful(const char *s,
4724 Py_ssize_t size,
4725 const char *errors,
4726 Py_ssize_t *consumed)
4727{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004729 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731
4732 Py_ssize_t startinpos;
4733 Py_ssize_t endinpos;
4734 const char *errmsg = "";
4735 PyObject *errorHandler = NULL;
4736 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004737
4738 if (size == 0) {
4739 if (consumed)
4740 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004741 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004742 }
4743
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004744 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4745 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004746 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004747 *consumed = 1;
4748 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004749 }
4750
Victor Stinner8f674cc2013-04-17 23:02:17 +02004751 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004752 writer.min_length = size;
4753 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004755
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004756 writer.pos = ascii_decode(s, end, writer.data);
4757 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 while (s < end) {
4759 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004760 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004761 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 if (PyUnicode_IS_ASCII(writer.buffer))
4763 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004765 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004767 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 } else {
4769 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004770 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 }
4772
4773 switch (ch) {
4774 case 0:
4775 if (s == end || consumed)
4776 goto End;
4777 errmsg = "unexpected end of data";
4778 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004779 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004780 break;
4781 case 1:
4782 errmsg = "invalid start byte";
4783 startinpos = s - starts;
4784 endinpos = startinpos + 1;
4785 break;
4786 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004787 case 3:
4788 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004789 errmsg = "invalid continuation byte";
4790 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004791 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 break;
4793 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004794 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795 goto onError;
4796 continue;
4797 }
4798
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004799 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 errors, &errorHandler,
4801 "utf-8", errmsg,
4802 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004803 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004804 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004805 }
4806
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004808 if (consumed)
4809 *consumed = s - starts;
4810
4811 Py_XDECREF(errorHandler);
4812 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004813 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814
4815onError:
4816 Py_XDECREF(errorHandler);
4817 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004818 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004819 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004820}
4821
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822#ifdef __APPLE__
4823
4824/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004825 used to decode the command line arguments on Mac OS X.
4826
4827 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004828 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829
4830wchar_t*
4831_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4832{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004833 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004834 wchar_t *unicode;
4835 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836
4837 /* Note: size will always be longer than the resulting Unicode
4838 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004839 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004841 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842 if (!unicode)
4843 return NULL;
4844
4845 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004852#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004853 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004854#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004855 if (ch > 0xFF) {
4856#if SIZEOF_WCHAR_T == 4
4857 assert(0);
4858#else
4859 assert(Py_UNICODE_IS_SURROGATE(ch));
4860 /* compute and append the two surrogates: */
4861 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4862 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4863#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 else {
4866 if (!ch && s == e)
4867 break;
4868 /* surrogateescape */
4869 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4870 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004871 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004873 return unicode;
4874}
4875
4876#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004878/* Primary internal function which creates utf8 encoded bytes objects.
4879
4880 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004881 and allocate exactly as much space needed at the end. Else allocate the
4882 maximum possible needed (4 result bytes per Unicode character), and return
4883 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004884*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004885PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004886_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004887{
Victor Stinner6099a032011-12-18 14:22:26 +01004888 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889 void *data;
4890 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004892 if (!PyUnicode_Check(unicode)) {
4893 PyErr_BadArgument();
4894 return NULL;
4895 }
4896
4897 if (PyUnicode_READY(unicode) == -1)
4898 return NULL;
4899
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004900 if (PyUnicode_UTF8(unicode))
4901 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4902 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004903
4904 kind = PyUnicode_KIND(unicode);
4905 data = PyUnicode_DATA(unicode);
4906 size = PyUnicode_GET_LENGTH(unicode);
4907
Benjamin Petersonead6b532011-12-20 17:23:42 -06004908 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004909 default:
4910 assert(0);
4911 case PyUnicode_1BYTE_KIND:
4912 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4913 assert(!PyUnicode_IS_ASCII(unicode));
4914 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4915 case PyUnicode_2BYTE_KIND:
4916 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4917 case PyUnicode_4BYTE_KIND:
4918 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004919 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004920}
4921
Alexander Belopolsky40018472011-02-26 01:02:56 +00004922PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004923PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4924 Py_ssize_t size,
4925 const char *errors)
4926{
4927 PyObject *v, *unicode;
4928
4929 unicode = PyUnicode_FromUnicode(s, size);
4930 if (unicode == NULL)
4931 return NULL;
4932 v = _PyUnicode_AsUTF8String(unicode, errors);
4933 Py_DECREF(unicode);
4934 return v;
4935}
4936
4937PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004938PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004939{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004940 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004941}
4942
Walter Dörwald41980ca2007-08-16 21:55:45 +00004943/* --- UTF-32 Codec ------------------------------------------------------- */
4944
4945PyObject *
4946PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004947 Py_ssize_t size,
4948 const char *errors,
4949 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950{
4951 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4952}
4953
4954PyObject *
4955PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004956 Py_ssize_t size,
4957 const char *errors,
4958 int *byteorder,
4959 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960{
4961 const char *starts = s;
4962 Py_ssize_t startinpos;
4963 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004964 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004965 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004966 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004967 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004968 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969 PyObject *errorHandler = NULL;
4970 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004971
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972 q = (unsigned char *)s;
4973 e = q + size;
4974
4975 if (byteorder)
4976 bo = *byteorder;
4977
4978 /* Check for BOM marks (U+FEFF) in the input and adjust current
4979 byte order setting accordingly. In native mode, the leading BOM
4980 mark is skipped, in all other modes, it is copied to the output
4981 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004982 if (bo == 0 && size >= 4) {
4983 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4984 if (bom == 0x0000FEFF) {
4985 bo = -1;
4986 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004988 else if (bom == 0xFFFE0000) {
4989 bo = 1;
4990 q += 4;
4991 }
4992 if (byteorder)
4993 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004994 }
4995
Victor Stinnere64322e2012-10-30 23:12:47 +01004996 if (q == e) {
4997 if (consumed)
4998 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004999 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000 }
5001
Victor Stinnere64322e2012-10-30 23:12:47 +01005002#ifdef WORDS_BIGENDIAN
5003 le = bo < 0;
5004#else
5005 le = bo <= 0;
5006#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005007 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005008
Victor Stinner8f674cc2013-04-17 23:02:17 +02005009 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005010 writer.min_length = (e - q + 3) / 4;
5011 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005012 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005013
Victor Stinnere64322e2012-10-30 23:12:47 +01005014 while (1) {
5015 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005016 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005017
Victor Stinnere64322e2012-10-30 23:12:47 +01005018 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005019 enum PyUnicode_Kind kind = writer.kind;
5020 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005022 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005023 if (le) {
5024 do {
5025 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5026 if (ch > maxch)
5027 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005028 if (kind != PyUnicode_1BYTE_KIND &&
5029 Py_UNICODE_IS_SURROGATE(ch))
5030 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005031 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005032 q += 4;
5033 } while (q <= last);
5034 }
5035 else {
5036 do {
5037 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5038 if (ch > maxch)
5039 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005040 if (kind != PyUnicode_1BYTE_KIND &&
5041 Py_UNICODE_IS_SURROGATE(ch))
5042 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005043 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005044 q += 4;
5045 } while (q <= last);
5046 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005047 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 }
5049
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005050 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005051 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005052 startinpos = ((const char *)q) - starts;
5053 endinpos = startinpos + 4;
5054 }
5055 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005056 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005058 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005059 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005060 startinpos = ((const char *)q) - starts;
5061 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005063 else {
5064 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005065 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005066 goto onError;
5067 q += 4;
5068 continue;
5069 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005070 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005071 startinpos = ((const char *)q) - starts;
5072 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005073 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005074
5075 /* The remaining input chars are ignored if the callback
5076 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005077 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005079 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005081 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005082 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 }
5084
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005086 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005087
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088 Py_XDECREF(errorHandler);
5089 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005090 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091
Benjamin Peterson29060642009-01-31 22:14:21 +00005092 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005093 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094 Py_XDECREF(errorHandler);
5095 Py_XDECREF(exc);
5096 return NULL;
5097}
5098
5099PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005100_PyUnicode_EncodeUTF32(PyObject *str,
5101 const char *errors,
5102 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 int kind;
5105 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005106 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005107 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005108 unsigned char *p;
5109 Py_ssize_t nsize, i;
5110 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005111#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005112 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005114 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005116 const char *encoding;
5117 PyObject *errorHandler = NULL;
5118 PyObject *exc = NULL;
5119 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005120
Serhiy Storchaka30793282014-01-04 22:44:01 +02005121#define STORECHAR(CH) \
5122 do { \
5123 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5124 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5125 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5126 p[iorder[0]] = (CH) & 0xff; \
5127 p += 4; \
5128 } while(0)
5129
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005130 if (!PyUnicode_Check(str)) {
5131 PyErr_BadArgument();
5132 return NULL;
5133 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005134 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005135 return NULL;
5136 kind = PyUnicode_KIND(str);
5137 data = PyUnicode_DATA(str);
5138 len = PyUnicode_GET_LENGTH(str);
5139
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005140 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 if (nsize > PY_SSIZE_T_MAX / 4)
5142 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005143 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144 if (v == NULL)
5145 return NULL;
5146
Serhiy Storchaka30793282014-01-04 22:44:01 +02005147 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005148 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005149 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005150 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005151 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005152
Serhiy Storchaka30793282014-01-04 22:44:01 +02005153 if (byteorder == -1) {
5154 /* force LE */
5155 iorder[0] = 0;
5156 iorder[1] = 1;
5157 iorder[2] = 2;
5158 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005159 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005160 }
5161 else if (byteorder == 1) {
5162 /* force BE */
5163 iorder[0] = 3;
5164 iorder[1] = 2;
5165 iorder[2] = 1;
5166 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005167 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005168 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005169 else
5170 encoding = "utf-32";
5171
5172 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005173 for (i = 0; i < len; i++)
5174 STORECHAR(PyUnicode_READ(kind, data, i));
5175 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005176 }
5177
Serhiy Storchaka30793282014-01-04 22:44:01 +02005178 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005179 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005180 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5181 i++;
5182 assert(ch <= MAX_UNICODE);
5183 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5184 STORECHAR(ch);
5185 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005186 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005187
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005188 rep = unicode_encode_call_errorhandler(
5189 errors, &errorHandler,
5190 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005191 str, &exc, i-1, i, &i);
5192
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 if (!rep)
5194 goto error;
5195
5196 if (PyBytes_Check(rep)) {
5197 repsize = PyBytes_GET_SIZE(rep);
5198 if (repsize & 3) {
5199 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005200 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 "surrogates not allowed");
5202 goto error;
5203 }
5204 moreunits = repsize / 4;
5205 }
5206 else {
5207 assert(PyUnicode_Check(rep));
5208 if (PyUnicode_READY(rep) < 0)
5209 goto error;
5210 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5211 if (!PyUnicode_IS_ASCII(rep)) {
5212 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005213 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005214 "surrogates not allowed");
5215 goto error;
5216 }
5217 }
5218
5219 /* four bytes are reserved for each surrogate */
5220 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005221 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005222 Py_ssize_t morebytes = 4 * (moreunits - 1);
5223 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5224 /* integer overflow */
5225 PyErr_NoMemory();
5226 goto error;
5227 }
5228 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5229 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005230 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005231 }
5232
5233 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005234 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5235 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005236 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005237 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005238 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005239 repdata = PyUnicode_1BYTE_DATA(rep);
5240 while (repsize--) {
5241 Py_UCS4 ch = *repdata++;
5242 STORECHAR(ch);
5243 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005244 }
5245
5246 Py_CLEAR(rep);
5247 }
5248
5249 /* Cut back to size actually needed. This is necessary for, for example,
5250 encoding of a string containing isolated surrogates and the 'ignore'
5251 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005252 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005253 if (nsize != PyBytes_GET_SIZE(v))
5254 _PyBytes_Resize(&v, nsize);
5255 Py_XDECREF(errorHandler);
5256 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005257 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005258 error:
5259 Py_XDECREF(rep);
5260 Py_XDECREF(errorHandler);
5261 Py_XDECREF(exc);
5262 Py_XDECREF(v);
5263 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005264#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005265}
5266
Alexander Belopolsky40018472011-02-26 01:02:56 +00005267PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005268PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5269 Py_ssize_t size,
5270 const char *errors,
5271 int byteorder)
5272{
5273 PyObject *result;
5274 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5275 if (tmp == NULL)
5276 return NULL;
5277 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5278 Py_DECREF(tmp);
5279 return result;
5280}
5281
5282PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005283PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005284{
Victor Stinnerb960b342011-11-20 19:12:52 +01005285 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005286}
5287
Guido van Rossumd57fd912000-03-10 22:53:23 +00005288/* --- UTF-16 Codec ------------------------------------------------------- */
5289
Tim Peters772747b2001-08-09 22:21:55 +00005290PyObject *
5291PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005292 Py_ssize_t size,
5293 const char *errors,
5294 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005295{
Walter Dörwald69652032004-09-07 20:24:22 +00005296 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5297}
5298
5299PyObject *
5300PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005301 Py_ssize_t size,
5302 const char *errors,
5303 int *byteorder,
5304 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005305{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005306 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005307 Py_ssize_t startinpos;
5308 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005309 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005310 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005311 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005312 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005313 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005314 PyObject *errorHandler = NULL;
5315 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005316 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005317
Tim Peters772747b2001-08-09 22:21:55 +00005318 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005320
5321 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005322 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005323
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005324 /* Check for BOM marks (U+FEFF) in the input and adjust current
5325 byte order setting accordingly. In native mode, the leading BOM
5326 mark is skipped, in all other modes, it is copied to the output
5327 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328 if (bo == 0 && size >= 2) {
5329 const Py_UCS4 bom = (q[1] << 8) | q[0];
5330 if (bom == 0xFEFF) {
5331 q += 2;
5332 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 else if (bom == 0xFFFE) {
5335 q += 2;
5336 bo = 1;
5337 }
5338 if (byteorder)
5339 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005340 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005341
Antoine Pitrou63065d72012-05-15 23:48:04 +02005342 if (q == e) {
5343 if (consumed)
5344 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005345 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005346 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005347
Christian Heimes743e0cd2012-10-17 23:52:17 +02005348#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005349 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005350 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005351#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005352 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005353 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005354#endif
Tim Peters772747b2001-08-09 22:21:55 +00005355
Antoine Pitrou63065d72012-05-15 23:48:04 +02005356 /* Note: size will always be longer than the resulting Unicode
5357 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005358 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005359 writer.min_length = (e - q + 1) / 2;
5360 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005361 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005362
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 while (1) {
5364 Py_UCS4 ch = 0;
5365 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005368 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005370 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 native_ordering);
5372 else
5373 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005374 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005375 native_ordering);
5376 } else if (kind == PyUnicode_2BYTE_KIND) {
5377 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005378 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005379 native_ordering);
5380 } else {
5381 assert(kind == PyUnicode_4BYTE_KIND);
5382 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005383 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005384 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005385 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005386 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005387
Antoine Pitrou63065d72012-05-15 23:48:04 +02005388 switch (ch)
5389 {
5390 case 0:
5391 /* remaining byte at the end? (size should be even) */
5392 if (q == e || consumed)
5393 goto End;
5394 errmsg = "truncated data";
5395 startinpos = ((const char *)q) - starts;
5396 endinpos = ((const char *)e) - starts;
5397 break;
5398 /* The remaining input chars are ignored if the callback
5399 chooses to skip the input */
5400 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005401 q -= 2;
5402 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005403 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005404 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005405 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005406 endinpos = ((const char *)e) - starts;
5407 break;
5408 case 2:
5409 errmsg = "illegal encoding";
5410 startinpos = ((const char *)q) - 2 - starts;
5411 endinpos = startinpos + 2;
5412 break;
5413 case 3:
5414 errmsg = "illegal UTF-16 surrogate";
5415 startinpos = ((const char *)q) - 4 - starts;
5416 endinpos = startinpos + 2;
5417 break;
5418 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005419 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005420 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005421 continue;
5422 }
5423
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005424 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005425 errors,
5426 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005428 &starts,
5429 (const char **)&e,
5430 &startinpos,
5431 &endinpos,
5432 &exc,
5433 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005434 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005435 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436 }
5437
Antoine Pitrou63065d72012-05-15 23:48:04 +02005438End:
Walter Dörwald69652032004-09-07 20:24:22 +00005439 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005440 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005441
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005442 Py_XDECREF(errorHandler);
5443 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005444 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445
Benjamin Peterson29060642009-01-31 22:14:21 +00005446 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005447 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005448 Py_XDECREF(errorHandler);
5449 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005450 return NULL;
5451}
5452
Tim Peters772747b2001-08-09 22:21:55 +00005453PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005454_PyUnicode_EncodeUTF16(PyObject *str,
5455 const char *errors,
5456 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005457{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005458 enum PyUnicode_Kind kind;
5459 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005460 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005461 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005462 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005463 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005464#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005465 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005466#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005467 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005468#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 const char *encoding;
5470 Py_ssize_t nsize, pos;
5471 PyObject *errorHandler = NULL;
5472 PyObject *exc = NULL;
5473 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005474
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005475 if (!PyUnicode_Check(str)) {
5476 PyErr_BadArgument();
5477 return NULL;
5478 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005479 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005480 return NULL;
5481 kind = PyUnicode_KIND(str);
5482 data = PyUnicode_DATA(str);
5483 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005484
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005485 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005486 if (kind == PyUnicode_4BYTE_KIND) {
5487 const Py_UCS4 *in = (const Py_UCS4 *)data;
5488 const Py_UCS4 *end = in + len;
5489 while (in < end)
5490 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005491 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005492 }
5493 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005494 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005495 nsize = len + pairs + (byteorder == 0);
5496 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497 if (v == NULL)
5498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005500 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005501 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005502 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005503 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005504 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005505 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005506 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005507
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005508 if (kind == PyUnicode_1BYTE_KIND) {
5509 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5510 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005511 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005512
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005513 if (byteorder < 0)
5514 encoding = "utf-16-le";
5515 else if (byteorder > 0)
5516 encoding = "utf-16-be";
5517 else
5518 encoding = "utf-16";
5519
5520 pos = 0;
5521 while (pos < len) {
5522 Py_ssize_t repsize, moreunits;
5523
5524 if (kind == PyUnicode_2BYTE_KIND) {
5525 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5526 &out, native_ordering);
5527 }
5528 else {
5529 assert(kind == PyUnicode_4BYTE_KIND);
5530 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5531 &out, native_ordering);
5532 }
5533 if (pos == len)
5534 break;
5535
5536 rep = unicode_encode_call_errorhandler(
5537 errors, &errorHandler,
5538 encoding, "surrogates not allowed",
5539 str, &exc, pos, pos + 1, &pos);
5540 if (!rep)
5541 goto error;
5542
5543 if (PyBytes_Check(rep)) {
5544 repsize = PyBytes_GET_SIZE(rep);
5545 if (repsize & 1) {
5546 raise_encode_exception(&exc, encoding,
5547 str, pos - 1, pos,
5548 "surrogates not allowed");
5549 goto error;
5550 }
5551 moreunits = repsize / 2;
5552 }
5553 else {
5554 assert(PyUnicode_Check(rep));
5555 if (PyUnicode_READY(rep) < 0)
5556 goto error;
5557 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5558 if (!PyUnicode_IS_ASCII(rep)) {
5559 raise_encode_exception(&exc, encoding,
5560 str, pos - 1, pos,
5561 "surrogates not allowed");
5562 goto error;
5563 }
5564 }
5565
5566 /* two bytes are reserved for each surrogate */
5567 if (moreunits > 1) {
5568 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5569 Py_ssize_t morebytes = 2 * (moreunits - 1);
5570 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5571 /* integer overflow */
5572 PyErr_NoMemory();
5573 goto error;
5574 }
5575 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5576 goto error;
5577 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5578 }
5579
5580 if (PyBytes_Check(rep)) {
5581 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5582 out += moreunits;
5583 } else /* rep is unicode */ {
5584 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5585 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5586 &out, native_ordering);
5587 }
5588
5589 Py_CLEAR(rep);
5590 }
5591
5592 /* Cut back to size actually needed. This is necessary for, for example,
5593 encoding of a string containing isolated surrogates and the 'ignore' handler
5594 is used. */
5595 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5596 if (nsize != PyBytes_GET_SIZE(v))
5597 _PyBytes_Resize(&v, nsize);
5598 Py_XDECREF(errorHandler);
5599 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005600 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005601 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005602 error:
5603 Py_XDECREF(rep);
5604 Py_XDECREF(errorHandler);
5605 Py_XDECREF(exc);
5606 Py_XDECREF(v);
5607 return NULL;
5608#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609}
5610
Alexander Belopolsky40018472011-02-26 01:02:56 +00005611PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005612PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5613 Py_ssize_t size,
5614 const char *errors,
5615 int byteorder)
5616{
5617 PyObject *result;
5618 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5619 if (tmp == NULL)
5620 return NULL;
5621 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5622 Py_DECREF(tmp);
5623 return result;
5624}
5625
5626PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005627PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005629 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630}
5631
5632/* --- Unicode Escape Codec ----------------------------------------------- */
5633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005634/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5635 if all the escapes in the string make it still a valid ASCII string.
5636 Returns -1 if any escapes were found which cause the string to
5637 pop out of ASCII range. Otherwise returns the length of the
5638 required buffer to hold the string.
5639 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005640static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005641length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5642{
5643 const unsigned char *p = (const unsigned char *)s;
5644 const unsigned char *end = p + size;
5645 Py_ssize_t length = 0;
5646
5647 if (size < 0)
5648 return -1;
5649
5650 for (; p < end; ++p) {
5651 if (*p > 127) {
5652 /* Non-ASCII */
5653 return -1;
5654 }
5655 else if (*p != '\\') {
5656 /* Normal character */
5657 ++length;
5658 }
5659 else {
5660 /* Backslash-escape, check next char */
5661 ++p;
5662 /* Escape sequence reaches till end of string or
5663 non-ASCII follow-up. */
5664 if (p >= end || *p > 127)
5665 return -1;
5666 switch (*p) {
5667 case '\n':
5668 /* backslash + \n result in zero characters */
5669 break;
5670 case '\\': case '\'': case '\"':
5671 case 'b': case 'f': case 't':
5672 case 'n': case 'r': case 'v': case 'a':
5673 ++length;
5674 break;
5675 case '0': case '1': case '2': case '3':
5676 case '4': case '5': case '6': case '7':
5677 case 'x': case 'u': case 'U': case 'N':
5678 /* these do not guarantee ASCII characters */
5679 return -1;
5680 default:
5681 /* count the backslash + the other character */
5682 length += 2;
5683 }
5684 }
5685 }
5686 return length;
5687}
5688
Fredrik Lundh06d12682001-01-24 07:59:11 +00005689static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005690
Alexander Belopolsky40018472011-02-26 01:02:56 +00005691PyObject *
5692PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005693 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005694 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005696 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005697 Py_ssize_t startinpos;
5698 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005699 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005701 char* message;
5702 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005703 PyObject *errorHandler = NULL;
5704 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005705 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005706
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005707 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005708 if (len == 0)
5709 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710
5711 /* After length_of_escaped_ascii_string() there are two alternatives,
5712 either the string is pure ASCII with named escapes like \n, etc.
5713 and we determined it's exact size (common case)
5714 or it contains \x, \u, ... escape sequences. then we create a
5715 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005716 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005717 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005718 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005719 }
5720 else {
5721 /* Escaped strings will always be longer than the resulting
5722 Unicode string, so we start with size here and then reduce the
5723 length after conversion to the true value.
5724 (but if the error callback returns a long replacement string
5725 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005726 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005727 }
5728
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005730 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005732
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733 while (s < end) {
5734 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005735 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005736 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737
5738 /* Non-escape characters are interpreted as Unicode ordinals */
5739 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005740 x = (unsigned char)*s;
5741 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005742 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005743 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 continue;
5745 }
5746
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005748 /* \ - Escapes */
5749 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005750 c = *s++;
5751 if (s > end)
5752 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005753
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005754 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755
Benjamin Peterson29060642009-01-31 22:14:21 +00005756 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005757#define WRITECHAR(ch) \
5758 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005759 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005760 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005761 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005762
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005764 case '\\': WRITECHAR('\\'); break;
5765 case '\'': WRITECHAR('\''); break;
5766 case '\"': WRITECHAR('\"'); break;
5767 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005768 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005769 case 'f': WRITECHAR('\014'); break;
5770 case 't': WRITECHAR('\t'); break;
5771 case 'n': WRITECHAR('\n'); break;
5772 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005773 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005774 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005775 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005776 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777
Benjamin Peterson29060642009-01-31 22:14:21 +00005778 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005779 case '0': case '1': case '2': case '3':
5780 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005781 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005782 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005783 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005784 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005785 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005787 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005788 break;
5789
Benjamin Peterson29060642009-01-31 22:14:21 +00005790 /* hex escapes */
5791 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005793 digits = 2;
5794 message = "truncated \\xXX escape";
5795 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796
Benjamin Peterson29060642009-01-31 22:14:21 +00005797 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005798 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 digits = 4;
5800 message = "truncated \\uXXXX escape";
5801 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005802
Benjamin Peterson29060642009-01-31 22:14:21 +00005803 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005804 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005805 digits = 8;
5806 message = "truncated \\UXXXXXXXX escape";
5807 hexescape:
5808 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005809 if (end - s < digits) {
5810 /* count only hex digits */
5811 for (; s < end; ++s) {
5812 c = (unsigned char)*s;
5813 if (!Py_ISXDIGIT(c))
5814 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005815 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005816 goto error;
5817 }
5818 for (; digits--; ++s) {
5819 c = (unsigned char)*s;
5820 if (!Py_ISXDIGIT(c))
5821 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005822 chr = (chr<<4) & ~0xF;
5823 if (c >= '0' && c <= '9')
5824 chr += c - '0';
5825 else if (c >= 'a' && c <= 'f')
5826 chr += 10 + c - 'a';
5827 else
5828 chr += 10 + c - 'A';
5829 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005830 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005831 /* _decoding_error will have already written into the
5832 target buffer. */
5833 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005835 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005836 message = "illegal Unicode character";
5837 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005838 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005839 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005840 break;
5841
Benjamin Peterson29060642009-01-31 22:14:21 +00005842 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005843 case 'N':
5844 message = "malformed \\N character escape";
5845 if (ucnhash_CAPI == NULL) {
5846 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5848 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005849 if (ucnhash_CAPI == NULL)
5850 goto ucnhashError;
5851 }
5852 if (*s == '{') {
5853 const char *start = s+1;
5854 /* look for the closing brace */
5855 while (*s != '}' && s < end)
5856 s++;
5857 if (s > start && s < end && *s == '}') {
5858 /* found a name. look it up in the unicode database */
5859 message = "unknown Unicode character name";
5860 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005861 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005862 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005863 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005864 goto store;
5865 }
5866 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005867 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005868
5869 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 message = "\\ at end of string";
5872 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005873 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 }
5875 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005877 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005878 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005879 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005881 continue;
5882
5883 error:
5884 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005885 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005886 errors, &errorHandler,
5887 "unicodeescape", message,
5888 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005889 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005890 goto onError;
5891 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005893#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005894
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005895 Py_XDECREF(errorHandler);
5896 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005897 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005898
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005900 PyErr_SetString(
5901 PyExc_UnicodeError,
5902 "\\N escapes not supported (can't load unicodedata module)"
5903 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005904 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005905 Py_XDECREF(errorHandler);
5906 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005907 return NULL;
5908
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005910 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 Py_XDECREF(errorHandler);
5912 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 return NULL;
5914}
5915
5916/* Return a Unicode-Escape string version of the Unicode object.
5917
5918 If quotes is true, the string is enclosed in u"" or u'' quotes as
5919 appropriate.
5920
5921*/
5922
Alexander Belopolsky40018472011-02-26 01:02:56 +00005923PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005924PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005926 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005927 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 int kind;
5930 void *data;
5931 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932
Ezio Melottie7f90372012-10-05 03:33:31 +03005933 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005934 escape.
5935
Ezio Melottie7f90372012-10-05 03:33:31 +03005936 For UCS1 strings it's '\xxx', 4 bytes per source character.
5937 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5938 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005939 */
5940
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005941 if (!PyUnicode_Check(unicode)) {
5942 PyErr_BadArgument();
5943 return NULL;
5944 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005945 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005946 return NULL;
5947 len = PyUnicode_GET_LENGTH(unicode);
5948 kind = PyUnicode_KIND(unicode);
5949 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005950 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5952 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5953 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5954 }
5955
5956 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 return PyBytes_FromStringAndSize(NULL, 0);
5958
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005959 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005960 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005961
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005962 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005964 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 if (repr == NULL)
5967 return NULL;
5968
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005969 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005971 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005972 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005973
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 /* Escape backslashes */
5975 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 *p++ = '\\';
5977 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005978 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005979 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005980
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005981 /* Map 21-bit characters to '\U00xxxxxx' */
5982 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005983 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005984 *p++ = '\\';
5985 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005986 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5987 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5988 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5989 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5990 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5991 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5993 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005995 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005996
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005998 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 *p++ = '\\';
6000 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006001 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6002 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6003 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6004 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006006
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006007 /* Map special whitespace to '\t', \n', '\r' */
6008 else if (ch == '\t') {
6009 *p++ = '\\';
6010 *p++ = 't';
6011 }
6012 else if (ch == '\n') {
6013 *p++ = '\\';
6014 *p++ = 'n';
6015 }
6016 else if (ch == '\r') {
6017 *p++ = '\\';
6018 *p++ = 'r';
6019 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006020
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006021 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006022 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006024 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006025 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6026 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006027 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006028
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 /* Copy everything else as-is */
6030 else
6031 *p++ = (char) ch;
6032 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006034 assert(p - PyBytes_AS_STRING(repr) > 0);
6035 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6036 return NULL;
6037 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038}
6039
Alexander Belopolsky40018472011-02-26 01:02:56 +00006040PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006041PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6042 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006044 PyObject *result;
6045 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6046 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006048 result = PyUnicode_AsUnicodeEscapeString(tmp);
6049 Py_DECREF(tmp);
6050 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051}
6052
6053/* --- Raw Unicode Escape Codec ------------------------------------------- */
6054
Alexander Belopolsky40018472011-02-26 01:02:56 +00006055PyObject *
6056PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006057 Py_ssize_t size,
6058 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006061 Py_ssize_t startinpos;
6062 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006063 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 const char *end;
6065 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006066 PyObject *errorHandler = NULL;
6067 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006068
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006069 if (size == 0)
6070 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006071
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 /* Escaped strings will always be longer than the resulting
6073 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006074 length after conversion to the true value. (But decoding error
6075 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006076 _PyUnicodeWriter_Init(&writer);
6077 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006078
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 end = s + size;
6080 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 unsigned char c;
6082 Py_UCS4 x;
6083 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006084 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 /* Non-escape characters are interpreted as Unicode ordinals */
6087 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006088 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006089 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006090 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006092 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 startinpos = s-starts;
6094
6095 /* \u-escapes are only interpreted iff the number of leading
6096 backslashes if odd */
6097 bs = s;
6098 for (;s < end;) {
6099 if (*s != '\\')
6100 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006101 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006102 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006103 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006104 }
6105 if (((s - bs) & 1) == 0 ||
6106 s >= end ||
6107 (*s != 'u' && *s != 'U')) {
6108 continue;
6109 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006110 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 count = *s=='u' ? 4 : 8;
6112 s++;
6113
6114 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 for (x = 0, i = 0; i < count; ++i, ++s) {
6116 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006117 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006119 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 errors, &errorHandler,
6121 "rawunicodeescape", "truncated \\uXXXX",
6122 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006123 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 goto onError;
6125 goto nextByte;
6126 }
6127 x = (x<<4) & ~0xF;
6128 if (c >= '0' && c <= '9')
6129 x += c - '0';
6130 else if (c >= 'a' && c <= 'f')
6131 x += 10 + c - 'a';
6132 else
6133 x += 10 + c - 'A';
6134 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006135 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006136 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006137 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006138 }
6139 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006140 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006141 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006142 errors, &errorHandler,
6143 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006144 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006145 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006146 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006147 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006148 nextByte:
6149 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006151 Py_XDECREF(errorHandler);
6152 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006153 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006154
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006156 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006157 Py_XDECREF(errorHandler);
6158 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 return NULL;
6160}
6161
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162
Alexander Belopolsky40018472011-02-26 01:02:56 +00006163PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006164PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006166 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167 char *p;
6168 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006169 Py_ssize_t expandsize, pos;
6170 int kind;
6171 void *data;
6172 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006174 if (!PyUnicode_Check(unicode)) {
6175 PyErr_BadArgument();
6176 return NULL;
6177 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006178 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 return NULL;
6180 kind = PyUnicode_KIND(unicode);
6181 data = PyUnicode_DATA(unicode);
6182 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006183 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6184 bytes, and 1 byte characters 4. */
6185 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006186
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006188 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006189
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191 if (repr == NULL)
6192 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006194 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006196 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006197 for (pos = 0; pos < len; pos++) {
6198 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006199 /* Map 32-bit characters to '\Uxxxxxxxx' */
6200 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006201 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006202 *p++ = '\\';
6203 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006204 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6205 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6206 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6207 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6208 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6209 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6211 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006212 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006213 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006214 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215 *p++ = '\\';
6216 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006217 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6218 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6219 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6220 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006222 /* Copy everything else as-is */
6223 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224 *p++ = (char) ch;
6225 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006226
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006227 assert(p > q);
6228 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006229 return NULL;
6230 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231}
6232
Alexander Belopolsky40018472011-02-26 01:02:56 +00006233PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006234PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6235 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237 PyObject *result;
6238 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6239 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006240 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006241 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6242 Py_DECREF(tmp);
6243 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244}
6245
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246/* --- Unicode Internal Codec ------------------------------------------- */
6247
Alexander Belopolsky40018472011-02-26 01:02:56 +00006248PyObject *
6249_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006250 Py_ssize_t size,
6251 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006252{
6253 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006254 Py_ssize_t startinpos;
6255 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006256 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006257 const char *end;
6258 const char *reason;
6259 PyObject *errorHandler = NULL;
6260 PyObject *exc = NULL;
6261
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006262 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006263 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006264 1))
6265 return NULL;
6266
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006267 if (size == 0)
6268 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006269
Victor Stinner8f674cc2013-04-17 23:02:17 +02006270 _PyUnicodeWriter_Init(&writer);
6271 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6272 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006274 }
6275 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006276
Victor Stinner8f674cc2013-04-17 23:02:17 +02006277 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006278 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006279 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006280 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006281 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006282 endinpos = end-starts;
6283 reason = "truncated input";
6284 goto error;
6285 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006286 /* We copy the raw representation one byte at a time because the
6287 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006288 ((char *) &uch)[0] = s[0];
6289 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006290#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006291 ((char *) &uch)[2] = s[2];
6292 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006293#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006294 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 /* We have to sanity check the raw data, otherwise doom looms for
6297 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006298 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006299 endinpos = s - starts + Py_UNICODE_SIZE;
6300 reason = "illegal code point (> 0x10FFFF)";
6301 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006302 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006303#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006304 s += Py_UNICODE_SIZE;
6305#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006306 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006307 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006308 Py_UNICODE uch2;
6309 ((char *) &uch2)[0] = s[0];
6310 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006311 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 {
Victor Stinner551ac952011-11-29 22:58:13 +01006313 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006314 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006315 }
6316 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006317#endif
6318
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006319 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006320 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006321 continue;
6322
6323 error:
6324 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006325 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006326 errors, &errorHandler,
6327 "unicode_internal", reason,
6328 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006329 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006330 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331 }
6332
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 Py_XDECREF(errorHandler);
6334 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006335 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006336
Benjamin Peterson29060642009-01-31 22:14:21 +00006337 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006338 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339 Py_XDECREF(errorHandler);
6340 Py_XDECREF(exc);
6341 return NULL;
6342}
6343
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344/* --- Latin-1 Codec ------------------------------------------------------ */
6345
Alexander Belopolsky40018472011-02-26 01:02:56 +00006346PyObject *
6347PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006348 Py_ssize_t size,
6349 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006351 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006352 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006353}
6354
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006356static void
6357make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006358 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006359 PyObject *unicode,
6360 Py_ssize_t startpos, Py_ssize_t endpos,
6361 const char *reason)
6362{
6363 if (*exceptionObject == NULL) {
6364 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006365 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006366 encoding, unicode, startpos, endpos, reason);
6367 }
6368 else {
6369 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6370 goto onError;
6371 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6372 goto onError;
6373 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6374 goto onError;
6375 return;
6376 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006377 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006378 }
6379}
6380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006382static void
6383raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006384 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006385 PyObject *unicode,
6386 Py_ssize_t startpos, Py_ssize_t endpos,
6387 const char *reason)
6388{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006389 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006390 encoding, unicode, startpos, endpos, reason);
6391 if (*exceptionObject != NULL)
6392 PyCodec_StrictErrors(*exceptionObject);
6393}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394
6395/* error handling callback helper:
6396 build arguments, call the callback and check the arguments,
6397 put the result into newpos and return the replacement string, which
6398 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006399static PyObject *
6400unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006401 PyObject **errorHandler,
6402 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006404 Py_ssize_t startpos, Py_ssize_t endpos,
6405 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006407 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006408 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 PyObject *restuple;
6410 PyObject *resunicode;
6411
6412 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006414 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 }
6417
Benjamin Petersonbac79492012-01-14 13:34:47 -05006418 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 return NULL;
6420 len = PyUnicode_GET_LENGTH(unicode);
6421
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006422 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006423 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426
6427 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006432 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 Py_DECREF(restuple);
6434 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006436 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006437 &resunicode, newpos)) {
6438 Py_DECREF(restuple);
6439 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006441 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6442 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6443 Py_DECREF(restuple);
6444 return NULL;
6445 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006446 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006447 *newpos = len + *newpos;
6448 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006449 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 Py_DECREF(restuple);
6451 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006452 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453 Py_INCREF(resunicode);
6454 Py_DECREF(restuple);
6455 return resunicode;
6456}
6457
Alexander Belopolsky40018472011-02-26 01:02:56 +00006458static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006460 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006461 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 /* input state */
6464 Py_ssize_t pos=0, size;
6465 int kind;
6466 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 /* output object */
6468 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 /* pointer into the output */
6470 char *str;
6471 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006472 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006473 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6474 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006475 PyObject *errorHandler = NULL;
6476 PyObject *exc = NULL;
6477 /* the following variable is used for caching string comparisons
6478 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6479 int known_errorHandler = -1;
6480
Benjamin Petersonbac79492012-01-14 13:34:47 -05006481 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006482 return NULL;
6483 size = PyUnicode_GET_LENGTH(unicode);
6484 kind = PyUnicode_KIND(unicode);
6485 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 /* allocate enough for a simple encoding without
6487 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006488 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006489 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006490 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006492 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006493 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494 ressize = size;
6495
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496 while (pos < size) {
6497 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006498
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 /* can we encode this? */
6500 if (c<limit) {
6501 /* no overflow check, because we know that the space is enough */
6502 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006504 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 Py_ssize_t requiredsize;
6507 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 Py_ssize_t collstart = pos;
6511 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006513 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 ++collend;
6515 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6516 if (known_errorHandler==-1) {
6517 if ((errors==NULL) || (!strcmp(errors, "strict")))
6518 known_errorHandler = 1;
6519 else if (!strcmp(errors, "replace"))
6520 known_errorHandler = 2;
6521 else if (!strcmp(errors, "ignore"))
6522 known_errorHandler = 3;
6523 else if (!strcmp(errors, "xmlcharrefreplace"))
6524 known_errorHandler = 4;
6525 else
6526 known_errorHandler = 0;
6527 }
6528 switch (known_errorHandler) {
6529 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006530 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 goto onError;
6532 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006533 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 *str++ = '?'; /* fall through */
6535 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 break;
6538 case 4: /* xmlcharrefreplace */
6539 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006540 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006542 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006544 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006546 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006548 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006550 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006551 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006552 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006554 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006556 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006557 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006558 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006559 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006560 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006561 if (requiredsize > PY_SSIZE_T_MAX - incr)
6562 goto overflow;
6563 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006565 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6566 goto overflow;
6567 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006568 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006569 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 requiredsize = 2*ressize;
6571 if (_PyBytes_Resize(&res, requiredsize))
6572 goto onError;
6573 str = PyBytes_AS_STRING(res) + respos;
6574 ressize = requiredsize;
6575 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006576 /* generate replacement */
6577 for (i = collstart; i < collend; ++i) {
6578 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 break;
6582 default:
6583 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006584 encoding, reason, unicode, &exc,
6585 collstart, collend, &newpos);
6586 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006587 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006589 if (PyBytes_Check(repunicode)) {
6590 /* Directly copy bytes result to output. */
6591 repsize = PyBytes_Size(repunicode);
6592 if (repsize > 1) {
6593 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006594 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006595 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6596 Py_DECREF(repunicode);
6597 goto overflow;
6598 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006599 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6600 Py_DECREF(repunicode);
6601 goto onError;
6602 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006603 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006604 ressize += repsize-1;
6605 }
6606 memcpy(str, PyBytes_AsString(repunicode), repsize);
6607 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006608 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006609 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006610 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006611 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006612 /* need more space? (at least enough for what we
6613 have+the replacement+the rest of the string, so
6614 we won't have to check space for encodable characters) */
6615 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006617 requiredsize = respos;
6618 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6619 goto overflow;
6620 requiredsize += repsize;
6621 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6622 goto overflow;
6623 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006624 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006625 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 requiredsize = 2*ressize;
6627 if (_PyBytes_Resize(&res, requiredsize)) {
6628 Py_DECREF(repunicode);
6629 goto onError;
6630 }
6631 str = PyBytes_AS_STRING(res) + respos;
6632 ressize = requiredsize;
6633 }
6634 /* check if there is anything unencodable in the replacement
6635 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 for (i = 0; repsize-->0; ++i, ++str) {
6637 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006639 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006640 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 Py_DECREF(repunicode);
6642 goto onError;
6643 }
6644 *str = (char)c;
6645 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006647 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006648 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006649 }
6650 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006651 /* Resize if we allocated to much */
6652 size = str - PyBytes_AS_STRING(res);
6653 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006654 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006655 if (_PyBytes_Resize(&res, size) < 0)
6656 goto onError;
6657 }
6658
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 Py_XDECREF(errorHandler);
6660 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006661 return res;
6662
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006663 overflow:
6664 PyErr_SetString(PyExc_OverflowError,
6665 "encoded result is too long for a Python string");
6666
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006667 onError:
6668 Py_XDECREF(res);
6669 Py_XDECREF(errorHandler);
6670 Py_XDECREF(exc);
6671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672}
6673
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006675PyObject *
6676PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006677 Py_ssize_t size,
6678 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006679{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006680 PyObject *result;
6681 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6682 if (unicode == NULL)
6683 return NULL;
6684 result = unicode_encode_ucs1(unicode, errors, 256);
6685 Py_DECREF(unicode);
6686 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006687}
6688
Alexander Belopolsky40018472011-02-26 01:02:56 +00006689PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006690_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691{
6692 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006693 PyErr_BadArgument();
6694 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006695 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006696 if (PyUnicode_READY(unicode) == -1)
6697 return NULL;
6698 /* Fast path: if it is a one-byte string, construct
6699 bytes object directly. */
6700 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6701 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6702 PyUnicode_GET_LENGTH(unicode));
6703 /* Non-Latin-1 characters present. Defer to above function to
6704 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006705 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006706}
6707
6708PyObject*
6709PyUnicode_AsLatin1String(PyObject *unicode)
6710{
6711 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712}
6713
6714/* --- 7-bit ASCII Codec -------------------------------------------------- */
6715
Alexander Belopolsky40018472011-02-26 01:02:56 +00006716PyObject *
6717PyUnicode_DecodeASCII(const char *s,
6718 Py_ssize_t size,
6719 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006720{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006722 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006723 int kind;
6724 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006725 Py_ssize_t startinpos;
6726 Py_ssize_t endinpos;
6727 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006728 const char *e;
6729 PyObject *errorHandler = NULL;
6730 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006731
Guido van Rossumd57fd912000-03-10 22:53:23 +00006732 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006733 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006734
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006736 if (size == 1 && (unsigned char)s[0] < 128)
6737 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006738
Victor Stinner8f674cc2013-04-17 23:02:17 +02006739 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006740 writer.min_length = size;
6741 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006742 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006743
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006745 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006746 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006747 writer.pos = outpos;
6748 if (writer.pos == size)
6749 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006750
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006751 s += writer.pos;
6752 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006753 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006754 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006756 PyUnicode_WRITE(kind, data, writer.pos, c);
6757 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 ++s;
6759 }
6760 else {
6761 startinpos = s-starts;
6762 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006763 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 errors, &errorHandler,
6765 "ascii", "ordinal not in range(128)",
6766 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006767 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006769 kind = writer.kind;
6770 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006773 Py_XDECREF(errorHandler);
6774 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006775 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006776
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006778 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006779 Py_XDECREF(errorHandler);
6780 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781 return NULL;
6782}
6783
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006785PyObject *
6786PyUnicode_EncodeASCII(const Py_UNICODE *p,
6787 Py_ssize_t size,
6788 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006789{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 PyObject *result;
6791 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6792 if (unicode == NULL)
6793 return NULL;
6794 result = unicode_encode_ucs1(unicode, errors, 128);
6795 Py_DECREF(unicode);
6796 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006797}
6798
Alexander Belopolsky40018472011-02-26 01:02:56 +00006799PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006800_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006801{
6802 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006803 PyErr_BadArgument();
6804 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006806 if (PyUnicode_READY(unicode) == -1)
6807 return NULL;
6808 /* Fast path: if it is an ASCII-only string, construct bytes object
6809 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006810 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006811 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6812 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006813 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006814}
6815
6816PyObject *
6817PyUnicode_AsASCIIString(PyObject *unicode)
6818{
6819 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006820}
6821
Victor Stinner99b95382011-07-04 14:23:54 +02006822#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006823
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006824/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006825
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006826#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827#define NEED_RETRY
6828#endif
6829
Victor Stinner3a50e702011-10-18 21:21:00 +02006830#ifndef WC_ERR_INVALID_CHARS
6831# define WC_ERR_INVALID_CHARS 0x0080
6832#endif
6833
6834static char*
6835code_page_name(UINT code_page, PyObject **obj)
6836{
6837 *obj = NULL;
6838 if (code_page == CP_ACP)
6839 return "mbcs";
6840 if (code_page == CP_UTF7)
6841 return "CP_UTF7";
6842 if (code_page == CP_UTF8)
6843 return "CP_UTF8";
6844
6845 *obj = PyBytes_FromFormat("cp%u", code_page);
6846 if (*obj == NULL)
6847 return NULL;
6848 return PyBytes_AS_STRING(*obj);
6849}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006850
Alexander Belopolsky40018472011-02-26 01:02:56 +00006851static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006852is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006853{
6854 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006855 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006856
Victor Stinner3a50e702011-10-18 21:21:00 +02006857 if (!IsDBCSLeadByteEx(code_page, *curr))
6858 return 0;
6859
6860 prev = CharPrevExA(code_page, s, curr, 0);
6861 if (prev == curr)
6862 return 1;
6863 /* FIXME: This code is limited to "true" double-byte encodings,
6864 as it assumes an incomplete character consists of a single
6865 byte. */
6866 if (curr - prev == 2)
6867 return 1;
6868 if (!IsDBCSLeadByteEx(code_page, *prev))
6869 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006870 return 0;
6871}
6872
Victor Stinner3a50e702011-10-18 21:21:00 +02006873static DWORD
6874decode_code_page_flags(UINT code_page)
6875{
6876 if (code_page == CP_UTF7) {
6877 /* The CP_UTF7 decoder only supports flags=0 */
6878 return 0;
6879 }
6880 else
6881 return MB_ERR_INVALID_CHARS;
6882}
6883
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006884/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 * Decode a byte string from a Windows code page into unicode object in strict
6886 * mode.
6887 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006888 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6889 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006890 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006891static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006892decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006893 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006894 const char *in,
6895 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006896{
Victor Stinner3a50e702011-10-18 21:21:00 +02006897 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006898 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006899 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006900
6901 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 assert(insize > 0);
6903 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6904 if (outsize <= 0)
6905 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006906
6907 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006909 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006910 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006911 if (*v == NULL)
6912 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006914 }
6915 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006917 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006918 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921 }
6922
6923 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006924 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6925 if (outsize <= 0)
6926 goto error;
6927 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006928
Victor Stinner3a50e702011-10-18 21:21:00 +02006929error:
6930 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6931 return -2;
6932 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006933 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006934}
6935
Victor Stinner3a50e702011-10-18 21:21:00 +02006936/*
6937 * Decode a byte string from a code page into unicode object with an error
6938 * handler.
6939 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006940 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006941 * UnicodeDecodeError exception and returns -1 on error.
6942 */
6943static int
6944decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006945 PyObject **v,
6946 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006947 const char *errors)
6948{
6949 const char *startin = in;
6950 const char *endin = in + size;
6951 const DWORD flags = decode_code_page_flags(code_page);
6952 /* Ideally, we should get reason from FormatMessage. This is the Windows
6953 2000 English version of the message. */
6954 const char *reason = "No mapping for the Unicode character exists "
6955 "in the target code page.";
6956 /* each step cannot decode more than 1 character, but a character can be
6957 represented as a surrogate pair */
6958 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006959 int insize;
6960 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 PyObject *errorHandler = NULL;
6962 PyObject *exc = NULL;
6963 PyObject *encoding_obj = NULL;
6964 char *encoding;
6965 DWORD err;
6966 int ret = -1;
6967
6968 assert(size > 0);
6969
6970 encoding = code_page_name(code_page, &encoding_obj);
6971 if (encoding == NULL)
6972 return -1;
6973
6974 if (errors == NULL || strcmp(errors, "strict") == 0) {
6975 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6976 UnicodeDecodeError. */
6977 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6978 if (exc != NULL) {
6979 PyCodec_StrictErrors(exc);
6980 Py_CLEAR(exc);
6981 }
6982 goto error;
6983 }
6984
6985 if (*v == NULL) {
6986 /* Create unicode object */
6987 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6988 PyErr_NoMemory();
6989 goto error;
6990 }
Victor Stinnerab595942011-12-17 04:59:06 +01006991 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006992 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006993 if (*v == NULL)
6994 goto error;
6995 startout = PyUnicode_AS_UNICODE(*v);
6996 }
6997 else {
6998 /* Extend unicode object */
6999 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7000 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7001 PyErr_NoMemory();
7002 goto error;
7003 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007004 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007005 goto error;
7006 startout = PyUnicode_AS_UNICODE(*v) + n;
7007 }
7008
7009 /* Decode the byte string character per character */
7010 out = startout;
7011 while (in < endin)
7012 {
7013 /* Decode a character */
7014 insize = 1;
7015 do
7016 {
7017 outsize = MultiByteToWideChar(code_page, flags,
7018 in, insize,
7019 buffer, Py_ARRAY_LENGTH(buffer));
7020 if (outsize > 0)
7021 break;
7022 err = GetLastError();
7023 if (err != ERROR_NO_UNICODE_TRANSLATION
7024 && err != ERROR_INSUFFICIENT_BUFFER)
7025 {
7026 PyErr_SetFromWindowsErr(0);
7027 goto error;
7028 }
7029 insize++;
7030 }
7031 /* 4=maximum length of a UTF-8 sequence */
7032 while (insize <= 4 && (in + insize) <= endin);
7033
7034 if (outsize <= 0) {
7035 Py_ssize_t startinpos, endinpos, outpos;
7036
7037 startinpos = in - startin;
7038 endinpos = startinpos + 1;
7039 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007040 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007041 errors, &errorHandler,
7042 encoding, reason,
7043 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007044 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007045 {
7046 goto error;
7047 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007048 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 }
7050 else {
7051 in += insize;
7052 memcpy(out, buffer, outsize * sizeof(wchar_t));
7053 out += outsize;
7054 }
7055 }
7056
7057 /* write a NUL character at the end */
7058 *out = 0;
7059
7060 /* Extend unicode object */
7061 outsize = out - startout;
7062 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007063 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007065 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007066
7067error:
7068 Py_XDECREF(encoding_obj);
7069 Py_XDECREF(errorHandler);
7070 Py_XDECREF(exc);
7071 return ret;
7072}
7073
Victor Stinner3a50e702011-10-18 21:21:00 +02007074static PyObject *
7075decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007076 const char *s, Py_ssize_t size,
7077 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078{
Victor Stinner76a31a62011-11-04 00:05:13 +01007079 PyObject *v = NULL;
7080 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 if (code_page < 0) {
7083 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7084 return NULL;
7085 }
7086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
Victor Stinner76a31a62011-11-04 00:05:13 +01007090 do
7091 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007093 if (size > INT_MAX) {
7094 chunk_size = INT_MAX;
7095 final = 0;
7096 done = 0;
7097 }
7098 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007099#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007100 {
7101 chunk_size = (int)size;
7102 final = (consumed == NULL);
7103 done = 1;
7104 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105
Victor Stinner76a31a62011-11-04 00:05:13 +01007106 /* Skip trailing lead-byte unless 'final' is set */
7107 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7108 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109
Victor Stinner76a31a62011-11-04 00:05:13 +01007110 if (chunk_size == 0 && done) {
7111 if (v != NULL)
7112 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007113 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007114 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007115
Victor Stinner76a31a62011-11-04 00:05:13 +01007116
7117 converted = decode_code_page_strict(code_page, &v,
7118 s, chunk_size);
7119 if (converted == -2)
7120 converted = decode_code_page_errors(code_page, &v,
7121 s, chunk_size,
7122 errors);
7123 assert(converted != 0);
7124
7125 if (converted < 0) {
7126 Py_XDECREF(v);
7127 return NULL;
7128 }
7129
7130 if (consumed)
7131 *consumed += converted;
7132
7133 s += converted;
7134 size -= converted;
7135 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007136
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007137 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007138}
7139
Alexander Belopolsky40018472011-02-26 01:02:56 +00007140PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007141PyUnicode_DecodeCodePageStateful(int code_page,
7142 const char *s,
7143 Py_ssize_t size,
7144 const char *errors,
7145 Py_ssize_t *consumed)
7146{
7147 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7148}
7149
7150PyObject *
7151PyUnicode_DecodeMBCSStateful(const char *s,
7152 Py_ssize_t size,
7153 const char *errors,
7154 Py_ssize_t *consumed)
7155{
7156 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7157}
7158
7159PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007160PyUnicode_DecodeMBCS(const char *s,
7161 Py_ssize_t size,
7162 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007163{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007164 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7165}
7166
Victor Stinner3a50e702011-10-18 21:21:00 +02007167static DWORD
7168encode_code_page_flags(UINT code_page, const char *errors)
7169{
7170 if (code_page == CP_UTF8) {
7171 if (winver.dwMajorVersion >= 6)
7172 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7173 and later */
7174 return WC_ERR_INVALID_CHARS;
7175 else
7176 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7177 return 0;
7178 }
7179 else if (code_page == CP_UTF7) {
7180 /* CP_UTF7 only supports flags=0 */
7181 return 0;
7182 }
7183 else {
7184 if (errors != NULL && strcmp(errors, "replace") == 0)
7185 return 0;
7186 else
7187 return WC_NO_BEST_FIT_CHARS;
7188 }
7189}
7190
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007191/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 * Encode a Unicode string to a Windows code page into a byte string in strict
7193 * mode.
7194 *
7195 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007196 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007198static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007199encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007200 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202{
Victor Stinner554f3f02010-06-16 23:33:54 +00007203 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 BOOL *pusedDefaultChar = &usedDefaultChar;
7205 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007206 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007207 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007208 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 const DWORD flags = encode_code_page_flags(code_page, NULL);
7210 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 /* Create a substring so that we can get the UTF-16 representation
7212 of just the slice under consideration. */
7213 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007214
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007216
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007218 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007220 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007221
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 substring = PyUnicode_Substring(unicode, offset, offset+len);
7223 if (substring == NULL)
7224 return -1;
7225 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7226 if (p == NULL) {
7227 Py_DECREF(substring);
7228 return -1;
7229 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007230 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007231
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007232 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007234 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 NULL, 0,
7236 NULL, pusedDefaultChar);
7237 if (outsize <= 0)
7238 goto error;
7239 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007240 if (pusedDefaultChar && *pusedDefaultChar) {
7241 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007243 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007244
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007246 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 if (*outbytes == NULL) {
7249 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007250 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007251 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007253 }
7254 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007255 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 const Py_ssize_t n = PyBytes_Size(*outbytes);
7257 if (outsize > PY_SSIZE_T_MAX - n) {
7258 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007259 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007260 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007262 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7263 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007265 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267 }
7268
7269 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007271 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 out, outsize,
7273 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007274 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 if (outsize <= 0)
7276 goto error;
7277 if (pusedDefaultChar && *pusedDefaultChar)
7278 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007280
Victor Stinner3a50e702011-10-18 21:21:00 +02007281error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007282 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7284 return -2;
7285 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007286 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007287}
7288
Victor Stinner3a50e702011-10-18 21:21:00 +02007289/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007290 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 * error handler.
7292 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007293 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007294 * -1 on other error.
7295 */
7296static int
7297encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007298 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007299 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007300{
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007302 Py_ssize_t pos = unicode_offset;
7303 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 /* Ideally, we should get reason from FormatMessage. This is the Windows
7305 2000 English version of the message. */
7306 const char *reason = "invalid character";
7307 /* 4=maximum length of a UTF-8 sequence */
7308 char buffer[4];
7309 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7310 Py_ssize_t outsize;
7311 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 PyObject *errorHandler = NULL;
7313 PyObject *exc = NULL;
7314 PyObject *encoding_obj = NULL;
7315 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007316 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 PyObject *rep;
7318 int ret = -1;
7319
7320 assert(insize > 0);
7321
7322 encoding = code_page_name(code_page, &encoding_obj);
7323 if (encoding == NULL)
7324 return -1;
7325
7326 if (errors == NULL || strcmp(errors, "strict") == 0) {
7327 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7328 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007329 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 if (exc != NULL) {
7331 PyCodec_StrictErrors(exc);
7332 Py_DECREF(exc);
7333 }
7334 Py_XDECREF(encoding_obj);
7335 return -1;
7336 }
7337
7338 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7339 pusedDefaultChar = &usedDefaultChar;
7340 else
7341 pusedDefaultChar = NULL;
7342
7343 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7344 PyErr_NoMemory();
7345 goto error;
7346 }
7347 outsize = insize * Py_ARRAY_LENGTH(buffer);
7348
7349 if (*outbytes == NULL) {
7350 /* Create string object */
7351 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7352 if (*outbytes == NULL)
7353 goto error;
7354 out = PyBytes_AS_STRING(*outbytes);
7355 }
7356 else {
7357 /* Extend string object */
7358 Py_ssize_t n = PyBytes_Size(*outbytes);
7359 if (n > PY_SSIZE_T_MAX - outsize) {
7360 PyErr_NoMemory();
7361 goto error;
7362 }
7363 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7364 goto error;
7365 out = PyBytes_AS_STRING(*outbytes) + n;
7366 }
7367
7368 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007369 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007370 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007371 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7372 wchar_t chars[2];
7373 int charsize;
7374 if (ch < 0x10000) {
7375 chars[0] = (wchar_t)ch;
7376 charsize = 1;
7377 }
7378 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007379 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7380 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007381 charsize = 2;
7382 }
7383
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 buffer, Py_ARRAY_LENGTH(buffer),
7387 NULL, pusedDefaultChar);
7388 if (outsize > 0) {
7389 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7390 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007391 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 memcpy(out, buffer, outsize);
7393 out += outsize;
7394 continue;
7395 }
7396 }
7397 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7398 PyErr_SetFromWindowsErr(0);
7399 goto error;
7400 }
7401
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 rep = unicode_encode_call_errorhandler(
7403 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007404 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 if (rep == NULL)
7407 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007408 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007409
7410 if (PyBytes_Check(rep)) {
7411 outsize = PyBytes_GET_SIZE(rep);
7412 if (outsize != 1) {
7413 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7414 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7415 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7416 Py_DECREF(rep);
7417 goto error;
7418 }
7419 out = PyBytes_AS_STRING(*outbytes) + offset;
7420 }
7421 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7422 out += outsize;
7423 }
7424 else {
7425 Py_ssize_t i;
7426 enum PyUnicode_Kind kind;
7427 void *data;
7428
Benjamin Petersonbac79492012-01-14 13:34:47 -05007429 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 Py_DECREF(rep);
7431 goto error;
7432 }
7433
7434 outsize = PyUnicode_GET_LENGTH(rep);
7435 if (outsize != 1) {
7436 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7437 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7438 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7439 Py_DECREF(rep);
7440 goto error;
7441 }
7442 out = PyBytes_AS_STRING(*outbytes) + offset;
7443 }
7444 kind = PyUnicode_KIND(rep);
7445 data = PyUnicode_DATA(rep);
7446 for (i=0; i < outsize; i++) {
7447 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7448 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007449 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007450 encoding, unicode,
7451 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 "unable to encode error handler result to ASCII");
7453 Py_DECREF(rep);
7454 goto error;
7455 }
7456 *out = (unsigned char)ch;
7457 out++;
7458 }
7459 }
7460 Py_DECREF(rep);
7461 }
7462 /* write a NUL byte */
7463 *out = 0;
7464 outsize = out - PyBytes_AS_STRING(*outbytes);
7465 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7466 if (_PyBytes_Resize(outbytes, outsize) < 0)
7467 goto error;
7468 ret = 0;
7469
7470error:
7471 Py_XDECREF(encoding_obj);
7472 Py_XDECREF(errorHandler);
7473 Py_XDECREF(exc);
7474 return ret;
7475}
7476
Victor Stinner3a50e702011-10-18 21:21:00 +02007477static PyObject *
7478encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007479 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 const char *errors)
7481{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007482 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007484 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007485 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007486
Benjamin Petersonbac79492012-01-14 13:34:47 -05007487 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007488 return NULL;
7489 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007490
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 if (code_page < 0) {
7492 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7493 return NULL;
7494 }
7495
Martin v. Löwis3d325192011-11-04 18:23:06 +01007496 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007497 return PyBytes_FromStringAndSize(NULL, 0);
7498
Victor Stinner7581cef2011-11-03 22:32:33 +01007499 offset = 0;
7500 do
7501 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007502#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007503 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 chunks. */
7505 if (len > INT_MAX/2) {
7506 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007507 done = 0;
7508 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007509 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007511 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007512 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007513 done = 1;
7514 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007515
Victor Stinner76a31a62011-11-04 00:05:13 +01007516 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007517 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007518 errors);
7519 if (ret == -2)
7520 ret = encode_code_page_errors(code_page, &outbytes,
7521 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007522 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007523 if (ret < 0) {
7524 Py_XDECREF(outbytes);
7525 return NULL;
7526 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007527
Victor Stinner7581cef2011-11-03 22:32:33 +01007528 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007529 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007530 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007531
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 return outbytes;
7533}
7534
7535PyObject *
7536PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7537 Py_ssize_t size,
7538 const char *errors)
7539{
Victor Stinner7581cef2011-11-03 22:32:33 +01007540 PyObject *unicode, *res;
7541 unicode = PyUnicode_FromUnicode(p, size);
7542 if (unicode == NULL)
7543 return NULL;
7544 res = encode_code_page(CP_ACP, unicode, errors);
7545 Py_DECREF(unicode);
7546 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007547}
7548
7549PyObject *
7550PyUnicode_EncodeCodePage(int code_page,
7551 PyObject *unicode,
7552 const char *errors)
7553{
Victor Stinner7581cef2011-11-03 22:32:33 +01007554 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007555}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007556
Alexander Belopolsky40018472011-02-26 01:02:56 +00007557PyObject *
7558PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007559{
7560 if (!PyUnicode_Check(unicode)) {
7561 PyErr_BadArgument();
7562 return NULL;
7563 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007564 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007565}
7566
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007567#undef NEED_RETRY
7568
Victor Stinner99b95382011-07-04 14:23:54 +02007569#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007570
Guido van Rossumd57fd912000-03-10 22:53:23 +00007571/* --- Character Mapping Codec -------------------------------------------- */
7572
Victor Stinnerfb161b12013-04-18 01:44:27 +02007573static int
7574charmap_decode_string(const char *s,
7575 Py_ssize_t size,
7576 PyObject *mapping,
7577 const char *errors,
7578 _PyUnicodeWriter *writer)
7579{
7580 const char *starts = s;
7581 const char *e;
7582 Py_ssize_t startinpos, endinpos;
7583 PyObject *errorHandler = NULL, *exc = NULL;
7584 Py_ssize_t maplen;
7585 enum PyUnicode_Kind mapkind;
7586 void *mapdata;
7587 Py_UCS4 x;
7588 unsigned char ch;
7589
7590 if (PyUnicode_READY(mapping) == -1)
7591 return -1;
7592
7593 maplen = PyUnicode_GET_LENGTH(mapping);
7594 mapdata = PyUnicode_DATA(mapping);
7595 mapkind = PyUnicode_KIND(mapping);
7596
7597 e = s + size;
7598
7599 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7600 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7601 * is disabled in encoding aliases, latin1 is preferred because
7602 * its implementation is faster. */
7603 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7604 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7605 Py_UCS4 maxchar = writer->maxchar;
7606
7607 assert (writer->kind == PyUnicode_1BYTE_KIND);
7608 while (s < e) {
7609 ch = *s;
7610 x = mapdata_ucs1[ch];
7611 if (x > maxchar) {
7612 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7613 goto onError;
7614 maxchar = writer->maxchar;
7615 outdata = (Py_UCS1 *)writer->data;
7616 }
7617 outdata[writer->pos] = x;
7618 writer->pos++;
7619 ++s;
7620 }
7621 return 0;
7622 }
7623
7624 while (s < e) {
7625 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7626 enum PyUnicode_Kind outkind = writer->kind;
7627 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7628 if (outkind == PyUnicode_1BYTE_KIND) {
7629 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7630 Py_UCS4 maxchar = writer->maxchar;
7631 while (s < e) {
7632 ch = *s;
7633 x = mapdata_ucs2[ch];
7634 if (x > maxchar)
7635 goto Error;
7636 outdata[writer->pos] = x;
7637 writer->pos++;
7638 ++s;
7639 }
7640 break;
7641 }
7642 else if (outkind == PyUnicode_2BYTE_KIND) {
7643 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7644 while (s < e) {
7645 ch = *s;
7646 x = mapdata_ucs2[ch];
7647 if (x == 0xFFFE)
7648 goto Error;
7649 outdata[writer->pos] = x;
7650 writer->pos++;
7651 ++s;
7652 }
7653 break;
7654 }
7655 }
7656 ch = *s;
7657
7658 if (ch < maplen)
7659 x = PyUnicode_READ(mapkind, mapdata, ch);
7660 else
7661 x = 0xfffe; /* invalid value */
7662Error:
7663 if (x == 0xfffe)
7664 {
7665 /* undefined mapping */
7666 startinpos = s-starts;
7667 endinpos = startinpos+1;
7668 if (unicode_decode_call_errorhandler_writer(
7669 errors, &errorHandler,
7670 "charmap", "character maps to <undefined>",
7671 &starts, &e, &startinpos, &endinpos, &exc, &s,
7672 writer)) {
7673 goto onError;
7674 }
7675 continue;
7676 }
7677
7678 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7679 goto onError;
7680 ++s;
7681 }
7682 Py_XDECREF(errorHandler);
7683 Py_XDECREF(exc);
7684 return 0;
7685
7686onError:
7687 Py_XDECREF(errorHandler);
7688 Py_XDECREF(exc);
7689 return -1;
7690}
7691
7692static int
7693charmap_decode_mapping(const char *s,
7694 Py_ssize_t size,
7695 PyObject *mapping,
7696 const char *errors,
7697 _PyUnicodeWriter *writer)
7698{
7699 const char *starts = s;
7700 const char *e;
7701 Py_ssize_t startinpos, endinpos;
7702 PyObject *errorHandler = NULL, *exc = NULL;
7703 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007704 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007705
7706 e = s + size;
7707
7708 while (s < e) {
7709 ch = *s;
7710
7711 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7712 key = PyLong_FromLong((long)ch);
7713 if (key == NULL)
7714 goto onError;
7715
7716 item = PyObject_GetItem(mapping, key);
7717 Py_DECREF(key);
7718 if (item == NULL) {
7719 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7720 /* No mapping found means: mapping is undefined. */
7721 PyErr_Clear();
7722 goto Undefined;
7723 } else
7724 goto onError;
7725 }
7726
7727 /* Apply mapping */
7728 if (item == Py_None)
7729 goto Undefined;
7730 if (PyLong_Check(item)) {
7731 long value = PyLong_AS_LONG(item);
7732 if (value == 0xFFFE)
7733 goto Undefined;
7734 if (value < 0 || value > MAX_UNICODE) {
7735 PyErr_Format(PyExc_TypeError,
7736 "character mapping must be in range(0x%lx)",
7737 (unsigned long)MAX_UNICODE + 1);
7738 goto onError;
7739 }
7740
7741 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7742 goto onError;
7743 }
7744 else if (PyUnicode_Check(item)) {
7745 if (PyUnicode_READY(item) == -1)
7746 goto onError;
7747 if (PyUnicode_GET_LENGTH(item) == 1) {
7748 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7749 if (value == 0xFFFE)
7750 goto Undefined;
7751 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7752 goto onError;
7753 }
7754 else {
7755 writer->overallocate = 1;
7756 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7757 goto onError;
7758 }
7759 }
7760 else {
7761 /* wrong return value */
7762 PyErr_SetString(PyExc_TypeError,
7763 "character mapping must return integer, None or str");
7764 goto onError;
7765 }
7766 Py_CLEAR(item);
7767 ++s;
7768 continue;
7769
7770Undefined:
7771 /* undefined mapping */
7772 Py_CLEAR(item);
7773 startinpos = s-starts;
7774 endinpos = startinpos+1;
7775 if (unicode_decode_call_errorhandler_writer(
7776 errors, &errorHandler,
7777 "charmap", "character maps to <undefined>",
7778 &starts, &e, &startinpos, &endinpos, &exc, &s,
7779 writer)) {
7780 goto onError;
7781 }
7782 }
7783 Py_XDECREF(errorHandler);
7784 Py_XDECREF(exc);
7785 return 0;
7786
7787onError:
7788 Py_XDECREF(item);
7789 Py_XDECREF(errorHandler);
7790 Py_XDECREF(exc);
7791 return -1;
7792}
7793
Alexander Belopolsky40018472011-02-26 01:02:56 +00007794PyObject *
7795PyUnicode_DecodeCharmap(const char *s,
7796 Py_ssize_t size,
7797 PyObject *mapping,
7798 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007799{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007800 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007801
Guido van Rossumd57fd912000-03-10 22:53:23 +00007802 /* Default to Latin-1 */
7803 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007805
Guido van Rossumd57fd912000-03-10 22:53:23 +00007806 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007807 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007808 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007809 writer.min_length = size;
7810 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007811 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007812
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007813 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007814 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7815 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007816 }
7817 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007818 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7819 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007820 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007821 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007822
Benjamin Peterson29060642009-01-31 22:14:21 +00007823 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007824 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007825 return NULL;
7826}
7827
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007828/* Charmap encoding: the lookup table */
7829
Alexander Belopolsky40018472011-02-26 01:02:56 +00007830struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 PyObject_HEAD
7832 unsigned char level1[32];
7833 int count2, count3;
7834 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007835};
7836
7837static PyObject*
7838encoding_map_size(PyObject *obj, PyObject* args)
7839{
7840 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007841 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007842 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843}
7844
7845static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007846 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 PyDoc_STR("Return the size (in bytes) of this object") },
7848 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007849};
7850
7851static void
7852encoding_map_dealloc(PyObject* o)
7853{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007854 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007855}
7856
7857static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007858 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 "EncodingMap", /*tp_name*/
7860 sizeof(struct encoding_map), /*tp_basicsize*/
7861 0, /*tp_itemsize*/
7862 /* methods */
7863 encoding_map_dealloc, /*tp_dealloc*/
7864 0, /*tp_print*/
7865 0, /*tp_getattr*/
7866 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007867 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007868 0, /*tp_repr*/
7869 0, /*tp_as_number*/
7870 0, /*tp_as_sequence*/
7871 0, /*tp_as_mapping*/
7872 0, /*tp_hash*/
7873 0, /*tp_call*/
7874 0, /*tp_str*/
7875 0, /*tp_getattro*/
7876 0, /*tp_setattro*/
7877 0, /*tp_as_buffer*/
7878 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7879 0, /*tp_doc*/
7880 0, /*tp_traverse*/
7881 0, /*tp_clear*/
7882 0, /*tp_richcompare*/
7883 0, /*tp_weaklistoffset*/
7884 0, /*tp_iter*/
7885 0, /*tp_iternext*/
7886 encoding_map_methods, /*tp_methods*/
7887 0, /*tp_members*/
7888 0, /*tp_getset*/
7889 0, /*tp_base*/
7890 0, /*tp_dict*/
7891 0, /*tp_descr_get*/
7892 0, /*tp_descr_set*/
7893 0, /*tp_dictoffset*/
7894 0, /*tp_init*/
7895 0, /*tp_alloc*/
7896 0, /*tp_new*/
7897 0, /*tp_free*/
7898 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899};
7900
7901PyObject*
7902PyUnicode_BuildEncodingMap(PyObject* string)
7903{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 PyObject *result;
7905 struct encoding_map *mresult;
7906 int i;
7907 int need_dict = 0;
7908 unsigned char level1[32];
7909 unsigned char level2[512];
7910 unsigned char *mlevel1, *mlevel2, *mlevel3;
7911 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007912 int kind;
7913 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007914 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007915 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007917 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918 PyErr_BadArgument();
7919 return NULL;
7920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007921 kind = PyUnicode_KIND(string);
7922 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007923 length = PyUnicode_GET_LENGTH(string);
7924 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007925 memset(level1, 0xFF, sizeof level1);
7926 memset(level2, 0xFF, sizeof level2);
7927
7928 /* If there isn't a one-to-one mapping of NULL to \0,
7929 or if there are non-BMP characters, we need to use
7930 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007931 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007932 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007933 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007935 ch = PyUnicode_READ(kind, data, i);
7936 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 need_dict = 1;
7938 break;
7939 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007940 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 /* unmapped character */
7942 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007943 l1 = ch >> 11;
7944 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007945 if (level1[l1] == 0xFF)
7946 level1[l1] = count2++;
7947 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007948 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007949 }
7950
7951 if (count2 >= 0xFF || count3 >= 0xFF)
7952 need_dict = 1;
7953
7954 if (need_dict) {
7955 PyObject *result = PyDict_New();
7956 PyObject *key, *value;
7957 if (!result)
7958 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007959 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007960 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007961 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007962 if (!key || !value)
7963 goto failed1;
7964 if (PyDict_SetItem(result, key, value) == -1)
7965 goto failed1;
7966 Py_DECREF(key);
7967 Py_DECREF(value);
7968 }
7969 return result;
7970 failed1:
7971 Py_XDECREF(key);
7972 Py_XDECREF(value);
7973 Py_DECREF(result);
7974 return NULL;
7975 }
7976
7977 /* Create a three-level trie */
7978 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7979 16*count2 + 128*count3 - 1);
7980 if (!result)
7981 return PyErr_NoMemory();
7982 PyObject_Init(result, &EncodingMapType);
7983 mresult = (struct encoding_map*)result;
7984 mresult->count2 = count2;
7985 mresult->count3 = count3;
7986 mlevel1 = mresult->level1;
7987 mlevel2 = mresult->level23;
7988 mlevel3 = mresult->level23 + 16*count2;
7989 memcpy(mlevel1, level1, 32);
7990 memset(mlevel2, 0xFF, 16*count2);
7991 memset(mlevel3, 0, 128*count3);
7992 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007993 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007995 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7996 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007997 /* unmapped character */
7998 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007999 o1 = ch>>11;
8000 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008001 i2 = 16*mlevel1[o1] + o2;
8002 if (mlevel2[i2] == 0xFF)
8003 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008004 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005 i3 = 128*mlevel2[i2] + o3;
8006 mlevel3[i3] = i;
8007 }
8008 return result;
8009}
8010
8011static int
Victor Stinner22168992011-11-20 17:09:18 +01008012encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013{
8014 struct encoding_map *map = (struct encoding_map*)mapping;
8015 int l1 = c>>11;
8016 int l2 = (c>>7) & 0xF;
8017 int l3 = c & 0x7F;
8018 int i;
8019
Victor Stinner22168992011-11-20 17:09:18 +01008020 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008022 if (c == 0)
8023 return 0;
8024 /* level 1*/
8025 i = map->level1[l1];
8026 if (i == 0xFF) {
8027 return -1;
8028 }
8029 /* level 2*/
8030 i = map->level23[16*i+l2];
8031 if (i == 0xFF) {
8032 return -1;
8033 }
8034 /* level 3 */
8035 i = map->level23[16*map->count2 + 128*i + l3];
8036 if (i == 0) {
8037 return -1;
8038 }
8039 return i;
8040}
8041
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042/* Lookup the character ch in the mapping. If the character
8043 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008044 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008045static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008046charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008047{
Christian Heimes217cfd12007-12-02 14:31:20 +00008048 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049 PyObject *x;
8050
8051 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053 x = PyObject_GetItem(mapping, w);
8054 Py_DECREF(w);
8055 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8057 /* No mapping found means: mapping is undefined. */
8058 PyErr_Clear();
8059 x = Py_None;
8060 Py_INCREF(x);
8061 return x;
8062 } else
8063 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008064 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008065 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008067 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 long value = PyLong_AS_LONG(x);
8069 if (value < 0 || value > 255) {
8070 PyErr_SetString(PyExc_TypeError,
8071 "character mapping must be in range(256)");
8072 Py_DECREF(x);
8073 return NULL;
8074 }
8075 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008076 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008077 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008078 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 /* wrong return value */
8081 PyErr_Format(PyExc_TypeError,
8082 "character mapping must return integer, bytes or None, not %.400s",
8083 x->ob_type->tp_name);
8084 Py_DECREF(x);
8085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008086 }
8087}
8088
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008090charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008092 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8093 /* exponentially overallocate to minimize reallocations */
8094 if (requiredsize < 2*outsize)
8095 requiredsize = 2*outsize;
8096 if (_PyBytes_Resize(outobj, requiredsize))
8097 return -1;
8098 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008099}
8100
Benjamin Peterson14339b62009-01-31 16:36:08 +00008101typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008103} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008104/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008105 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008106 space is available. Return a new reference to the object that
8107 was put in the output buffer, or Py_None, if the mapping was undefined
8108 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008109 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008110static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008111charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008112 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114 PyObject *rep;
8115 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008116 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117
Christian Heimes90aa7642007-12-19 02:45:37 +00008118 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 if (res == -1)
8122 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008123 if (outsize<requiredsize)
8124 if (charmapencode_resize(outobj, outpos, requiredsize))
8125 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008126 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 outstart[(*outpos)++] = (char)res;
8128 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008129 }
8130
8131 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008133 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 Py_DECREF(rep);
8136 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008137 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 if (PyLong_Check(rep)) {
8139 Py_ssize_t requiredsize = *outpos+1;
8140 if (outsize<requiredsize)
8141 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8142 Py_DECREF(rep);
8143 return enc_EXCEPTION;
8144 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008145 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 else {
8149 const char *repchars = PyBytes_AS_STRING(rep);
8150 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8151 Py_ssize_t requiredsize = *outpos+repsize;
8152 if (outsize<requiredsize)
8153 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8154 Py_DECREF(rep);
8155 return enc_EXCEPTION;
8156 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008157 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008158 memcpy(outstart + *outpos, repchars, repsize);
8159 *outpos += repsize;
8160 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008161 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008162 Py_DECREF(rep);
8163 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008164}
8165
8166/* handle an error in PyUnicode_EncodeCharmap
8167 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008168static int
8169charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008170 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008172 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008173 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008174{
8175 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008176 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008177 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008178 enum PyUnicode_Kind kind;
8179 void *data;
8180 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008181 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008182 Py_ssize_t collstartpos = *inpos;
8183 Py_ssize_t collendpos = *inpos+1;
8184 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008185 char *encoding = "charmap";
8186 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008188 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008189 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190
Benjamin Petersonbac79492012-01-14 13:34:47 -05008191 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008192 return -1;
8193 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008194 /* find all unencodable characters */
8195 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008197 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008199 val = encoding_map_lookup(ch, mapping);
8200 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008201 break;
8202 ++collendpos;
8203 continue;
8204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008205
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008206 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8207 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 if (rep==NULL)
8209 return -1;
8210 else if (rep!=Py_None) {
8211 Py_DECREF(rep);
8212 break;
8213 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008214 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216 }
8217 /* cache callback name lookup
8218 * (if not done yet, i.e. it's the first error) */
8219 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 if ((errors==NULL) || (!strcmp(errors, "strict")))
8221 *known_errorHandler = 1;
8222 else if (!strcmp(errors, "replace"))
8223 *known_errorHandler = 2;
8224 else if (!strcmp(errors, "ignore"))
8225 *known_errorHandler = 3;
8226 else if (!strcmp(errors, "xmlcharrefreplace"))
8227 *known_errorHandler = 4;
8228 else
8229 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 }
8231 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008233 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008234 return -1;
8235 case 2: /* replace */
8236 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 x = charmapencode_output('?', mapping, res, respos);
8238 if (x==enc_EXCEPTION) {
8239 return -1;
8240 }
8241 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008242 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 return -1;
8244 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008245 }
8246 /* fall through */
8247 case 3: /* ignore */
8248 *inpos = collendpos;
8249 break;
8250 case 4: /* xmlcharrefreplace */
8251 /* generate replacement (temporarily (mis)uses p) */
8252 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 char buffer[2+29+1+1];
8254 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008255 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 for (cp = buffer; *cp; ++cp) {
8257 x = charmapencode_output(*cp, mapping, res, respos);
8258 if (x==enc_EXCEPTION)
8259 return -1;
8260 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008261 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 return -1;
8263 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008264 }
8265 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008266 *inpos = collendpos;
8267 break;
8268 default:
8269 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008270 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008272 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008274 if (PyBytes_Check(repunicode)) {
8275 /* Directly copy bytes result to output. */
8276 Py_ssize_t outsize = PyBytes_Size(*res);
8277 Py_ssize_t requiredsize;
8278 repsize = PyBytes_Size(repunicode);
8279 requiredsize = *respos + repsize;
8280 if (requiredsize > outsize)
8281 /* Make room for all additional bytes. */
8282 if (charmapencode_resize(res, respos, requiredsize)) {
8283 Py_DECREF(repunicode);
8284 return -1;
8285 }
8286 memcpy(PyBytes_AsString(*res) + *respos,
8287 PyBytes_AsString(repunicode), repsize);
8288 *respos += repsize;
8289 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008290 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008291 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008292 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008293 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008294 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008295 Py_DECREF(repunicode);
8296 return -1;
8297 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008298 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008299 data = PyUnicode_DATA(repunicode);
8300 kind = PyUnicode_KIND(repunicode);
8301 for (index = 0; index < repsize; index++) {
8302 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8303 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008305 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 return -1;
8307 }
8308 else if (x==enc_FAILED) {
8309 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008310 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 return -1;
8312 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008313 }
8314 *inpos = newpos;
8315 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 }
8317 return 0;
8318}
8319
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321_PyUnicode_EncodeCharmap(PyObject *unicode,
8322 PyObject *mapping,
8323 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 /* output object */
8326 PyObject *res = NULL;
8327 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008328 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008329 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008331 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 PyObject *errorHandler = NULL;
8333 PyObject *exc = NULL;
8334 /* the following variable is used for caching string comparisons
8335 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8336 * 3=ignore, 4=xmlcharrefreplace */
8337 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008338 void *data;
8339 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340
Benjamin Petersonbac79492012-01-14 13:34:47 -05008341 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008342 return NULL;
8343 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008344 data = PyUnicode_DATA(unicode);
8345 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008346
Guido van Rossumd57fd912000-03-10 22:53:23 +00008347 /* Default to Latin-1 */
8348 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008349 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351 /* allocate enough for a simple encoding without
8352 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008353 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 if (res == NULL)
8355 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008356 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008358
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008360 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008362 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 if (x==enc_EXCEPTION) /* error */
8364 goto onError;
8365 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008366 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 &exc,
8368 &known_errorHandler, &errorHandler, errors,
8369 &res, &respos)) {
8370 goto onError;
8371 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008372 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 else
8374 /* done with this character => adjust input position */
8375 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008377
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008379 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008380 if (_PyBytes_Resize(&res, respos) < 0)
8381 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008382
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 Py_XDECREF(exc);
8384 Py_XDECREF(errorHandler);
8385 return res;
8386
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 Py_XDECREF(res);
8389 Py_XDECREF(exc);
8390 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 return NULL;
8392}
8393
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008394/* Deprecated */
8395PyObject *
8396PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8397 Py_ssize_t size,
8398 PyObject *mapping,
8399 const char *errors)
8400{
8401 PyObject *result;
8402 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8403 if (unicode == NULL)
8404 return NULL;
8405 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8406 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008407 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408}
8409
Alexander Belopolsky40018472011-02-26 01:02:56 +00008410PyObject *
8411PyUnicode_AsCharmapString(PyObject *unicode,
8412 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008413{
8414 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 PyErr_BadArgument();
8416 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008417 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008418 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008419}
8420
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008422static void
8423make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425 Py_ssize_t startpos, Py_ssize_t endpos,
8426 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008429 *exceptionObject = _PyUnicodeTranslateError_Create(
8430 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431 }
8432 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8434 goto onError;
8435 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8436 goto onError;
8437 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8438 goto onError;
8439 return;
8440 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008441 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008442 }
8443}
8444
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445/* error handling callback helper:
8446 build arguments, call the callback and check the arguments,
8447 put the result into newpos and return the replacement string, which
8448 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008449static PyObject *
8450unicode_translate_call_errorhandler(const char *errors,
8451 PyObject **errorHandler,
8452 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008453 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008454 Py_ssize_t startpos, Py_ssize_t endpos,
8455 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008457 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008458
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008459 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 PyObject *restuple;
8461 PyObject *resunicode;
8462
8463 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467 }
8468
8469 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473
8474 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008479 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 Py_DECREF(restuple);
8481 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 }
8483 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 &resunicode, &i_newpos)) {
8485 Py_DECREF(restuple);
8486 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008488 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008490 else
8491 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008493 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 Py_DECREF(restuple);
8495 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008496 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497 Py_INCREF(resunicode);
8498 Py_DECREF(restuple);
8499 return resunicode;
8500}
8501
8502/* Lookup the character ch in the mapping and put the result in result,
8503 which must be decrefed by the caller.
8504 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507{
Christian Heimes217cfd12007-12-02 14:31:20 +00008508 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008509 PyObject *x;
8510
8511 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513 x = PyObject_GetItem(mapping, w);
8514 Py_DECREF(w);
8515 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8517 /* No mapping found means: use 1:1 mapping. */
8518 PyErr_Clear();
8519 *result = NULL;
8520 return 0;
8521 } else
8522 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008523 }
8524 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 *result = x;
8526 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008528 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 long value = PyLong_AS_LONG(x);
8530 long max = PyUnicode_GetMax();
8531 if (value < 0 || value > max) {
8532 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008533 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 Py_DECREF(x);
8535 return -1;
8536 }
8537 *result = x;
8538 return 0;
8539 }
8540 else if (PyUnicode_Check(x)) {
8541 *result = x;
8542 return 0;
8543 }
8544 else {
8545 /* wrong return value */
8546 PyErr_SetString(PyExc_TypeError,
8547 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008548 Py_DECREF(x);
8549 return -1;
8550 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551}
8552/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 if not reallocate and adjust various state variables.
8554 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008555static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008556charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008560 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008561 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 /* exponentially overallocate to minimize reallocations */
8563 if (requiredsize < 2 * oldsize)
8564 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008565 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8566 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008568 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008569 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 }
8571 return 0;
8572}
8573/* lookup the character, put the result in the output string and adjust
8574 various state variables. Return a new reference to the object that
8575 was put in the output buffer in *result, or Py_None, if the mapping was
8576 undefined (in which case no character was written).
8577 The called must decref result.
8578 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008579static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8581 PyObject *mapping, Py_UCS4 **output,
8582 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008583 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8586 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 }
8592 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008594 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 }
8598 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599 Py_ssize_t repsize;
8600 if (PyUnicode_READY(*res) == -1)
8601 return -1;
8602 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 if (repsize==1) {
8604 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 }
8607 else if (repsize!=0) {
8608 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 Py_ssize_t requiredsize = *opos +
8610 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 Py_ssize_t i;
8613 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 for(i = 0; i < repsize; i++)
8616 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 }
8619 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621 return 0;
8622}
8623
Alexander Belopolsky40018472011-02-26 01:02:56 +00008624PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625_PyUnicode_TranslateCharmap(PyObject *input,
8626 PyObject *mapping,
8627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008628{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 /* input object */
8630 char *idata;
8631 Py_ssize_t size, i;
8632 int kind;
8633 /* output buffer */
8634 Py_UCS4 *output = NULL;
8635 Py_ssize_t osize;
8636 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 char *reason = "character maps to <undefined>";
8640 PyObject *errorHandler = NULL;
8641 PyObject *exc = NULL;
8642 /* the following variable is used for caching string comparisons
8643 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8644 * 3=ignore, 4=xmlcharrefreplace */
8645 int known_errorHandler = -1;
8646
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 PyErr_BadArgument();
8649 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 if (PyUnicode_READY(input) == -1)
8653 return NULL;
8654 idata = (char*)PyUnicode_DATA(input);
8655 kind = PyUnicode_KIND(input);
8656 size = PyUnicode_GET_LENGTH(input);
8657 i = 0;
8658
8659 if (size == 0) {
8660 Py_INCREF(input);
8661 return input;
8662 }
8663
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 /* allocate enough for a simple 1:1 translation without
8665 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 osize = size;
Benjamin Petersone5a853c2015-03-02 13:23:25 -05008667 output = PyMem_NEW(Py_UCS4, osize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 opos = 0;
8669 if (output == NULL) {
8670 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 /* try to encode it */
8676 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 if (charmaptranslate_output(input, i, mapping,
8678 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 Py_XDECREF(x);
8680 goto onError;
8681 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008682 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 else { /* untranslatable character */
8686 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8687 Py_ssize_t repsize;
8688 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 Py_ssize_t collstart = i;
8692 Py_ssize_t collend = i+1;
8693 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008694
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 while (collend < size) {
8697 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 goto onError;
8699 Py_XDECREF(x);
8700 if (x!=Py_None)
8701 break;
8702 ++collend;
8703 }
8704 /* cache callback name lookup
8705 * (if not done yet, i.e. it's the first error) */
8706 if (known_errorHandler==-1) {
8707 if ((errors==NULL) || (!strcmp(errors, "strict")))
8708 known_errorHandler = 1;
8709 else if (!strcmp(errors, "replace"))
8710 known_errorHandler = 2;
8711 else if (!strcmp(errors, "ignore"))
8712 known_errorHandler = 3;
8713 else if (!strcmp(errors, "xmlcharrefreplace"))
8714 known_errorHandler = 4;
8715 else
8716 known_errorHandler = 0;
8717 }
8718 switch (known_errorHandler) {
8719 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008720 make_translate_exception(&exc,
8721 input, collstart, collend, reason);
8722 if (exc != NULL)
8723 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008724 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 case 2: /* replace */
8726 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 for (coll = collstart; coll<collend; coll++)
8728 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 /* fall through */
8730 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 break;
8733 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 /* generate replacement (temporarily (mis)uses i) */
8735 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 char buffer[2+29+1+1];
8737 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8739 if (charmaptranslate_makespace(&output, &osize,
8740 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 goto onError;
8742 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 break;
8747 default:
8748 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 reason, input, &exc,
8750 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008751 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008753 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008754 Py_DECREF(repunicode);
8755 goto onError;
8756 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008758 repsize = PyUnicode_GET_LENGTH(repunicode);
8759 if (charmaptranslate_makespace(&output, &osize,
8760 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 Py_DECREF(repunicode);
8762 goto onError;
8763 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008764 for (uni2 = 0; repsize-->0; ++uni2)
8765 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8766 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008769 }
8770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8772 if (!res)
8773 goto onError;
8774 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008775 Py_XDECREF(exc);
8776 Py_XDECREF(errorHandler);
8777 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008778
Benjamin Peterson29060642009-01-31 22:14:21 +00008779 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 Py_XDECREF(exc);
8782 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008783 return NULL;
8784}
8785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008786/* Deprecated. Use PyUnicode_Translate instead. */
8787PyObject *
8788PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8789 Py_ssize_t size,
8790 PyObject *mapping,
8791 const char *errors)
8792{
Christian Heimes5f520f42012-09-11 14:03:25 +02008793 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8795 if (!unicode)
8796 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008797 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8798 Py_DECREF(unicode);
8799 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800}
8801
Alexander Belopolsky40018472011-02-26 01:02:56 +00008802PyObject *
8803PyUnicode_Translate(PyObject *str,
8804 PyObject *mapping,
8805 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008806{
8807 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008808
Guido van Rossumd57fd912000-03-10 22:53:23 +00008809 str = PyUnicode_FromObject(str);
8810 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008811 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008812 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008813 Py_DECREF(str);
8814 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008815}
Tim Petersced69f82003-09-16 20:30:58 +00008816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008818fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819{
8820 /* No need to call PyUnicode_READY(self) because this function is only
8821 called as a callback from fixup() which does it already. */
8822 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8823 const int kind = PyUnicode_KIND(self);
8824 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008825 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008826 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008827 Py_ssize_t i;
8828
8829 for (i = 0; i < len; ++i) {
8830 ch = PyUnicode_READ(kind, data, i);
8831 fixed = 0;
8832 if (ch > 127) {
8833 if (Py_UNICODE_ISSPACE(ch))
8834 fixed = ' ';
8835 else {
8836 const int decimal = Py_UNICODE_TODECIMAL(ch);
8837 if (decimal >= 0)
8838 fixed = '0' + decimal;
8839 }
8840 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008841 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008842 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843 PyUnicode_WRITE(kind, data, i, fixed);
8844 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008845 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008846 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008847 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008848 }
8849
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008850 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851}
8852
8853PyObject *
8854_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8855{
8856 if (!PyUnicode_Check(unicode)) {
8857 PyErr_BadInternalCall();
8858 return NULL;
8859 }
8860 if (PyUnicode_READY(unicode) == -1)
8861 return NULL;
8862 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8863 /* If the string is already ASCII, just return the same string */
8864 Py_INCREF(unicode);
8865 return unicode;
8866 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008867 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868}
8869
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008870PyObject *
8871PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8872 Py_ssize_t length)
8873{
Victor Stinnerf0124502011-11-21 23:12:56 +01008874 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008875 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008876 Py_UCS4 maxchar;
8877 enum PyUnicode_Kind kind;
8878 void *data;
8879
Victor Stinner99d7ad02012-02-22 13:37:39 +01008880 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008881 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008882 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008883 if (ch > 127) {
8884 int decimal = Py_UNICODE_TODECIMAL(ch);
8885 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008886 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008887 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008888 }
8889 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008890
8891 /* Copy to a new string */
8892 decimal = PyUnicode_New(length, maxchar);
8893 if (decimal == NULL)
8894 return decimal;
8895 kind = PyUnicode_KIND(decimal);
8896 data = PyUnicode_DATA(decimal);
8897 /* Iterate over code points */
8898 for (i = 0; i < length; i++) {
8899 Py_UNICODE ch = s[i];
8900 if (ch > 127) {
8901 int decimal = Py_UNICODE_TODECIMAL(ch);
8902 if (decimal >= 0)
8903 ch = '0' + decimal;
8904 }
8905 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008907 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008908}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008909/* --- Decimal Encoder ---------------------------------------------------- */
8910
Alexander Belopolsky40018472011-02-26 01:02:56 +00008911int
8912PyUnicode_EncodeDecimal(Py_UNICODE *s,
8913 Py_ssize_t length,
8914 char *output,
8915 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008916{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008917 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008918 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008919 enum PyUnicode_Kind kind;
8920 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008921
8922 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 PyErr_BadArgument();
8924 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008925 }
8926
Victor Stinner42bf7752011-11-21 22:52:58 +01008927 unicode = PyUnicode_FromUnicode(s, length);
8928 if (unicode == NULL)
8929 return -1;
8930
Benjamin Petersonbac79492012-01-14 13:34:47 -05008931 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008932 Py_DECREF(unicode);
8933 return -1;
8934 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008935 kind = PyUnicode_KIND(unicode);
8936 data = PyUnicode_DATA(unicode);
8937
Victor Stinnerb84d7232011-11-22 01:50:07 +01008938 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008939 PyObject *exc;
8940 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008942 Py_ssize_t startpos;
8943
8944 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008945
Benjamin Peterson29060642009-01-31 22:14:21 +00008946 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008947 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008948 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008950 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008951 decimal = Py_UNICODE_TODECIMAL(ch);
8952 if (decimal >= 0) {
8953 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008954 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 continue;
8956 }
8957 if (0 < ch && ch < 256) {
8958 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008959 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008960 continue;
8961 }
Victor Stinner6345be92011-11-25 20:09:01 +01008962
Victor Stinner42bf7752011-11-21 22:52:58 +01008963 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008964 exc = NULL;
8965 raise_encode_exception(&exc, "decimal", unicode,
8966 startpos, startpos+1,
8967 "invalid decimal Unicode string");
8968 Py_XDECREF(exc);
8969 Py_DECREF(unicode);
8970 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008971 }
8972 /* 0-terminate the output string */
8973 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008974 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008975 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008976}
8977
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978/* --- Helpers ------------------------------------------------------------ */
8979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008981any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 Py_ssize_t start,
8983 Py_ssize_t end)
8984{
8985 int kind1, kind2, kind;
8986 void *buf1, *buf2;
8987 Py_ssize_t len1, len2, result;
8988
8989 kind1 = PyUnicode_KIND(s1);
8990 kind2 = PyUnicode_KIND(s2);
8991 kind = kind1 > kind2 ? kind1 : kind2;
8992 buf1 = PyUnicode_DATA(s1);
8993 buf2 = PyUnicode_DATA(s2);
8994 if (kind1 != kind)
8995 buf1 = _PyUnicode_AsKind(s1, kind);
8996 if (!buf1)
8997 return -2;
8998 if (kind2 != kind)
8999 buf2 = _PyUnicode_AsKind(s2, kind);
9000 if (!buf2) {
9001 if (kind1 != kind) PyMem_Free(buf1);
9002 return -2;
9003 }
9004 len1 = PyUnicode_GET_LENGTH(s1);
9005 len2 = PyUnicode_GET_LENGTH(s2);
9006
Victor Stinner794d5672011-10-10 03:21:36 +02009007 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009008 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009009 case PyUnicode_1BYTE_KIND:
9010 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9011 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9012 else
9013 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9014 break;
9015 case PyUnicode_2BYTE_KIND:
9016 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9017 break;
9018 case PyUnicode_4BYTE_KIND:
9019 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9020 break;
9021 default:
9022 assert(0); result = -2;
9023 }
9024 }
9025 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009026 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009027 case PyUnicode_1BYTE_KIND:
9028 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9029 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9030 else
9031 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9032 break;
9033 case PyUnicode_2BYTE_KIND:
9034 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9035 break;
9036 case PyUnicode_4BYTE_KIND:
9037 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9038 break;
9039 default:
9040 assert(0); result = -2;
9041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042 }
9043
9044 if (kind1 != kind)
9045 PyMem_Free(buf1);
9046 if (kind2 != kind)
9047 PyMem_Free(buf2);
9048
9049 return result;
9050}
9051
9052Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009053_PyUnicode_InsertThousandsGrouping(
9054 PyObject *unicode, Py_ssize_t index,
9055 Py_ssize_t n_buffer,
9056 void *digits, Py_ssize_t n_digits,
9057 Py_ssize_t min_width,
9058 const char *grouping, PyObject *thousands_sep,
9059 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009060{
Victor Stinner41a863c2012-02-24 00:37:51 +01009061 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009062 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009063 Py_ssize_t thousands_sep_len;
9064 Py_ssize_t len;
9065
9066 if (unicode != NULL) {
9067 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009068 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009069 }
9070 else {
9071 kind = PyUnicode_1BYTE_KIND;
9072 data = NULL;
9073 }
9074 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9075 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9076 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9077 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009078 if (thousands_sep_kind < kind) {
9079 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9080 if (!thousands_sep_data)
9081 return -1;
9082 }
9083 else {
9084 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9085 if (!data)
9086 return -1;
9087 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009088 }
9089
Benjamin Petersonead6b532011-12-20 17:23:42 -06009090 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009092 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009094 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009095 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009096 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009097 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009098 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009099 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009100 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009101 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009102 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009104 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009105 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009106 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009107 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009108 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009109 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009110 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009111 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009112 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009113 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009114 break;
9115 default:
9116 assert(0);
9117 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009119 if (unicode != NULL && thousands_sep_kind != kind) {
9120 if (thousands_sep_kind < kind)
9121 PyMem_Free(thousands_sep_data);
9122 else
9123 PyMem_Free(data);
9124 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009125 if (unicode == NULL) {
9126 *maxchar = 127;
9127 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009128 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009129 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009130 }
9131 }
9132 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133}
9134
9135
Thomas Wouters477c8d52006-05-27 19:21:47 +00009136/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009137#define ADJUST_INDICES(start, end, len) \
9138 if (end > len) \
9139 end = len; \
9140 else if (end < 0) { \
9141 end += len; \
9142 if (end < 0) \
9143 end = 0; \
9144 } \
9145 if (start < 0) { \
9146 start += len; \
9147 if (start < 0) \
9148 start = 0; \
9149 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009150
Alexander Belopolsky40018472011-02-26 01:02:56 +00009151Py_ssize_t
9152PyUnicode_Count(PyObject *str,
9153 PyObject *substr,
9154 Py_ssize_t start,
9155 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009156{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009157 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009158 PyObject* str_obj;
9159 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009160 int kind1, kind2, kind;
9161 void *buf1 = NULL, *buf2 = NULL;
9162 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009163
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009164 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009165 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009167 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009168 if (!sub_obj) {
9169 Py_DECREF(str_obj);
9170 return -1;
9171 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009172 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009173 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009174 Py_DECREF(str_obj);
9175 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009176 }
Tim Petersced69f82003-09-16 20:30:58 +00009177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009178 kind1 = PyUnicode_KIND(str_obj);
9179 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009180 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009183 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009184 if (kind2 > kind) {
9185 Py_DECREF(sub_obj);
9186 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009187 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009188 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009189 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 if (!buf2)
9192 goto onError;
9193 len1 = PyUnicode_GET_LENGTH(str_obj);
9194 len2 = PyUnicode_GET_LENGTH(sub_obj);
9195
9196 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009197 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009199 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9200 result = asciilib_count(
9201 ((Py_UCS1*)buf1) + start, end - start,
9202 buf2, len2, PY_SSIZE_T_MAX
9203 );
9204 else
9205 result = ucs1lib_count(
9206 ((Py_UCS1*)buf1) + start, end - start,
9207 buf2, len2, PY_SSIZE_T_MAX
9208 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 break;
9210 case PyUnicode_2BYTE_KIND:
9211 result = ucs2lib_count(
9212 ((Py_UCS2*)buf1) + start, end - start,
9213 buf2, len2, PY_SSIZE_T_MAX
9214 );
9215 break;
9216 case PyUnicode_4BYTE_KIND:
9217 result = ucs4lib_count(
9218 ((Py_UCS4*)buf1) + start, end - start,
9219 buf2, len2, PY_SSIZE_T_MAX
9220 );
9221 break;
9222 default:
9223 assert(0); result = 0;
9224 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009225
9226 Py_DECREF(sub_obj);
9227 Py_DECREF(str_obj);
9228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229 if (kind2 != kind)
9230 PyMem_Free(buf2);
9231
Guido van Rossumd57fd912000-03-10 22:53:23 +00009232 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009233 onError:
9234 Py_DECREF(sub_obj);
9235 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 if (kind2 != kind && buf2)
9237 PyMem_Free(buf2);
9238 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239}
9240
Alexander Belopolsky40018472011-02-26 01:02:56 +00009241Py_ssize_t
9242PyUnicode_Find(PyObject *str,
9243 PyObject *sub,
9244 Py_ssize_t start,
9245 Py_ssize_t end,
9246 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009248 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009249
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009251 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009252 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009253 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009254 if (!sub) {
9255 Py_DECREF(str);
9256 return -2;
9257 }
9258 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9259 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009260 Py_DECREF(str);
9261 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262 }
Tim Petersced69f82003-09-16 20:30:58 +00009263
Victor Stinner794d5672011-10-10 03:21:36 +02009264 result = any_find_slice(direction,
9265 str, sub, start, end
9266 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009267
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009269 Py_DECREF(sub);
9270
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 return result;
9272}
9273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274Py_ssize_t
9275PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9276 Py_ssize_t start, Py_ssize_t end,
9277 int direction)
9278{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009280 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 if (PyUnicode_READY(str) == -1)
9282 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009283 if (start < 0 || end < 0) {
9284 PyErr_SetString(PyExc_IndexError, "string index out of range");
9285 return -2;
9286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 if (end > PyUnicode_GET_LENGTH(str))
9288 end = PyUnicode_GET_LENGTH(str);
9289 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009290 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9291 kind, end-start, ch, direction);
9292 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009294 else
9295 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296}
9297
Alexander Belopolsky40018472011-02-26 01:02:56 +00009298static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009299tailmatch(PyObject *self,
9300 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009301 Py_ssize_t start,
9302 Py_ssize_t end,
9303 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 int kind_self;
9306 int kind_sub;
9307 void *data_self;
9308 void *data_sub;
9309 Py_ssize_t offset;
9310 Py_ssize_t i;
9311 Py_ssize_t end_sub;
9312
9313 if (PyUnicode_READY(self) == -1 ||
9314 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316
9317 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009318 return 1;
9319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9321 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009323 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325 kind_self = PyUnicode_KIND(self);
9326 data_self = PyUnicode_DATA(self);
9327 kind_sub = PyUnicode_KIND(substring);
9328 data_sub = PyUnicode_DATA(substring);
9329 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9330
9331 if (direction > 0)
9332 offset = end;
9333 else
9334 offset = start;
9335
9336 if (PyUnicode_READ(kind_self, data_self, offset) ==
9337 PyUnicode_READ(kind_sub, data_sub, 0) &&
9338 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9339 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9340 /* If both are of the same kind, memcmp is sufficient */
9341 if (kind_self == kind_sub) {
9342 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009343 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 data_sub,
9345 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009346 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 }
9348 /* otherwise we have to compare each character by first accesing it */
9349 else {
9350 /* We do not need to compare 0 and len(substring)-1 because
9351 the if statement above ensured already that they are equal
9352 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 for (i = 1; i < end_sub; ++i) {
9354 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9355 PyUnicode_READ(kind_sub, data_sub, i))
9356 return 0;
9357 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009358 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360 }
9361
9362 return 0;
9363}
9364
Alexander Belopolsky40018472011-02-26 01:02:56 +00009365Py_ssize_t
9366PyUnicode_Tailmatch(PyObject *str,
9367 PyObject *substr,
9368 Py_ssize_t start,
9369 Py_ssize_t end,
9370 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009372 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009373
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 str = PyUnicode_FromObject(str);
9375 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009376 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377 substr = PyUnicode_FromObject(substr);
9378 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009379 Py_DECREF(str);
9380 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381 }
Tim Petersced69f82003-09-16 20:30:58 +00009382
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009383 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009384 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385 Py_DECREF(str);
9386 Py_DECREF(substr);
9387 return result;
9388}
9389
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390/* Apply fixfct filter to the Unicode object self and return a
9391 reference to the modified object */
9392
Alexander Belopolsky40018472011-02-26 01:02:56 +00009393static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009394fixup(PyObject *self,
9395 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 PyObject *u;
9398 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009399 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009401 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009402 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009403 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009404 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 /* fix functions return the new maximum character in a string,
9407 if the kind of the resulting unicode object does not change,
9408 everything is fine. Otherwise we need to change the string kind
9409 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009410 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009411
9412 if (maxchar_new == 0) {
9413 /* no changes */;
9414 if (PyUnicode_CheckExact(self)) {
9415 Py_DECREF(u);
9416 Py_INCREF(self);
9417 return self;
9418 }
9419 else
9420 return u;
9421 }
9422
Victor Stinnere6abb482012-05-02 01:15:40 +02009423 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424
Victor Stinnereaab6042011-12-11 22:22:39 +01009425 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009427
9428 /* In case the maximum character changed, we need to
9429 convert the string to the new category. */
9430 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9431 if (v == NULL) {
9432 Py_DECREF(u);
9433 return NULL;
9434 }
9435 if (maxchar_new > maxchar_old) {
9436 /* If the maxchar increased so that the kind changed, not all
9437 characters are representable anymore and we need to fix the
9438 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009439 _PyUnicode_FastCopyCharacters(v, 0,
9440 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009441 maxchar_old = fixfct(v);
9442 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 }
9444 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009445 _PyUnicode_FastCopyCharacters(v, 0,
9446 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009448 Py_DECREF(u);
9449 assert(_PyUnicode_CheckConsistency(v, 1));
9450 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451}
9452
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009453static PyObject *
9454ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009456 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9457 char *resdata, *data = PyUnicode_DATA(self);
9458 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009459
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009460 res = PyUnicode_New(len, 127);
9461 if (res == NULL)
9462 return NULL;
9463 resdata = PyUnicode_DATA(res);
9464 if (lower)
9465 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009467 _Py_bytes_upper(resdata, data, len);
9468 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009469}
9470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009472handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009474 Py_ssize_t j;
9475 int final_sigma;
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02009476 Py_UCS4 c = 0;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009477 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009478
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009479 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9480
9481 where ! is a negation and \p{xxx} is a character with property xxx.
9482 */
9483 for (j = i - 1; j >= 0; j--) {
9484 c = PyUnicode_READ(kind, data, j);
9485 if (!_PyUnicode_IsCaseIgnorable(c))
9486 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009488 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9489 if (final_sigma) {
9490 for (j = i + 1; j < length; j++) {
9491 c = PyUnicode_READ(kind, data, j);
9492 if (!_PyUnicode_IsCaseIgnorable(c))
9493 break;
9494 }
9495 final_sigma = j == length || !_PyUnicode_IsCased(c);
9496 }
9497 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498}
9499
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009500static int
9501lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9502 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009504 /* Obscure special case. */
9505 if (c == 0x3A3) {
9506 mapped[0] = handle_capital_sigma(kind, data, length, i);
9507 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009509 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510}
9511
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009512static Py_ssize_t
9513do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009515 Py_ssize_t i, k = 0;
9516 int n_res, j;
9517 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009518
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009519 c = PyUnicode_READ(kind, data, 0);
9520 n_res = _PyUnicode_ToUpperFull(c, mapped);
9521 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009522 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009523 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009525 for (i = 1; i < length; i++) {
9526 c = PyUnicode_READ(kind, data, i);
9527 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9528 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009529 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009530 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009531 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009532 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009533 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534}
9535
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009536static Py_ssize_t
9537do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9538 Py_ssize_t i, k = 0;
9539
9540 for (i = 0; i < length; i++) {
9541 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9542 int n_res, j;
9543 if (Py_UNICODE_ISUPPER(c)) {
9544 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9545 }
9546 else if (Py_UNICODE_ISLOWER(c)) {
9547 n_res = _PyUnicode_ToUpperFull(c, mapped);
9548 }
9549 else {
9550 n_res = 1;
9551 mapped[0] = c;
9552 }
9553 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009554 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009555 res[k++] = mapped[j];
9556 }
9557 }
9558 return k;
9559}
9560
9561static Py_ssize_t
9562do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9563 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 Py_ssize_t i, k = 0;
9566
9567 for (i = 0; i < length; i++) {
9568 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9569 int n_res, j;
9570 if (lower)
9571 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9572 else
9573 n_res = _PyUnicode_ToUpperFull(c, mapped);
9574 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009575 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009576 res[k++] = mapped[j];
9577 }
9578 }
9579 return k;
9580}
9581
9582static Py_ssize_t
9583do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9584{
9585 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9586}
9587
9588static Py_ssize_t
9589do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9590{
9591 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9592}
9593
Benjamin Petersone51757f2012-01-12 21:10:29 -05009594static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009595do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9596{
9597 Py_ssize_t i, k = 0;
9598
9599 for (i = 0; i < length; i++) {
9600 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9601 Py_UCS4 mapped[3];
9602 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9603 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009604 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009605 res[k++] = mapped[j];
9606 }
9607 }
9608 return k;
9609}
9610
9611static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009612do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9613{
9614 Py_ssize_t i, k = 0;
9615 int previous_is_cased;
9616
9617 previous_is_cased = 0;
9618 for (i = 0; i < length; i++) {
9619 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9620 Py_UCS4 mapped[3];
9621 int n_res, j;
9622
9623 if (previous_is_cased)
9624 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9625 else
9626 n_res = _PyUnicode_ToTitleFull(c, mapped);
9627
9628 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009629 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009630 res[k++] = mapped[j];
9631 }
9632
9633 previous_is_cased = _PyUnicode_IsCased(c);
9634 }
9635 return k;
9636}
9637
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638static PyObject *
9639case_operation(PyObject *self,
9640 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9641{
9642 PyObject *res = NULL;
9643 Py_ssize_t length, newlength = 0;
9644 int kind, outkind;
9645 void *data, *outdata;
9646 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9647
Benjamin Petersoneea48462012-01-16 14:28:50 -05009648 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649
9650 kind = PyUnicode_KIND(self);
9651 data = PyUnicode_DATA(self);
9652 length = PyUnicode_GET_LENGTH(self);
Antoine Pitroub6dc9b72014-10-15 23:14:53 +02009653 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009654 PyErr_SetString(PyExc_OverflowError, "string is too long");
9655 return NULL;
9656 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009657 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 if (tmp == NULL)
9659 return PyErr_NoMemory();
9660 newlength = perform(kind, data, length, tmp, &maxchar);
9661 res = PyUnicode_New(newlength, maxchar);
9662 if (res == NULL)
9663 goto leave;
9664 tmpend = tmp + newlength;
9665 outdata = PyUnicode_DATA(res);
9666 outkind = PyUnicode_KIND(res);
9667 switch (outkind) {
9668 case PyUnicode_1BYTE_KIND:
9669 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9670 break;
9671 case PyUnicode_2BYTE_KIND:
9672 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9673 break;
9674 case PyUnicode_4BYTE_KIND:
9675 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9676 break;
9677 default:
9678 assert(0);
9679 break;
9680 }
9681 leave:
9682 PyMem_FREE(tmp);
9683 return res;
9684}
9685
Tim Peters8ce9f162004-08-27 01:49:32 +00009686PyObject *
9687PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009688{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009690 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9694 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009695 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009696 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009697 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009699 int use_memcpy;
9700 unsigned char *res_data = NULL, *sep_data = NULL;
9701 PyObject *last_obj;
9702 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009703
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009704 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009705 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009706 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009707 }
9708
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009709 /* NOTE: the following code can't call back into Python code,
9710 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009711 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009712
Tim Peters05eba1f2004-08-27 21:32:02 +00009713 seqlen = PySequence_Fast_GET_SIZE(fseq);
9714 /* If empty sequence, return u"". */
9715 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009716 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009717 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009718 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009719
Tim Peters05eba1f2004-08-27 21:32:02 +00009720 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009721 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009722 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009723 if (seqlen == 1) {
9724 if (PyUnicode_CheckExact(items[0])) {
9725 res = items[0];
9726 Py_INCREF(res);
9727 Py_DECREF(fseq);
9728 return res;
9729 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009730 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009731 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009732 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009733 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009734 /* Set up sep and seplen */
9735 if (separator == NULL) {
9736 /* fall back to a blank space separator */
9737 sep = PyUnicode_FromOrdinal(' ');
9738 if (!sep)
9739 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009741 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009742 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009743 else {
9744 if (!PyUnicode_Check(separator)) {
9745 PyErr_Format(PyExc_TypeError,
9746 "separator: expected str instance,"
9747 " %.80s found",
9748 Py_TYPE(separator)->tp_name);
9749 goto onError;
9750 }
9751 if (PyUnicode_READY(separator))
9752 goto onError;
9753 sep = separator;
9754 seplen = PyUnicode_GET_LENGTH(separator);
9755 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9756 /* inc refcount to keep this code path symmetric with the
9757 above case of a blank separator */
9758 Py_INCREF(sep);
9759 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009760 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009761 }
9762
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 /* There are at least two things to join, or else we have a subclass
9764 * of str in the sequence.
9765 * Do a pre-pass to figure out the total amount of space we'll
9766 * need (sz), and see whether all argument are strings.
9767 */
9768 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009769#ifdef Py_DEBUG
9770 use_memcpy = 0;
9771#else
9772 use_memcpy = 1;
9773#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009774 for (i = 0; i < seqlen; i++) {
9775 const Py_ssize_t old_sz = sz;
9776 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009777 if (!PyUnicode_Check(item)) {
9778 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009779 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009780 " %.80s found",
9781 i, Py_TYPE(item)->tp_name);
9782 goto onError;
9783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 if (PyUnicode_READY(item) == -1)
9785 goto onError;
9786 sz += PyUnicode_GET_LENGTH(item);
9787 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009788 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009789 if (i != 0)
9790 sz += seplen;
9791 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9792 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009793 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009794 goto onError;
9795 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009796 if (use_memcpy && last_obj != NULL) {
9797 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9798 use_memcpy = 0;
9799 }
9800 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009801 }
Tim Petersced69f82003-09-16 20:30:58 +00009802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009804 if (res == NULL)
9805 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009806
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009807 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009808#ifdef Py_DEBUG
9809 use_memcpy = 0;
9810#else
9811 if (use_memcpy) {
9812 res_data = PyUnicode_1BYTE_DATA(res);
9813 kind = PyUnicode_KIND(res);
9814 if (seplen != 0)
9815 sep_data = PyUnicode_1BYTE_DATA(sep);
9816 }
9817#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009818 if (use_memcpy) {
9819 for (i = 0; i < seqlen; ++i) {
9820 Py_ssize_t itemlen;
9821 item = items[i];
9822
9823 /* Copy item, and maybe the separator. */
9824 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009825 Py_MEMCPY(res_data,
9826 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009827 kind * seplen);
9828 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009829 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009830
9831 itemlen = PyUnicode_GET_LENGTH(item);
9832 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009833 Py_MEMCPY(res_data,
9834 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009835 kind * itemlen);
9836 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009837 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009838 }
9839 assert(res_data == PyUnicode_1BYTE_DATA(res)
9840 + kind * PyUnicode_GET_LENGTH(res));
9841 }
9842 else {
9843 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9844 Py_ssize_t itemlen;
9845 item = items[i];
9846
9847 /* Copy item, and maybe the separator. */
9848 if (i && seplen != 0) {
9849 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9850 res_offset += seplen;
9851 }
9852
9853 itemlen = PyUnicode_GET_LENGTH(item);
9854 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009855 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009856 res_offset += itemlen;
9857 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009858 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009859 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009860 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009861
Tim Peters05eba1f2004-08-27 21:32:02 +00009862 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009864 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866
Benjamin Peterson29060642009-01-31 22:14:21 +00009867 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009868 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009870 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009871 return NULL;
9872}
9873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874#define FILL(kind, data, value, start, length) \
9875 do { \
9876 Py_ssize_t i_ = 0; \
9877 assert(kind != PyUnicode_WCHAR_KIND); \
9878 switch ((kind)) { \
9879 case PyUnicode_1BYTE_KIND: { \
9880 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009881 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 break; \
9883 } \
9884 case PyUnicode_2BYTE_KIND: { \
9885 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9886 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9887 break; \
9888 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009889 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9891 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9892 break; \
9893 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009894 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 } \
9896 } while (0)
9897
Victor Stinnerd3f08822012-05-29 12:57:52 +02009898void
9899_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9900 Py_UCS4 fill_char)
9901{
9902 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9903 const void *data = PyUnicode_DATA(unicode);
9904 assert(PyUnicode_IS_READY(unicode));
9905 assert(unicode_modifiable(unicode));
9906 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9907 assert(start >= 0);
9908 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9909 FILL(kind, data, fill_char, start, length);
9910}
9911
Victor Stinner3fe55312012-01-04 00:33:50 +01009912Py_ssize_t
9913PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9914 Py_UCS4 fill_char)
9915{
9916 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009917
9918 if (!PyUnicode_Check(unicode)) {
9919 PyErr_BadInternalCall();
9920 return -1;
9921 }
9922 if (PyUnicode_READY(unicode) == -1)
9923 return -1;
9924 if (unicode_check_modifiable(unicode))
9925 return -1;
9926
Victor Stinnerd3f08822012-05-29 12:57:52 +02009927 if (start < 0) {
9928 PyErr_SetString(PyExc_IndexError, "string index out of range");
9929 return -1;
9930 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009931 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9932 PyErr_SetString(PyExc_ValueError,
9933 "fill character is bigger than "
9934 "the string maximum character");
9935 return -1;
9936 }
9937
9938 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9939 length = Py_MIN(maxlen, length);
9940 if (length <= 0)
9941 return 0;
9942
Victor Stinnerd3f08822012-05-29 12:57:52 +02009943 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009944 return length;
9945}
9946
Victor Stinner9310abb2011-10-05 00:59:23 +02009947static PyObject *
9948pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009949 Py_ssize_t left,
9950 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 PyObject *u;
9954 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009955 int kind;
9956 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957
9958 if (left < 0)
9959 left = 0;
9960 if (right < 0)
9961 right = 0;
9962
Victor Stinnerc4b49542011-12-11 22:44:26 +01009963 if (left == 0 && right == 0)
9964 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9967 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009968 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9969 return NULL;
9970 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009972 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009974 if (!u)
9975 return NULL;
9976
9977 kind = PyUnicode_KIND(u);
9978 data = PyUnicode_DATA(u);
9979 if (left)
9980 FILL(kind, data, fill, 0, left);
9981 if (right)
9982 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009983 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009984 assert(_PyUnicode_CheckConsistency(u, 1));
9985 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986}
9987
Alexander Belopolsky40018472011-02-26 01:02:56 +00009988PyObject *
9989PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992
9993 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009994 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009995 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009996 if (PyUnicode_READY(string) == -1) {
9997 Py_DECREF(string);
9998 return NULL;
9999 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010000
Benjamin Petersonead6b532011-12-20 17:23:42 -060010001 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010003 if (PyUnicode_IS_ASCII(string))
10004 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010005 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010006 PyUnicode_GET_LENGTH(string), keepends);
10007 else
10008 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010010 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 break;
10012 case PyUnicode_2BYTE_KIND:
10013 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010014 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 PyUnicode_GET_LENGTH(string), keepends);
10016 break;
10017 case PyUnicode_4BYTE_KIND:
10018 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010019 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 PyUnicode_GET_LENGTH(string), keepends);
10021 break;
10022 default:
10023 assert(0);
10024 list = 0;
10025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010026 Py_DECREF(string);
10027 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010028}
10029
Alexander Belopolsky40018472011-02-26 01:02:56 +000010030static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010031split(PyObject *self,
10032 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010033 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 int kind1, kind2, kind;
10036 void *buf1, *buf2;
10037 Py_ssize_t len1, len2;
10038 PyObject* out;
10039
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010041 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 if (PyUnicode_READY(self) == -1)
10044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010047 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010049 if (PyUnicode_IS_ASCII(self))
10050 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010051 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010052 PyUnicode_GET_LENGTH(self), maxcount
10053 );
10054 else
10055 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010056 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010057 PyUnicode_GET_LENGTH(self), maxcount
10058 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 case PyUnicode_2BYTE_KIND:
10060 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010061 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 PyUnicode_GET_LENGTH(self), maxcount
10063 );
10064 case PyUnicode_4BYTE_KIND:
10065 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010066 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 PyUnicode_GET_LENGTH(self), maxcount
10068 );
10069 default:
10070 assert(0);
10071 return NULL;
10072 }
10073
10074 if (PyUnicode_READY(substring) == -1)
10075 return NULL;
10076
10077 kind1 = PyUnicode_KIND(self);
10078 kind2 = PyUnicode_KIND(substring);
10079 kind = kind1 > kind2 ? kind1 : kind2;
10080 buf1 = PyUnicode_DATA(self);
10081 buf2 = PyUnicode_DATA(substring);
10082 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010083 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 if (!buf1)
10085 return NULL;
10086 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010087 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 if (!buf2) {
10089 if (kind1 != kind) PyMem_Free(buf1);
10090 return NULL;
10091 }
10092 len1 = PyUnicode_GET_LENGTH(self);
10093 len2 = PyUnicode_GET_LENGTH(substring);
10094
Benjamin Petersonead6b532011-12-20 17:23:42 -060010095 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010097 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10098 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010099 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 else
10101 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010102 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 break;
10104 case PyUnicode_2BYTE_KIND:
10105 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010106 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 break;
10108 case PyUnicode_4BYTE_KIND:
10109 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010110 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 break;
10112 default:
10113 out = NULL;
10114 }
10115 if (kind1 != kind)
10116 PyMem_Free(buf1);
10117 if (kind2 != kind)
10118 PyMem_Free(buf2);
10119 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010120}
10121
Alexander Belopolsky40018472011-02-26 01:02:56 +000010122static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010123rsplit(PyObject *self,
10124 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010126{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 int kind1, kind2, kind;
10128 void *buf1, *buf2;
10129 Py_ssize_t len1, len2;
10130 PyObject* out;
10131
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010132 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010133 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 if (PyUnicode_READY(self) == -1)
10136 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010139 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010141 if (PyUnicode_IS_ASCII(self))
10142 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010143 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144 PyUnicode_GET_LENGTH(self), maxcount
10145 );
10146 else
10147 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010148 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 PyUnicode_GET_LENGTH(self), maxcount
10150 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 case PyUnicode_2BYTE_KIND:
10152 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010153 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 PyUnicode_GET_LENGTH(self), maxcount
10155 );
10156 case PyUnicode_4BYTE_KIND:
10157 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010158 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 PyUnicode_GET_LENGTH(self), maxcount
10160 );
10161 default:
10162 assert(0);
10163 return NULL;
10164 }
10165
10166 if (PyUnicode_READY(substring) == -1)
10167 return NULL;
10168
10169 kind1 = PyUnicode_KIND(self);
10170 kind2 = PyUnicode_KIND(substring);
10171 kind = kind1 > kind2 ? kind1 : kind2;
10172 buf1 = PyUnicode_DATA(self);
10173 buf2 = PyUnicode_DATA(substring);
10174 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010175 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (!buf1)
10177 return NULL;
10178 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010179 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 if (!buf2) {
10181 if (kind1 != kind) PyMem_Free(buf1);
10182 return NULL;
10183 }
10184 len1 = PyUnicode_GET_LENGTH(self);
10185 len2 = PyUnicode_GET_LENGTH(substring);
10186
Benjamin Petersonead6b532011-12-20 17:23:42 -060010187 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10190 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010191 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 else
10193 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010194 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 break;
10196 case PyUnicode_2BYTE_KIND:
10197 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010198 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 break;
10200 case PyUnicode_4BYTE_KIND:
10201 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 break;
10204 default:
10205 out = NULL;
10206 }
10207 if (kind1 != kind)
10208 PyMem_Free(buf1);
10209 if (kind2 != kind)
10210 PyMem_Free(buf2);
10211 return out;
10212}
10213
10214static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010215anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10216 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010218 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010220 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10221 return asciilib_find(buf1, len1, buf2, len2, offset);
10222 else
10223 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 case PyUnicode_2BYTE_KIND:
10225 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10226 case PyUnicode_4BYTE_KIND:
10227 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10228 }
10229 assert(0);
10230 return -1;
10231}
10232
10233static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010234anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10235 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010237 switch (kind) {
10238 case PyUnicode_1BYTE_KIND:
10239 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10240 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10241 else
10242 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10243 case PyUnicode_2BYTE_KIND:
10244 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10245 case PyUnicode_4BYTE_KIND:
10246 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10247 }
10248 assert(0);
10249 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010250}
10251
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010252static void
10253replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10254 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10255{
10256 int kind = PyUnicode_KIND(u);
10257 void *data = PyUnicode_DATA(u);
10258 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10259 if (kind == PyUnicode_1BYTE_KIND) {
10260 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10261 (Py_UCS1 *)data + len,
10262 u1, u2, maxcount);
10263 }
10264 else if (kind == PyUnicode_2BYTE_KIND) {
10265 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10266 (Py_UCS2 *)data + len,
10267 u1, u2, maxcount);
10268 }
10269 else {
10270 assert(kind == PyUnicode_4BYTE_KIND);
10271 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10272 (Py_UCS4 *)data + len,
10273 u1, u2, maxcount);
10274 }
10275}
10276
Alexander Belopolsky40018472011-02-26 01:02:56 +000010277static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278replace(PyObject *self, PyObject *str1,
10279 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 PyObject *u;
10282 char *sbuf = PyUnicode_DATA(self);
10283 char *buf1 = PyUnicode_DATA(str1);
10284 char *buf2 = PyUnicode_DATA(str2);
10285 int srelease = 0, release1 = 0, release2 = 0;
10286 int skind = PyUnicode_KIND(self);
10287 int kind1 = PyUnicode_KIND(str1);
10288 int kind2 = PyUnicode_KIND(str2);
10289 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10290 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10291 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010292 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010293 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294
10295 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010296 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010298 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299
Victor Stinner59de0ee2011-10-07 10:01:28 +020010300 if (str1 == str2)
10301 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302
Victor Stinner49a0a212011-10-12 23:46:10 +020010303 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010304 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10305 if (maxchar < maxchar_str1)
10306 /* substring too wide to be present */
10307 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010308 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10309 /* Replacing str1 with str2 may cause a maxchar reduction in the
10310 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010311 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010312 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010315 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010317 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010320 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010321 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010322
Victor Stinner69ed0f42013-04-09 21:48:24 +020010323 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010324 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010325 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010326 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010327 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010331
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010332 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10333 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010334 }
10335 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 int rkind = skind;
10337 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010338 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 if (kind1 < rkind) {
10341 /* widen substring */
10342 buf1 = _PyUnicode_AsKind(str1, rkind);
10343 if (!buf1) goto error;
10344 release1 = 1;
10345 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010346 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010347 if (i < 0)
10348 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 if (rkind > kind2) {
10350 /* widen replacement */
10351 buf2 = _PyUnicode_AsKind(str2, rkind);
10352 if (!buf2) goto error;
10353 release2 = 1;
10354 }
10355 else if (rkind < kind2) {
10356 /* widen self and buf1 */
10357 rkind = kind2;
10358 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010359 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 sbuf = _PyUnicode_AsKind(self, rkind);
10361 if (!sbuf) goto error;
10362 srelease = 1;
10363 buf1 = _PyUnicode_AsKind(str1, rkind);
10364 if (!buf1) goto error;
10365 release1 = 1;
10366 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010367 u = PyUnicode_New(slen, maxchar);
10368 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010370 assert(PyUnicode_KIND(u) == rkind);
10371 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010372
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010373 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010374 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010375 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010377 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010379
10380 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010381 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010382 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010383 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010384 if (i == -1)
10385 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010386 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010388 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010392 }
10393 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010395 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 int rkind = skind;
10397 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010400 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 buf1 = _PyUnicode_AsKind(str1, rkind);
10402 if (!buf1) goto error;
10403 release1 = 1;
10404 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010405 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010406 if (n == 0)
10407 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010409 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 buf2 = _PyUnicode_AsKind(str2, rkind);
10411 if (!buf2) goto error;
10412 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010415 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 rkind = kind2;
10417 sbuf = _PyUnicode_AsKind(self, rkind);
10418 if (!sbuf) goto error;
10419 srelease = 1;
10420 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010421 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 buf1 = _PyUnicode_AsKind(str1, rkind);
10423 if (!buf1) goto error;
10424 release1 = 1;
10425 }
10426 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10427 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010428 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 PyErr_SetString(PyExc_OverflowError,
10430 "replace string is too long");
10431 goto error;
10432 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010433 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010434 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010435 _Py_INCREF_UNICODE_EMPTY();
10436 if (!unicode_empty)
10437 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 u = unicode_empty;
10439 goto done;
10440 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010441 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 PyErr_SetString(PyExc_OverflowError,
10443 "replace string is too long");
10444 goto error;
10445 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010446 u = PyUnicode_New(new_size, maxchar);
10447 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010449 assert(PyUnicode_KIND(u) == rkind);
10450 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 ires = i = 0;
10452 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 while (n-- > 0) {
10454 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010455 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010456 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010457 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010458 if (j == -1)
10459 break;
10460 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010461 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010462 memcpy(res + rkind * ires,
10463 sbuf + rkind * i,
10464 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010466 }
10467 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010469 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010473 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010475 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010477 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010478 memcpy(res + rkind * ires,
10479 sbuf + rkind * i,
10480 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010481 }
10482 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010483 /* interleave */
10484 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010485 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010487 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489 if (--n <= 0)
10490 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010491 memcpy(res + rkind * ires,
10492 sbuf + rkind * i,
10493 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 ires++;
10495 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010497 memcpy(res + rkind * ires,
10498 sbuf + rkind * i,
10499 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010501 }
10502
10503 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010504 unicode_adjust_maxchar(&u);
10505 if (u == NULL)
10506 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010508
10509 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 if (srelease)
10511 PyMem_FREE(sbuf);
10512 if (release1)
10513 PyMem_FREE(buf1);
10514 if (release2)
10515 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010516 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010518
Benjamin Peterson29060642009-01-31 22:14:21 +000010519 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010520 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (srelease)
10522 PyMem_FREE(sbuf);
10523 if (release1)
10524 PyMem_FREE(buf1);
10525 if (release2)
10526 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010527 return unicode_result_unchanged(self);
10528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 error:
10530 if (srelease && sbuf)
10531 PyMem_FREE(sbuf);
10532 if (release1 && buf1)
10533 PyMem_FREE(buf1);
10534 if (release2 && buf2)
10535 PyMem_FREE(buf2);
10536 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537}
10538
10539/* --- Unicode Object Methods --------------------------------------------- */
10540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010541PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010542 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543\n\
10544Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010545characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546
10547static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010548unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010550 if (PyUnicode_READY(self) == -1)
10551 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010552 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010553}
10554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010555PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010556 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010557\n\
10558Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010559have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560
10561static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010562unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010564 if (PyUnicode_READY(self) == -1)
10565 return NULL;
10566 if (PyUnicode_GET_LENGTH(self) == 0)
10567 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010568 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010569}
10570
Benjamin Petersond5890c82012-01-14 13:23:30 -050010571PyDoc_STRVAR(casefold__doc__,
10572 "S.casefold() -> str\n\
10573\n\
10574Return a version of S suitable for caseless comparisons.");
10575
10576static PyObject *
10577unicode_casefold(PyObject *self)
10578{
10579 if (PyUnicode_READY(self) == -1)
10580 return NULL;
10581 if (PyUnicode_IS_ASCII(self))
10582 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010583 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010584}
10585
10586
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010587/* Argument converter. Coerces to a single unicode character */
10588
10589static int
10590convert_uc(PyObject *obj, void *addr)
10591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010593 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010594
Benjamin Peterson14339b62009-01-31 16:36:08 +000010595 uniobj = PyUnicode_FromObject(obj);
10596 if (uniobj == NULL) {
10597 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010598 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010599 return 0;
10600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010602 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010603 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010604 Py_DECREF(uniobj);
10605 return 0;
10606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010608 Py_DECREF(uniobj);
10609 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010610}
10611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010612PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010613 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010614\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010615Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010616done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617
10618static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010619unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010621 Py_ssize_t marg, left;
10622 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 Py_UCS4 fillchar = ' ';
10624
Victor Stinnere9a29352011-10-01 02:14:59 +020010625 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627
Benjamin Petersonbac79492012-01-14 13:34:47 -050010628 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629 return NULL;
10630
Victor Stinnerc4b49542011-12-11 22:44:26 +010010631 if (PyUnicode_GET_LENGTH(self) >= width)
10632 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633
Victor Stinnerc4b49542011-12-11 22:44:26 +010010634 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635 left = marg / 2 + (marg & width & 1);
10636
Victor Stinner9310abb2011-10-05 00:59:23 +020010637 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638}
10639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640/* This function assumes that str1 and str2 are readied by the caller. */
10641
Marc-André Lemburge5034372000-08-08 08:04:29 +000010642static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010643unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010644{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010645#define COMPARE(TYPE1, TYPE2) \
10646 do { \
10647 TYPE1* p1 = (TYPE1 *)data1; \
10648 TYPE2* p2 = (TYPE2 *)data2; \
10649 TYPE1* end = p1 + len; \
10650 Py_UCS4 c1, c2; \
10651 for (; p1 != end; p1++, p2++) { \
10652 c1 = *p1; \
10653 c2 = *p2; \
10654 if (c1 != c2) \
10655 return (c1 < c2) ? -1 : 1; \
10656 } \
10657 } \
10658 while (0)
10659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 int kind1, kind2;
10661 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010662 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010663
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 kind1 = PyUnicode_KIND(str1);
10665 kind2 = PyUnicode_KIND(str2);
10666 data1 = PyUnicode_DATA(str1);
10667 data2 = PyUnicode_DATA(str2);
10668 len1 = PyUnicode_GET_LENGTH(str1);
10669 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010670 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010671
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010672 switch(kind1) {
10673 case PyUnicode_1BYTE_KIND:
10674 {
10675 switch(kind2) {
10676 case PyUnicode_1BYTE_KIND:
10677 {
10678 int cmp = memcmp(data1, data2, len);
10679 /* normalize result of memcmp() into the range [-1; 1] */
10680 if (cmp < 0)
10681 return -1;
10682 if (cmp > 0)
10683 return 1;
10684 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010685 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010686 case PyUnicode_2BYTE_KIND:
10687 COMPARE(Py_UCS1, Py_UCS2);
10688 break;
10689 case PyUnicode_4BYTE_KIND:
10690 COMPARE(Py_UCS1, Py_UCS4);
10691 break;
10692 default:
10693 assert(0);
10694 }
10695 break;
10696 }
10697 case PyUnicode_2BYTE_KIND:
10698 {
10699 switch(kind2) {
10700 case PyUnicode_1BYTE_KIND:
10701 COMPARE(Py_UCS2, Py_UCS1);
10702 break;
10703 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010704 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010705 COMPARE(Py_UCS2, Py_UCS2);
10706 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010707 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010708 case PyUnicode_4BYTE_KIND:
10709 COMPARE(Py_UCS2, Py_UCS4);
10710 break;
10711 default:
10712 assert(0);
10713 }
10714 break;
10715 }
10716 case PyUnicode_4BYTE_KIND:
10717 {
10718 switch(kind2) {
10719 case PyUnicode_1BYTE_KIND:
10720 COMPARE(Py_UCS4, Py_UCS1);
10721 break;
10722 case PyUnicode_2BYTE_KIND:
10723 COMPARE(Py_UCS4, Py_UCS2);
10724 break;
10725 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010726 {
10727#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10728 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10729 /* normalize result of wmemcmp() into the range [-1; 1] */
10730 if (cmp < 0)
10731 return -1;
10732 if (cmp > 0)
10733 return 1;
10734#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010735 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010736#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010737 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010738 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010739 default:
10740 assert(0);
10741 }
10742 break;
10743 }
10744 default:
10745 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010746 }
10747
Victor Stinner770e19e2012-10-04 22:59:45 +020010748 if (len1 == len2)
10749 return 0;
10750 if (len1 < len2)
10751 return -1;
10752 else
10753 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010754
10755#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010756}
10757
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010758Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010759unicode_compare_eq(PyObject *str1, PyObject *str2)
10760{
10761 int kind;
10762 void *data1, *data2;
10763 Py_ssize_t len;
10764 int cmp;
10765
Victor Stinnere5567ad2012-10-23 02:48:49 +020010766 len = PyUnicode_GET_LENGTH(str1);
10767 if (PyUnicode_GET_LENGTH(str2) != len)
10768 return 0;
10769 kind = PyUnicode_KIND(str1);
10770 if (PyUnicode_KIND(str2) != kind)
10771 return 0;
10772 data1 = PyUnicode_DATA(str1);
10773 data2 = PyUnicode_DATA(str2);
10774
10775 cmp = memcmp(data1, data2, len * kind);
10776 return (cmp == 0);
10777}
10778
10779
Alexander Belopolsky40018472011-02-26 01:02:56 +000010780int
10781PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10784 if (PyUnicode_READY(left) == -1 ||
10785 PyUnicode_READY(right) == -1)
10786 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010787
10788 /* a string is equal to itself */
10789 if (left == right)
10790 return 0;
10791
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010792 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010794 PyErr_Format(PyExc_TypeError,
10795 "Can't compare %.100s and %.100s",
10796 left->ob_type->tp_name,
10797 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 return -1;
10799}
10800
Martin v. Löwis5b222132007-06-10 09:51:05 +000010801int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010802_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10803{
10804 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10805 if (right_str == NULL)
10806 return -1;
10807 return PyUnicode_Compare(left, right_str);
10808}
10809
10810int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010811PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010813 Py_ssize_t i;
10814 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 Py_UCS4 chr;
10816
Victor Stinner910337b2011-10-03 03:20:16 +020010817 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 if (PyUnicode_READY(uni) == -1)
10819 return -1;
10820 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010821 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010822 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010823 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010824 size_t len, len2 = strlen(str);
10825 int cmp;
10826
10827 len = Py_MIN(len1, len2);
10828 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010829 if (cmp != 0) {
10830 if (cmp < 0)
10831 return -1;
10832 else
10833 return 1;
10834 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010835 if (len1 > len2)
10836 return 1; /* uni is longer */
10837 if (len2 > len1)
10838 return -1; /* str is longer */
10839 return 0;
10840 }
10841 else {
10842 void *data = PyUnicode_DATA(uni);
10843 /* Compare Unicode string and source character set string */
10844 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10845 if (chr != str[i])
10846 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10847 /* This check keeps Python strings that end in '\0' from comparing equal
10848 to C strings identical up to that point. */
10849 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10850 return 1; /* uni is longer */
10851 if (str[i])
10852 return -1; /* str is longer */
10853 return 0;
10854 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010855}
10856
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010857
Benjamin Peterson29060642009-01-31 22:14:21 +000010858#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010859 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010860
Alexander Belopolsky40018472011-02-26 01:02:56 +000010861PyObject *
10862PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010863{
10864 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010865 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010866
Victor Stinnere5567ad2012-10-23 02:48:49 +020010867 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10868 Py_RETURN_NOTIMPLEMENTED;
10869
10870 if (PyUnicode_READY(left) == -1 ||
10871 PyUnicode_READY(right) == -1)
10872 return NULL;
10873
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010874 if (left == right) {
10875 switch (op) {
10876 case Py_EQ:
10877 case Py_LE:
10878 case Py_GE:
10879 /* a string is equal to itself */
10880 v = Py_True;
10881 break;
10882 case Py_NE:
10883 case Py_LT:
10884 case Py_GT:
10885 v = Py_False;
10886 break;
10887 default:
10888 PyErr_BadArgument();
10889 return NULL;
10890 }
10891 }
10892 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010893 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010894 result ^= (op == Py_NE);
10895 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010896 }
10897 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010898 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010899
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010900 /* Convert the return value to a Boolean */
10901 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010902 case Py_LE:
10903 v = TEST_COND(result <= 0);
10904 break;
10905 case Py_GE:
10906 v = TEST_COND(result >= 0);
10907 break;
10908 case Py_LT:
10909 v = TEST_COND(result == -1);
10910 break;
10911 case Py_GT:
10912 v = TEST_COND(result == 1);
10913 break;
10914 default:
10915 PyErr_BadArgument();
10916 return NULL;
10917 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010918 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010919 Py_INCREF(v);
10920 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010921}
10922
Alexander Belopolsky40018472011-02-26 01:02:56 +000010923int
10924PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010925{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010926 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010927 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 void *buf1, *buf2;
10929 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010930 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010931
10932 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010933 sub = PyUnicode_FromObject(element);
10934 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010935 PyErr_Format(PyExc_TypeError,
10936 "'in <string>' requires string as left operand, not %s",
10937 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010938 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010939 }
10940
Thomas Wouters477c8d52006-05-27 19:21:47 +000010941 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010942 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010943 Py_DECREF(sub);
10944 return -1;
10945 }
10946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 kind1 = PyUnicode_KIND(str);
10948 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949 buf1 = PyUnicode_DATA(str);
10950 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010951 if (kind2 != kind1) {
10952 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010953 Py_DECREF(sub);
10954 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010955 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010956 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010957 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010959 if (!buf2) {
10960 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010961 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 return -1;
10963 }
10964 len1 = PyUnicode_GET_LENGTH(str);
10965 len2 = PyUnicode_GET_LENGTH(sub);
10966
Victor Stinner77282cb2013-04-14 19:22:47 +020010967 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968 case PyUnicode_1BYTE_KIND:
10969 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10970 break;
10971 case PyUnicode_2BYTE_KIND:
10972 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10973 break;
10974 case PyUnicode_4BYTE_KIND:
10975 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10976 break;
10977 default:
10978 result = -1;
10979 assert(0);
10980 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010981
10982 Py_DECREF(str);
10983 Py_DECREF(sub);
10984
Victor Stinner77282cb2013-04-14 19:22:47 +020010985 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 PyMem_Free(buf2);
10987
Guido van Rossum403d68b2000-03-13 15:55:09 +000010988 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010989}
10990
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991/* Concat to string or Unicode object giving a new Unicode object. */
10992
Alexander Belopolsky40018472011-02-26 01:02:56 +000010993PyObject *
10994PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010997 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010998 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999
11000 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011003 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011006 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007
11008 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011009 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011010 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011011 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011013 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011014 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 }
11017
Victor Stinner488fa492011-12-12 00:01:39 +010011018 u_len = PyUnicode_GET_LENGTH(u);
11019 v_len = PyUnicode_GET_LENGTH(v);
11020 if (u_len > PY_SSIZE_T_MAX - v_len) {
11021 PyErr_SetString(PyExc_OverflowError,
11022 "strings are too large to concat");
11023 goto onError;
11024 }
11025 new_len = u_len + v_len;
11026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011027 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011028 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011029 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011030
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011032 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011034 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011035 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11036 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037 Py_DECREF(u);
11038 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011039 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011040 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043 Py_XDECREF(u);
11044 Py_XDECREF(v);
11045 return NULL;
11046}
11047
Walter Dörwald1ab83302007-05-18 17:15:44 +000011048void
Victor Stinner23e56682011-10-03 03:54:37 +020011049PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011050{
Victor Stinner23e56682011-10-03 03:54:37 +020011051 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011052 Py_UCS4 maxchar, maxchar2;
11053 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011054
11055 if (p_left == NULL) {
11056 if (!PyErr_Occurred())
11057 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011058 return;
11059 }
Victor Stinner23e56682011-10-03 03:54:37 +020011060 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011061 if (right == NULL || left == NULL
11062 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011063 if (!PyErr_Occurred())
11064 PyErr_BadInternalCall();
11065 goto error;
11066 }
11067
Benjamin Petersonbac79492012-01-14 13:34:47 -050011068 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011069 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011070 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011071 goto error;
11072
Victor Stinner488fa492011-12-12 00:01:39 +010011073 /* Shortcuts */
11074 if (left == unicode_empty) {
11075 Py_DECREF(left);
11076 Py_INCREF(right);
11077 *p_left = right;
11078 return;
11079 }
11080 if (right == unicode_empty)
11081 return;
11082
11083 left_len = PyUnicode_GET_LENGTH(left);
11084 right_len = PyUnicode_GET_LENGTH(right);
11085 if (left_len > PY_SSIZE_T_MAX - right_len) {
11086 PyErr_SetString(PyExc_OverflowError,
11087 "strings are too large to concat");
11088 goto error;
11089 }
11090 new_len = left_len + right_len;
11091
11092 if (unicode_modifiable(left)
11093 && PyUnicode_CheckExact(right)
11094 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011095 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11096 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011097 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011098 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011099 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11100 {
11101 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011102 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011103 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011104
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011105 /* copy 'right' into the newly allocated area of 'left' */
11106 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011107 }
Victor Stinner488fa492011-12-12 00:01:39 +010011108 else {
11109 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11110 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011111 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011112
Victor Stinner488fa492011-12-12 00:01:39 +010011113 /* Concat the two Unicode strings */
11114 res = PyUnicode_New(new_len, maxchar);
11115 if (res == NULL)
11116 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011117 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11118 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011119 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011120 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011121 }
11122 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011123 return;
11124
11125error:
Victor Stinner488fa492011-12-12 00:01:39 +010011126 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011127}
11128
11129void
11130PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011132 PyUnicode_Append(pleft, right);
11133 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011134}
11135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011136PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011137 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011139Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011140string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011141interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142
11143static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011144unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020011146 PyObject *substring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011147 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011148 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 int kind1, kind2, kind;
11151 void *buf1, *buf2;
11152 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153
Jesus Ceaac451502011-04-20 17:09:23 +020011154 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11155 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011156 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 kind1 = PyUnicode_KIND(self);
11159 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011160 if (kind2 > kind1) {
11161 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011162 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011163 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011164 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 buf1 = PyUnicode_DATA(self);
11166 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011168 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 if (!buf2) {
11170 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 return NULL;
11172 }
11173 len1 = PyUnicode_GET_LENGTH(self);
11174 len2 = PyUnicode_GET_LENGTH(substring);
11175
11176 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011177 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 case PyUnicode_1BYTE_KIND:
11179 iresult = ucs1lib_count(
11180 ((Py_UCS1*)buf1) + start, end - start,
11181 buf2, len2, PY_SSIZE_T_MAX
11182 );
11183 break;
11184 case PyUnicode_2BYTE_KIND:
11185 iresult = ucs2lib_count(
11186 ((Py_UCS2*)buf1) + start, end - start,
11187 buf2, len2, PY_SSIZE_T_MAX
11188 );
11189 break;
11190 case PyUnicode_4BYTE_KIND:
11191 iresult = ucs4lib_count(
11192 ((Py_UCS4*)buf1) + start, end - start,
11193 buf2, len2, PY_SSIZE_T_MAX
11194 );
11195 break;
11196 default:
11197 assert(0); iresult = 0;
11198 }
11199
11200 result = PyLong_FromSsize_t(iresult);
11201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 if (kind2 != kind)
11203 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011206
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 return result;
11208}
11209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011210PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011211 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011213Encode S using the codec registered for encoding. Default encoding\n\
11214is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011215handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011216a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11217'xmlcharrefreplace' as well as any other name registered with\n\
11218codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
11220static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011221unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011223 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 char *encoding = NULL;
11225 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011226
Benjamin Peterson308d6372009-09-18 21:42:35 +000011227 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11228 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011230 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011231}
11232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011233PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011234 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235\n\
11236Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011237If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238
11239static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011240unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011242 Py_ssize_t i, j, line_pos, src_len, incr;
11243 Py_UCS4 ch;
11244 PyObject *u;
11245 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011246 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011249 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250
Ezio Melotti745d54d2013-11-16 19:10:57 +020011251 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11252 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011253 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254
Antoine Pitrou22425222011-10-04 19:10:51 +020011255 if (PyUnicode_READY(self) == -1)
11256 return NULL;
11257
Thomas Wouters7e474022000-07-16 12:04:32 +000011258 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011259 src_len = PyUnicode_GET_LENGTH(self);
11260 i = j = line_pos = 0;
11261 kind = PyUnicode_KIND(self);
11262 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011263 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011264 for (; i < src_len; i++) {
11265 ch = PyUnicode_READ(kind, src_data, i);
11266 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011267 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011269 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011270 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011271 goto overflow;
11272 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011274 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 goto overflow;
11279 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011281 if (ch == '\n' || ch == '\r')
11282 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011284 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011285 if (!found)
11286 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011287
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011289 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290 if (!u)
11291 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011292 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293
Antoine Pitroue71d5742011-10-04 15:55:09 +020011294 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
Antoine Pitroue71d5742011-10-04 15:55:09 +020011296 for (; i < src_len; i++) {
11297 ch = PyUnicode_READ(kind, src_data, i);
11298 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011299 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011300 incr = tabsize - (line_pos % tabsize);
11301 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011302 FILL(kind, dest_data, ' ', j, incr);
11303 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011304 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011305 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011306 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011307 line_pos++;
11308 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011309 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011310 if (ch == '\n' || ch == '\r')
11311 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011313 }
11314 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011315 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011316
Antoine Pitroue71d5742011-10-04 15:55:09 +020011317 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011318 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11319 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320}
11321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011322PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011323 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324\n\
11325Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011326such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327arguments start and end are interpreted as in slice notation.\n\
11328\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011329Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
11331static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020011334 PyObject *substring = NULL;
11335 Py_ssize_t start = 0;
11336 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011337 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338
Jesus Ceaac451502011-04-20 17:09:23 +020011339 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11340 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
Christian Heimesd47802e2013-06-29 21:33:36 +020011343 if (PyUnicode_READY(self) == -1) {
11344 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011346 }
11347 if (PyUnicode_READY(substring) == -1) {
11348 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011350 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351
Victor Stinner7931d9a2011-11-04 00:22:48 +010011352 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
11354 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 if (result == -2)
11357 return NULL;
11358
Christian Heimes217cfd12007-12-02 14:31:20 +000011359 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360}
11361
11362static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011363unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011365 void *data;
11366 enum PyUnicode_Kind kind;
11367 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011368
11369 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11370 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011372 }
11373 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11374 PyErr_SetString(PyExc_IndexError, "string index out of range");
11375 return NULL;
11376 }
11377 kind = PyUnicode_KIND(self);
11378 data = PyUnicode_DATA(self);
11379 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011380 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381}
11382
Guido van Rossumc2504932007-09-18 19:42:40 +000011383/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011384 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011385static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011386unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387{
Guido van Rossumc2504932007-09-18 19:42:40 +000011388 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011389 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011390
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011391#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011392 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011393#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011394 if (_PyUnicode_HASH(self) != -1)
11395 return _PyUnicode_HASH(self);
11396 if (PyUnicode_READY(self) == -1)
11397 return -1;
11398 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011399 /*
11400 We make the hash of the empty string be 0, rather than using
11401 (prefix ^ suffix), since this slightly obfuscates the hash secret
11402 */
11403 if (len == 0) {
11404 _PyUnicode_HASH(self) = 0;
11405 return 0;
11406 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011407 x = _Py_HashBytes(PyUnicode_DATA(self),
11408 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011410 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
11418static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011419unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011421 Py_ssize_t result;
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020011422 PyObject *substring = NULL;
11423 Py_ssize_t start = 0;
11424 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Jesus Ceaac451502011-04-20 17:09:23 +020011426 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11427 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Christian Heimesd47a0452013-06-29 21:21:37 +020011430 if (PyUnicode_READY(self) == -1) {
11431 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011433 }
11434 if (PyUnicode_READY(substring) == -1) {
11435 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011437 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438
Victor Stinner7931d9a2011-11-04 00:22:48 +010011439 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
11441 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011443 if (result == -2)
11444 return NULL;
11445
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446 if (result < 0) {
11447 PyErr_SetString(PyExc_ValueError, "substring not found");
11448 return NULL;
11449 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011450
Christian Heimes217cfd12007-12-02 14:31:20 +000011451 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452}
11453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011454PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011457Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011458at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
11460static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011461unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 Py_ssize_t i, length;
11464 int kind;
11465 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 int cased;
11467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (PyUnicode_READY(self) == -1)
11469 return NULL;
11470 length = PyUnicode_GET_LENGTH(self);
11471 kind = PyUnicode_KIND(self);
11472 data = PyUnicode_DATA(self);
11473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 if (length == 1)
11476 return PyBool_FromLong(
11477 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011479 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011482
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 for (i = 0; i < length; i++) {
11485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011486
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11488 return PyBool_FromLong(0);
11489 else if (!cased && Py_UNICODE_ISLOWER(ch))
11490 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011492 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493}
11494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011495PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011498Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011499at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500
11501static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011502unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011504 Py_ssize_t i, length;
11505 int kind;
11506 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 int cased;
11508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 if (PyUnicode_READY(self) == -1)
11510 return NULL;
11511 length = PyUnicode_GET_LENGTH(self);
11512 kind = PyUnicode_KIND(self);
11513 data = PyUnicode_DATA(self);
11514
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 if (length == 1)
11517 return PyBool_FromLong(
11518 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011520 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011523
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 for (i = 0; i < length; i++) {
11526 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011527
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11529 return PyBool_FromLong(0);
11530 else if (!cased && Py_UNICODE_ISUPPER(ch))
11531 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011533 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534}
11535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011536PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011537 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011539Return True if S is a titlecased string and there is at least one\n\
11540character in S, i.e. upper- and titlecase characters may only\n\
11541follow uncased characters and lowercase characters only cased ones.\n\
11542Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543
11544static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011545unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 Py_ssize_t i, length;
11548 int kind;
11549 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550 int cased, previous_is_cased;
11551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 if (PyUnicode_READY(self) == -1)
11553 return NULL;
11554 length = PyUnicode_GET_LENGTH(self);
11555 kind = PyUnicode_KIND(self);
11556 data = PyUnicode_DATA(self);
11557
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 if (length == 1) {
11560 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11561 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11562 (Py_UNICODE_ISUPPER(ch) != 0));
11563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011565 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011567 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011568
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569 cased = 0;
11570 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 for (i = 0; i < length; i++) {
11572 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011573
Benjamin Peterson29060642009-01-31 22:14:21 +000011574 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11575 if (previous_is_cased)
11576 return PyBool_FromLong(0);
11577 previous_is_cased = 1;
11578 cased = 1;
11579 }
11580 else if (Py_UNICODE_ISLOWER(ch)) {
11581 if (!previous_is_cased)
11582 return PyBool_FromLong(0);
11583 previous_is_cased = 1;
11584 cased = 1;
11585 }
11586 else
11587 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011589 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590}
11591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011592PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011593 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011595Return True if all characters in S are whitespace\n\
11596and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
11598static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011599unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 Py_ssize_t i, length;
11602 int kind;
11603 void *data;
11604
11605 if (PyUnicode_READY(self) == -1)
11606 return NULL;
11607 length = PyUnicode_GET_LENGTH(self);
11608 kind = PyUnicode_KIND(self);
11609 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 if (length == 1)
11613 return PyBool_FromLong(
11614 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011616 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 for (i = 0; i < length; i++) {
11621 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011622 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011625 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626}
11627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011628PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011629 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011630\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011631Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011632and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011633
11634static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011635unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011636{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 Py_ssize_t i, length;
11638 int kind;
11639 void *data;
11640
11641 if (PyUnicode_READY(self) == -1)
11642 return NULL;
11643 length = PyUnicode_GET_LENGTH(self);
11644 kind = PyUnicode_KIND(self);
11645 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011646
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011647 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 if (length == 1)
11649 return PyBool_FromLong(
11650 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011651
11652 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 for (i = 0; i < length; i++) {
11657 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011659 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011660 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011661}
11662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011663PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011665\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011666Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011668
11669static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011670unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 int kind;
11673 void *data;
11674 Py_ssize_t len, i;
11675
11676 if (PyUnicode_READY(self) == -1)
11677 return NULL;
11678
11679 kind = PyUnicode_KIND(self);
11680 data = PyUnicode_DATA(self);
11681 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011682
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011683 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 if (len == 1) {
11685 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11686 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11687 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688
11689 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 for (i = 0; i < len; i++) {
11694 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011695 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011697 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011698 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011699}
11700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011701PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011704Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011705False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706
11707static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011708unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 Py_ssize_t i, length;
11711 int kind;
11712 void *data;
11713
11714 if (PyUnicode_READY(self) == -1)
11715 return NULL;
11716 length = PyUnicode_GET_LENGTH(self);
11717 kind = PyUnicode_KIND(self);
11718 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 if (length == 1)
11722 return PyBool_FromLong(
11723 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011725 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 for (i = 0; i < length; i++) {
11730 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011733 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734}
11735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011736PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011737 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011739Return True if all characters in S are digits\n\
11740and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741
11742static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011743unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 Py_ssize_t i, length;
11746 int kind;
11747 void *data;
11748
11749 if (PyUnicode_READY(self) == -1)
11750 return NULL;
11751 length = PyUnicode_GET_LENGTH(self);
11752 kind = PyUnicode_KIND(self);
11753 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 if (length == 1) {
11757 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11758 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11759 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011761 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 for (i = 0; i < length; i++) {
11766 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011767 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011769 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770}
11771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011772PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011775Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011776False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
11778static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011779unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 Py_ssize_t i, length;
11782 int kind;
11783 void *data;
11784
11785 if (PyUnicode_READY(self) == -1)
11786 return NULL;
11787 length = PyUnicode_GET_LENGTH(self);
11788 kind = PyUnicode_KIND(self);
11789 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011792 if (length == 1)
11793 return PyBool_FromLong(
11794 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011796 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011798 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 for (i = 0; i < length; i++) {
11801 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011802 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011804 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805}
11806
Martin v. Löwis47383402007-08-15 07:32:56 +000011807int
11808PyUnicode_IsIdentifier(PyObject *self)
11809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 int kind;
11811 void *data;
11812 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011813 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 if (PyUnicode_READY(self) == -1) {
11816 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 }
11819
11820 /* Special case for empty strings */
11821 if (PyUnicode_GET_LENGTH(self) == 0)
11822 return 0;
11823 kind = PyUnicode_KIND(self);
11824 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011825
11826 /* PEP 3131 says that the first character must be in
11827 XID_Start and subsequent characters in XID_Continue,
11828 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011829 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011830 letters, digits, underscore). However, given the current
11831 definition of XID_Start and XID_Continue, it is sufficient
11832 to check just for these, except that _ must be allowed
11833 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011835 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011836 return 0;
11837
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011838 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011840 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011841 return 1;
11842}
11843
11844PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011846\n\
11847Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011848to the language definition.\n\
11849\n\
11850Use keyword.iskeyword() to test for reserved identifiers\n\
11851such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011852
11853static PyObject*
11854unicode_isidentifier(PyObject *self)
11855{
11856 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11857}
11858
Georg Brandl559e5d72008-06-11 18:37:52 +000011859PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011861\n\
11862Return True if all characters in S are considered\n\
11863printable in repr() or S is empty, False otherwise.");
11864
11865static PyObject*
11866unicode_isprintable(PyObject *self)
11867{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011868 Py_ssize_t i, length;
11869 int kind;
11870 void *data;
11871
11872 if (PyUnicode_READY(self) == -1)
11873 return NULL;
11874 length = PyUnicode_GET_LENGTH(self);
11875 kind = PyUnicode_KIND(self);
11876 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011877
11878 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 if (length == 1)
11880 return PyBool_FromLong(
11881 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 for (i = 0; i < length; i++) {
11884 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011885 Py_RETURN_FALSE;
11886 }
11887 }
11888 Py_RETURN_TRUE;
11889}
11890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011891PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011892 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893\n\
11894Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011895iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896
11897static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011898unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011900 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901}
11902
Martin v. Löwis18e16552006-02-15 17:27:45 +000011903static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011904unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 if (PyUnicode_READY(self) == -1)
11907 return -1;
11908 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909}
11910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011911PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011912 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011914Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011915done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916
11917static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011918unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011920 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 Py_UCS4 fillchar = ' ';
11922
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011923 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 return NULL;
11925
Benjamin Petersonbac79492012-01-14 13:34:47 -050011926 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011927 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928
Victor Stinnerc4b49542011-12-11 22:44:26 +010011929 if (PyUnicode_GET_LENGTH(self) >= width)
11930 return unicode_result_unchanged(self);
11931
11932 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933}
11934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011935PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011936 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011938Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
11940static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011941unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011943 if (PyUnicode_READY(self) == -1)
11944 return NULL;
11945 if (PyUnicode_IS_ASCII(self))
11946 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011947 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948}
11949
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011950#define LEFTSTRIP 0
11951#define RIGHTSTRIP 1
11952#define BOTHSTRIP 2
11953
11954/* Arrays indexed by above */
11955static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11956
11957#define STRIPNAME(i) (stripformat[i]+3)
11958
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011959/* externally visible for str.strip(unicode) */
11960PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011961_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 void *data;
11964 int kind;
11965 Py_ssize_t i, j, len;
11966 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011967 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11970 return NULL;
11971
11972 kind = PyUnicode_KIND(self);
11973 data = PyUnicode_DATA(self);
11974 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011975 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11977 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011978 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011979
Benjamin Peterson14339b62009-01-31 16:36:08 +000011980 i = 0;
11981 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011982 while (i < len) {
11983 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11984 if (!BLOOM(sepmask, ch))
11985 break;
11986 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11987 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 i++;
11989 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011990 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011991
Benjamin Peterson14339b62009-01-31 16:36:08 +000011992 j = len;
11993 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011994 j--;
11995 while (j >= i) {
11996 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11997 if (!BLOOM(sepmask, ch))
11998 break;
11999 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12000 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012001 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012002 }
12003
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012005 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012006
Victor Stinner7931d9a2011-11-04 00:22:48 +010012007 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008}
12009
12010PyObject*
12011PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12012{
12013 unsigned char *data;
12014 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012015 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016
Victor Stinnerde636f32011-10-01 03:55:54 +020012017 if (PyUnicode_READY(self) == -1)
12018 return NULL;
12019
Victor Stinner684d5fd2012-05-03 02:32:34 +020012020 length = PyUnicode_GET_LENGTH(self);
12021 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012022
Victor Stinner684d5fd2012-05-03 02:32:34 +020012023 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012024 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025
Victor Stinnerde636f32011-10-01 03:55:54 +020012026 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012027 PyErr_SetString(PyExc_IndexError, "string index out of range");
12028 return NULL;
12029 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012030 if (start >= length || end < start)
12031 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012032
Victor Stinner684d5fd2012-05-03 02:32:34 +020012033 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012034 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012035 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012036 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012037 }
12038 else {
12039 kind = PyUnicode_KIND(self);
12040 data = PyUnicode_1BYTE_DATA(self);
12041 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012042 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012043 length);
12044 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046
12047static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012048do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 Py_ssize_t len, i, j;
12051
12052 if (PyUnicode_READY(self) == -1)
12053 return NULL;
12054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012056
Victor Stinnercc7af722013-04-09 22:39:24 +020012057 if (PyUnicode_IS_ASCII(self)) {
12058 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12059
12060 i = 0;
12061 if (striptype != RIGHTSTRIP) {
12062 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012063 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012064 if (!_Py_ascii_whitespace[ch])
12065 break;
12066 i++;
12067 }
12068 }
12069
12070 j = len;
12071 if (striptype != LEFTSTRIP) {
12072 j--;
12073 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012074 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012075 if (!_Py_ascii_whitespace[ch])
12076 break;
12077 j--;
12078 }
12079 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012080 }
12081 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012082 else {
12083 int kind = PyUnicode_KIND(self);
12084 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012085
Victor Stinnercc7af722013-04-09 22:39:24 +020012086 i = 0;
12087 if (striptype != RIGHTSTRIP) {
12088 while (i < len) {
12089 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12090 if (!Py_UNICODE_ISSPACE(ch))
12091 break;
12092 i++;
12093 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012094 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012095
12096 j = len;
12097 if (striptype != LEFTSTRIP) {
12098 j--;
12099 while (j >= i) {
12100 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12101 if (!Py_UNICODE_ISSPACE(ch))
12102 break;
12103 j--;
12104 }
12105 j++;
12106 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012107 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012108
Victor Stinner7931d9a2011-11-04 00:22:48 +010012109 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110}
12111
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012112
12113static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012114do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012115{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012116 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012117
Serhiy Storchakac6792272013-10-19 21:03:34 +030012118 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012119 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012120
Benjamin Peterson14339b62009-01-31 16:36:08 +000012121 if (sep != NULL && sep != Py_None) {
12122 if (PyUnicode_Check(sep))
12123 return _PyUnicode_XStrip(self, striptype, sep);
12124 else {
12125 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012126 "%s arg must be None or str",
12127 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012128 return NULL;
12129 }
12130 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131
Benjamin Peterson14339b62009-01-31 16:36:08 +000012132 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133}
12134
12135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012136PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012137 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012138\n\
12139Return a copy of the string S with leading and trailing\n\
12140whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012141If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012142
12143static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012144unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146 if (PyTuple_GET_SIZE(args) == 0)
12147 return do_strip(self, BOTHSTRIP); /* Common case */
12148 else
12149 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012150}
12151
12152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012153PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012155\n\
12156Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012157If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012158
12159static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012160unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012162 if (PyTuple_GET_SIZE(args) == 0)
12163 return do_strip(self, LEFTSTRIP); /* Common case */
12164 else
12165 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166}
12167
12168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012169PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012170 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012171\n\
12172Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012173If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012174
12175static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012176unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012177{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012178 if (PyTuple_GET_SIZE(args) == 0)
12179 return do_strip(self, RIGHTSTRIP); /* Common case */
12180 else
12181 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012182}
12183
12184
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012186unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012188 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190
Serhiy Storchaka05997252013-01-26 12:14:02 +020012191 if (len < 1)
12192 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193
Victor Stinnerc4b49542011-12-11 22:44:26 +010012194 /* no repeat, return original string */
12195 if (len == 1)
12196 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012197
Benjamin Petersonbac79492012-01-14 13:34:47 -050012198 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 return NULL;
12200
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012201 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012202 PyErr_SetString(PyExc_OverflowError,
12203 "repeated string is too long");
12204 return NULL;
12205 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012207
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012208 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209 if (!u)
12210 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012211 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 if (PyUnicode_GET_LENGTH(str) == 1) {
12214 const int kind = PyUnicode_KIND(str);
12215 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012216 if (kind == PyUnicode_1BYTE_KIND) {
12217 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012218 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012219 }
12220 else if (kind == PyUnicode_2BYTE_KIND) {
12221 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012222 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012223 ucs2[n] = fill_char;
12224 } else {
12225 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12226 assert(kind == PyUnicode_4BYTE_KIND);
12227 for (n = 0; n < len; ++n)
12228 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 }
12231 else {
12232 /* number of characters copied this far */
12233 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012234 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 char *to = (char *) PyUnicode_DATA(u);
12236 Py_MEMCPY(to, PyUnicode_DATA(str),
12237 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012238 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 n = (done <= nchars-done) ? done : nchars-done;
12240 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012241 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012242 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243 }
12244
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012245 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012246 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247}
12248
Alexander Belopolsky40018472011-02-26 01:02:56 +000012249PyObject *
12250PyUnicode_Replace(PyObject *obj,
12251 PyObject *subobj,
12252 PyObject *replobj,
12253 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254{
12255 PyObject *self;
12256 PyObject *str1;
12257 PyObject *str2;
12258 PyObject *result;
12259
12260 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012261 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012264 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 Py_DECREF(self);
12266 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267 }
12268 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012269 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012270 Py_DECREF(self);
12271 Py_DECREF(str1);
12272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012274 if (PyUnicode_READY(self) == -1 ||
12275 PyUnicode_READY(str1) == -1 ||
12276 PyUnicode_READY(str2) == -1)
12277 result = NULL;
12278 else
12279 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280 Py_DECREF(self);
12281 Py_DECREF(str1);
12282 Py_DECREF(str2);
12283 return result;
12284}
12285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012286PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012287 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288\n\
12289Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012290old replaced by new. If the optional argument count is\n\
12291given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292
12293static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 PyObject *str1;
12297 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012298 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012299 PyObject *result;
12300
Martin v. Löwis18e16552006-02-15 17:27:45 +000012301 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012303 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012304 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012306 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 return NULL;
12308 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012309 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012310 Py_DECREF(str1);
12311 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012312 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012313 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12314 result = NULL;
12315 else
12316 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317
12318 Py_DECREF(str1);
12319 Py_DECREF(str2);
12320 return result;
12321}
12322
Alexander Belopolsky40018472011-02-26 01:02:56 +000012323static PyObject *
12324unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012326 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 Py_ssize_t isize;
12328 Py_ssize_t osize, squote, dquote, i, o;
12329 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012330 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012334 return NULL;
12335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 isize = PyUnicode_GET_LENGTH(unicode);
12337 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 /* Compute length of output, quote characters, and
12340 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012341 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 max = 127;
12343 squote = dquote = 0;
12344 ikind = PyUnicode_KIND(unicode);
12345 for (i = 0; i < isize; i++) {
12346 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012347 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012349 case '\'': squote++; break;
12350 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012352 incr = 2;
12353 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354 default:
12355 /* Fast-path ASCII */
12356 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012357 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012359 ;
12360 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012363 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012365 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012367 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012369 if (osize > PY_SSIZE_T_MAX - incr) {
12370 PyErr_SetString(PyExc_OverflowError,
12371 "string is too long to generate repr");
12372 return NULL;
12373 }
12374 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 }
12376
12377 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012378 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012380 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381 if (dquote)
12382 /* Both squote and dquote present. Use squote,
12383 and escape them */
12384 osize += squote;
12385 else
12386 quote = '"';
12387 }
Victor Stinner55c08782013-04-14 18:45:39 +020012388 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012389
12390 repr = PyUnicode_New(osize, max);
12391 if (repr == NULL)
12392 return NULL;
12393 okind = PyUnicode_KIND(repr);
12394 odata = PyUnicode_DATA(repr);
12395
12396 PyUnicode_WRITE(okind, odata, 0, quote);
12397 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012398 if (unchanged) {
12399 _PyUnicode_FastCopyCharacters(repr, 1,
12400 unicode, 0,
12401 isize);
12402 }
12403 else {
12404 for (i = 0, o = 1; i < isize; i++) {
12405 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012406
Victor Stinner55c08782013-04-14 18:45:39 +020012407 /* Escape quotes and backslashes */
12408 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012409 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012411 continue;
12412 }
12413
12414 /* Map special whitespace to '\t', \n', '\r' */
12415 if (ch == '\t') {
12416 PyUnicode_WRITE(okind, odata, o++, '\\');
12417 PyUnicode_WRITE(okind, odata, o++, 't');
12418 }
12419 else if (ch == '\n') {
12420 PyUnicode_WRITE(okind, odata, o++, '\\');
12421 PyUnicode_WRITE(okind, odata, o++, 'n');
12422 }
12423 else if (ch == '\r') {
12424 PyUnicode_WRITE(okind, odata, o++, '\\');
12425 PyUnicode_WRITE(okind, odata, o++, 'r');
12426 }
12427
12428 /* Map non-printable US ASCII to '\xhh' */
12429 else if (ch < ' ' || ch == 0x7F) {
12430 PyUnicode_WRITE(okind, odata, o++, '\\');
12431 PyUnicode_WRITE(okind, odata, o++, 'x');
12432 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12433 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12434 }
12435
12436 /* Copy ASCII characters as-is */
12437 else if (ch < 0x7F) {
12438 PyUnicode_WRITE(okind, odata, o++, ch);
12439 }
12440
12441 /* Non-ASCII characters */
12442 else {
12443 /* Map Unicode whitespace and control characters
12444 (categories Z* and C* except ASCII space)
12445 */
12446 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12447 PyUnicode_WRITE(okind, odata, o++, '\\');
12448 /* Map 8-bit characters to '\xhh' */
12449 if (ch <= 0xff) {
12450 PyUnicode_WRITE(okind, odata, o++, 'x');
12451 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12452 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12453 }
12454 /* Map 16-bit characters to '\uxxxx' */
12455 else if (ch <= 0xffff) {
12456 PyUnicode_WRITE(okind, odata, o++, 'u');
12457 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12458 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12461 }
12462 /* Map 21-bit characters to '\U00xxxxxx' */
12463 else {
12464 PyUnicode_WRITE(okind, odata, o++, 'U');
12465 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12466 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12467 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12468 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12469 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12470 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12471 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12472 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12473 }
12474 }
12475 /* Copy characters as-is */
12476 else {
12477 PyUnicode_WRITE(okind, odata, o++, ch);
12478 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012479 }
12480 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012483 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012484 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485}
12486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012487PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012488 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489\n\
12490Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012491such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492arguments start and end are interpreted as in slice notation.\n\
12493\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012494Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
12496static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020012499 PyObject *substring = NULL;
12500 Py_ssize_t start = 0;
12501 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012502 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
Jesus Ceaac451502011-04-20 17:09:23 +020012504 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12505 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012506 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507
Christian Heimesea71a522013-06-29 21:17:34 +020012508 if (PyUnicode_READY(self) == -1) {
12509 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012510 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012511 }
12512 if (PyUnicode_READY(substring) == -1) {
12513 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012514 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012515 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012516
Victor Stinner7931d9a2011-11-04 00:22:48 +010012517 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518
12519 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 if (result == -2)
12522 return NULL;
12523
Christian Heimes217cfd12007-12-02 14:31:20 +000012524 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525}
12526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012527PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012530Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531
12532static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020012535 PyObject *substring = NULL;
12536 Py_ssize_t start = 0;
12537 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012538 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539
Jesus Ceaac451502011-04-20 17:09:23 +020012540 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12541 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543
Christian Heimesea71a522013-06-29 21:17:34 +020012544 if (PyUnicode_READY(self) == -1) {
12545 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012547 }
12548 if (PyUnicode_READY(substring) == -1) {
12549 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552
Victor Stinner7931d9a2011-11-04 00:22:48 +010012553 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554
12555 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 if (result == -2)
12558 return NULL;
12559
Guido van Rossumd57fd912000-03-10 22:53:23 +000012560 if (result < 0) {
12561 PyErr_SetString(PyExc_ValueError, "substring not found");
12562 return NULL;
12563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564
Christian Heimes217cfd12007-12-02 14:31:20 +000012565 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012566}
12567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012568PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012569 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012571Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012572done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573
12574static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012575unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012577 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 Py_UCS4 fillchar = ' ';
12579
Victor Stinnere9a29352011-10-01 02:14:59 +020012580 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012582
Benjamin Petersonbac79492012-01-14 13:34:47 -050012583 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584 return NULL;
12585
Victor Stinnerc4b49542011-12-11 22:44:26 +010012586 if (PyUnicode_GET_LENGTH(self) >= width)
12587 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588
Victor Stinnerc4b49542011-12-11 22:44:26 +010012589 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590}
12591
Alexander Belopolsky40018472011-02-26 01:02:56 +000012592PyObject *
12593PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594{
12595 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012596
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597 s = PyUnicode_FromObject(s);
12598 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012599 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012600 if (sep != NULL) {
12601 sep = PyUnicode_FromObject(sep);
12602 if (sep == NULL) {
12603 Py_DECREF(s);
12604 return NULL;
12605 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606 }
12607
Victor Stinner9310abb2011-10-05 00:59:23 +020012608 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609
12610 Py_DECREF(s);
12611 Py_XDECREF(sep);
12612 return result;
12613}
12614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012615PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012616 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617\n\
12618Return a list of the words in S, using sep as the\n\
12619delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012620splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012621whitespace string is a separator and empty strings are\n\
12622removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623
12624static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012625unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012627 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012629 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012631 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12632 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633 return NULL;
12634
12635 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012636 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012638 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012640 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641}
12642
Thomas Wouters477c8d52006-05-27 19:21:47 +000012643PyObject *
12644PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12645{
12646 PyObject* str_obj;
12647 PyObject* sep_obj;
12648 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 int kind1, kind2, kind;
12650 void *buf1 = NULL, *buf2 = NULL;
12651 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012652
12653 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012654 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012655 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012656 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012657 if (!sep_obj) {
12658 Py_DECREF(str_obj);
12659 return NULL;
12660 }
12661 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12662 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012663 Py_DECREF(str_obj);
12664 return NULL;
12665 }
12666
Victor Stinner14f8f022011-10-05 20:58:25 +020012667 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012669 kind = Py_MAX(kind1, kind2);
12670 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012671 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012672 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012673 if (!buf1)
12674 goto onError;
12675 buf2 = PyUnicode_DATA(sep_obj);
12676 if (kind2 != kind)
12677 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12678 if (!buf2)
12679 goto onError;
12680 len1 = PyUnicode_GET_LENGTH(str_obj);
12681 len2 = PyUnicode_GET_LENGTH(sep_obj);
12682
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012683 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012685 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12686 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12687 else
12688 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 break;
12690 case PyUnicode_2BYTE_KIND:
12691 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12692 break;
12693 case PyUnicode_4BYTE_KIND:
12694 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12695 break;
12696 default:
12697 assert(0);
12698 out = 0;
12699 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700
12701 Py_DECREF(sep_obj);
12702 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 if (kind1 != kind)
12704 PyMem_Free(buf1);
12705 if (kind2 != kind)
12706 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012707
12708 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709 onError:
12710 Py_DECREF(sep_obj);
12711 Py_DECREF(str_obj);
12712 if (kind1 != kind && buf1)
12713 PyMem_Free(buf1);
12714 if (kind2 != kind && buf2)
12715 PyMem_Free(buf2);
12716 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012717}
12718
12719
12720PyObject *
12721PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12722{
12723 PyObject* str_obj;
12724 PyObject* sep_obj;
12725 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 int kind1, kind2, kind;
12727 void *buf1 = NULL, *buf2 = NULL;
12728 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012729
12730 str_obj = PyUnicode_FromObject(str_in);
12731 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012732 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012733 sep_obj = PyUnicode_FromObject(sep_in);
12734 if (!sep_obj) {
12735 Py_DECREF(str_obj);
12736 return NULL;
12737 }
12738
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012739 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012741 kind = Py_MAX(kind1, kind2);
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012742 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 if (kind1 != kind)
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012744 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 if (!buf1)
12746 goto onError;
12747 buf2 = PyUnicode_DATA(sep_obj);
12748 if (kind2 != kind)
12749 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12750 if (!buf2)
12751 goto onError;
12752 len1 = PyUnicode_GET_LENGTH(str_obj);
12753 len2 = PyUnicode_GET_LENGTH(sep_obj);
12754
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012755 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012757 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12758 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12759 else
12760 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761 break;
12762 case PyUnicode_2BYTE_KIND:
12763 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12764 break;
12765 case PyUnicode_4BYTE_KIND:
12766 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12767 break;
12768 default:
12769 assert(0);
12770 out = 0;
12771 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012772
12773 Py_DECREF(sep_obj);
12774 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012775 if (kind1 != kind)
12776 PyMem_Free(buf1);
12777 if (kind2 != kind)
12778 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012779
12780 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 onError:
12782 Py_DECREF(sep_obj);
12783 Py_DECREF(str_obj);
12784 if (kind1 != kind && buf1)
12785 PyMem_Free(buf1);
12786 if (kind2 != kind && buf2)
12787 PyMem_Free(buf2);
12788 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012789}
12790
12791PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012792 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012793\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012794Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012795the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012796found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797
12798static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012799unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800{
Victor Stinner9310abb2011-10-05 00:59:23 +020012801 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802}
12803
12804PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012805 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012806\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012807Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012808the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012809separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012810
12811static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012812unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012813{
Victor Stinner9310abb2011-10-05 00:59:23 +020012814 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815}
12816
Alexander Belopolsky40018472011-02-26 01:02:56 +000012817PyObject *
12818PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012819{
12820 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012821
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012822 s = PyUnicode_FromObject(s);
12823 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012824 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012825 if (sep != NULL) {
12826 sep = PyUnicode_FromObject(sep);
12827 if (sep == NULL) {
12828 Py_DECREF(s);
12829 return NULL;
12830 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012831 }
12832
Victor Stinner9310abb2011-10-05 00:59:23 +020012833 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012834
12835 Py_DECREF(s);
12836 Py_XDECREF(sep);
12837 return result;
12838}
12839
12840PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012841 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012842\n\
12843Return a list of the words in S, using sep as the\n\
12844delimiter string, starting at the end of the string and\n\
12845working to the front. If maxsplit is given, at most maxsplit\n\
12846splits are done. If sep is not specified, any whitespace string\n\
12847is a separator.");
12848
12849static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012850unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012851{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012852 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012853 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012854 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012855
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012856 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12857 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012858 return NULL;
12859
12860 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012862 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012863 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012864 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012865 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012866}
12867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012868PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012869 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012870\n\
12871Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012872Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012873is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012874
12875static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012876unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012878 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012879 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012881 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12882 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883 return NULL;
12884
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012885 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886}
12887
12888static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012889PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012891 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892}
12893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012894PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012895 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896\n\
12897Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012898and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899
12900static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012901unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012902{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012903 if (PyUnicode_READY(self) == -1)
12904 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012905 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906}
12907
Larry Hastings61272b72014-01-07 12:41:53 -080012908/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012909
Larry Hastings31826802013-10-19 00:09:25 -070012910@staticmethod
12911str.maketrans as unicode_maketrans
12912
12913 x: object
12914
12915 y: unicode=NULL
12916
12917 z: unicode=NULL
12918
12919 /
12920
12921Return a translation table usable for str.translate().
12922
12923If there is only one argument, it must be a dictionary mapping Unicode
12924ordinals (integers) or characters to Unicode ordinals, strings or None.
12925Character keys will be then converted to ordinals.
12926If there are two arguments, they must be strings of equal length, and
12927in the resulting dictionary, each character in x will be mapped to the
12928character at the same position in y. If there is a third argument, it
12929must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012930[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012931
12932PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012933"maketrans(x, y=None, z=None, /)\n"
12934"--\n"
12935"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012936"Return a translation table usable for str.translate().\n"
12937"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012938"If there is only one argument, it must be a dictionary mapping Unicode\n"
12939"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12940"Character keys will be then converted to ordinals.\n"
12941"If there are two arguments, they must be strings of equal length, and\n"
12942"in the resulting dictionary, each character in x will be mapped to the\n"
12943"character at the same position in y. If there is a third argument, it\n"
12944"must be a string, whose characters will be mapped to None in the result.");
12945
12946#define UNICODE_MAKETRANS_METHODDEF \
12947 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12948
12949static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012950unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012951
12952static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012953unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012954{
Larry Hastings31826802013-10-19 00:09:25 -070012955 PyObject *return_value = NULL;
12956 PyObject *x;
12957 PyObject *y = NULL;
12958 PyObject *z = NULL;
12959
12960 if (!PyArg_ParseTuple(args,
12961 "O|UU:maketrans",
12962 &x, &y, &z))
12963 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012964 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012965
12966exit:
12967 return return_value;
12968}
12969
12970static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012971unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012972/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012973{
Georg Brandlceee0772007-11-27 23:48:05 +000012974 PyObject *new = NULL, *key, *value;
12975 Py_ssize_t i = 0;
12976 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012977
Georg Brandlceee0772007-11-27 23:48:05 +000012978 new = PyDict_New();
12979 if (!new)
12980 return NULL;
12981 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 int x_kind, y_kind, z_kind;
12983 void *x_data, *y_data, *z_data;
12984
Georg Brandlceee0772007-11-27 23:48:05 +000012985 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012986 if (!PyUnicode_Check(x)) {
12987 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12988 "be a string if there is a second argument");
12989 goto err;
12990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012992 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12993 "arguments must have equal length");
12994 goto err;
12995 }
12996 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 x_kind = PyUnicode_KIND(x);
12998 y_kind = PyUnicode_KIND(y);
12999 x_data = PyUnicode_DATA(x);
13000 y_data = PyUnicode_DATA(y);
13001 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13002 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013003 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013004 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013005 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013006 if (!value) {
13007 Py_DECREF(key);
13008 goto err;
13009 }
Georg Brandlceee0772007-11-27 23:48:05 +000013010 res = PyDict_SetItem(new, key, value);
13011 Py_DECREF(key);
13012 Py_DECREF(value);
13013 if (res < 0)
13014 goto err;
13015 }
13016 /* create entries for deleting chars in z */
13017 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013018 z_kind = PyUnicode_KIND(z);
13019 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013020 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013022 if (!key)
13023 goto err;
13024 res = PyDict_SetItem(new, key, Py_None);
13025 Py_DECREF(key);
13026 if (res < 0)
13027 goto err;
13028 }
13029 }
13030 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013031 int kind;
13032 void *data;
13033
Georg Brandlceee0772007-11-27 23:48:05 +000013034 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013035 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013036 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13037 "to maketrans it must be a dict");
13038 goto err;
13039 }
13040 /* copy entries into the new dict, converting string keys to int keys */
13041 while (PyDict_Next(x, &i, &key, &value)) {
13042 if (PyUnicode_Check(key)) {
13043 /* convert string keys to integer keys */
13044 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013045 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013046 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13047 "table must be of length 1");
13048 goto err;
13049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013050 kind = PyUnicode_KIND(key);
13051 data = PyUnicode_DATA(key);
13052 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013053 if (!newkey)
13054 goto err;
13055 res = PyDict_SetItem(new, newkey, value);
13056 Py_DECREF(newkey);
13057 if (res < 0)
13058 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013059 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013060 /* just keep integer keys */
13061 if (PyDict_SetItem(new, key, value) < 0)
13062 goto err;
13063 } else {
13064 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13065 "be strings or integers");
13066 goto err;
13067 }
13068 }
13069 }
13070 return new;
13071 err:
13072 Py_DECREF(new);
13073 return NULL;
13074}
13075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013076PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013077 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013079Return a copy of the string S in which each character has been mapped\n\
13080through the given translation table. The table must implement\n\
13081lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13082mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13083this operation raises LookupError, the character is left untouched.\n\
13084Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013085
13086static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013087unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013089 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090}
13091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013092PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013095Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096
13097static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013098unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013100 if (PyUnicode_READY(self) == -1)
13101 return NULL;
13102 if (PyUnicode_IS_ASCII(self))
13103 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013104 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105}
13106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013107PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013108 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013110Pad a numeric string S with zeros on the left, to fill a field\n\
13111of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112
13113static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013114unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013116 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013117 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013118 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 int kind;
13120 void *data;
13121 Py_UCS4 chr;
13122
Martin v. Löwis18e16552006-02-15 17:27:45 +000013123 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124 return NULL;
13125
Benjamin Petersonbac79492012-01-14 13:34:47 -050013126 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128
Victor Stinnerc4b49542011-12-11 22:44:26 +010013129 if (PyUnicode_GET_LENGTH(self) >= width)
13130 return unicode_result_unchanged(self);
13131
13132 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133
13134 u = pad(self, fill, 0, '0');
13135
Walter Dörwald068325e2002-04-15 13:36:47 +000013136 if (u == NULL)
13137 return NULL;
13138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013139 kind = PyUnicode_KIND(u);
13140 data = PyUnicode_DATA(u);
13141 chr = PyUnicode_READ(kind, data, fill);
13142
13143 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013144 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 PyUnicode_WRITE(kind, data, 0, chr);
13146 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147 }
13148
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013149 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013150 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152
13153#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013154static PyObject *
13155unicode__decimal2ascii(PyObject *self)
13156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013158}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013159#endif
13160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013161PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013162 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013164Return True if S starts with the specified prefix, False otherwise.\n\
13165With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013166With optional end, stop comparing S at that position.\n\
13167prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168
13169static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013170unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013171 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013173 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013174 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013175 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013176 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013177 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178
Jesus Ceaac451502011-04-20 17:09:23 +020013179 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013181 if (PyTuple_Check(subobj)) {
13182 Py_ssize_t i;
13183 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013184 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013185 if (substring == NULL)
13186 return NULL;
13187 result = tailmatch(self, substring, start, end, -1);
13188 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013189 if (result == -1)
13190 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 if (result) {
13192 Py_RETURN_TRUE;
13193 }
13194 }
13195 /* nothing matched */
13196 Py_RETURN_FALSE;
13197 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013199 if (substring == NULL) {
13200 if (PyErr_ExceptionMatches(PyExc_TypeError))
13201 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13202 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013203 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013204 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013205 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013207 if (result == -1)
13208 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013209 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210}
13211
13212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013213PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013216Return True if S ends with the specified suffix, False otherwise.\n\
13217With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013218With optional end, stop comparing S at that position.\n\
13219suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220
13221static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013222unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013225 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013226 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013227 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013228 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013229 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230
Jesus Ceaac451502011-04-20 17:09:23 +020013231 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013233 if (PyTuple_Check(subobj)) {
13234 Py_ssize_t i;
13235 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013236 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013238 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013240 result = tailmatch(self, substring, start, end, +1);
13241 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013242 if (result == -1)
13243 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013244 if (result) {
13245 Py_RETURN_TRUE;
13246 }
13247 }
13248 Py_RETURN_FALSE;
13249 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013250 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013251 if (substring == NULL) {
13252 if (PyErr_ExceptionMatches(PyExc_TypeError))
13253 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13254 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013256 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013257 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013258 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013259 if (result == -1)
13260 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013261 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262}
13263
Victor Stinner202fdca2012-05-07 12:47:02 +020013264Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013265_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013266{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013267 if (!writer->readonly)
13268 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13269 else {
13270 /* Copy-on-write mode: set buffer size to 0 so
13271 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13272 * next write. */
13273 writer->size = 0;
13274 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013275 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13276 writer->data = PyUnicode_DATA(writer->buffer);
13277 writer->kind = PyUnicode_KIND(writer->buffer);
13278}
13279
Victor Stinnerd3f08822012-05-29 12:57:52 +020013280void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013281_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013282{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013283 memset(writer, 0, sizeof(*writer));
13284#ifdef Py_DEBUG
13285 writer->kind = 5; /* invalid kind */
13286#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013287 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013288}
13289
Victor Stinnerd3f08822012-05-29 12:57:52 +020013290int
13291_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13292 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013293{
Victor Stinner6989ba02013-11-18 21:08:39 +010013294#ifdef MS_WINDOWS
13295 /* On Windows, overallocate by 50% is the best factor */
13296# define OVERALLOCATE_FACTOR 2
13297#else
13298 /* On Linux, overallocate by 25% is the best factor */
13299# define OVERALLOCATE_FACTOR 4
13300#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013301 Py_ssize_t newlen;
13302 PyObject *newbuffer;
13303
Victor Stinnerd3f08822012-05-29 12:57:52 +020013304 assert(length > 0);
13305
Victor Stinner202fdca2012-05-07 12:47:02 +020013306 if (length > PY_SSIZE_T_MAX - writer->pos) {
13307 PyErr_NoMemory();
13308 return -1;
13309 }
13310 newlen = writer->pos + length;
13311
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013312 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013313
Victor Stinnerd3f08822012-05-29 12:57:52 +020013314 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013315 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013316 if (writer->overallocate
13317 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13318 /* overallocate to limit the number of realloc() */
13319 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013320 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013321 if (newlen < writer->min_length)
13322 newlen = writer->min_length;
13323
Victor Stinnerd3f08822012-05-29 12:57:52 +020013324 writer->buffer = PyUnicode_New(newlen, maxchar);
13325 if (writer->buffer == NULL)
13326 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013328 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013329 if (writer->overallocate
13330 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13331 /* overallocate to limit the number of realloc() */
13332 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013333 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013334 if (newlen < writer->min_length)
13335 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013336
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013337 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013338 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013339 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013340 newbuffer = PyUnicode_New(newlen, maxchar);
13341 if (newbuffer == NULL)
13342 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013343 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13344 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013345 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013346 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013347 }
13348 else {
13349 newbuffer = resize_compact(writer->buffer, newlen);
13350 if (newbuffer == NULL)
13351 return -1;
13352 }
13353 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013354 }
13355 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013356 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013357 newbuffer = PyUnicode_New(writer->size, maxchar);
13358 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013359 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013360 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13361 writer->buffer, 0, writer->pos);
13362 Py_DECREF(writer->buffer);
13363 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013364 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013365 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013366 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013367
13368#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013369}
13370
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013371Py_LOCAL_INLINE(int)
13372_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013373{
13374 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13375 return -1;
13376 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13377 writer->pos++;
13378 return 0;
13379}
13380
13381int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013382_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13383{
13384 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13385}
13386
13387int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013388_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13389{
13390 Py_UCS4 maxchar;
13391 Py_ssize_t len;
13392
13393 if (PyUnicode_READY(str) == -1)
13394 return -1;
13395 len = PyUnicode_GET_LENGTH(str);
13396 if (len == 0)
13397 return 0;
13398 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13399 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013400 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013401 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013402 Py_INCREF(str);
13403 writer->buffer = str;
13404 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013405 writer->pos += len;
13406 return 0;
13407 }
13408 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13409 return -1;
13410 }
13411 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13412 str, 0, len);
13413 writer->pos += len;
13414 return 0;
13415}
13416
Victor Stinnere215d962012-10-06 23:03:36 +020013417int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013418_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13419 Py_ssize_t start, Py_ssize_t end)
13420{
13421 Py_UCS4 maxchar;
13422 Py_ssize_t len;
13423
13424 if (PyUnicode_READY(str) == -1)
13425 return -1;
13426
13427 assert(0 <= start);
13428 assert(end <= PyUnicode_GET_LENGTH(str));
13429 assert(start <= end);
13430
13431 if (end == 0)
13432 return 0;
13433
13434 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13435 return _PyUnicodeWriter_WriteStr(writer, str);
13436
13437 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13438 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13439 else
13440 maxchar = writer->maxchar;
13441 len = end - start;
13442
13443 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13444 return -1;
13445
13446 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13447 str, start, len);
13448 writer->pos += len;
13449 return 0;
13450}
13451
13452int
Victor Stinner4a587072013-11-19 12:54:53 +010013453_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13454 const char *ascii, Py_ssize_t len)
13455{
13456 if (len == -1)
13457 len = strlen(ascii);
13458
13459 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13460
13461 if (writer->buffer == NULL && !writer->overallocate) {
13462 PyObject *str;
13463
13464 str = _PyUnicode_FromASCII(ascii, len);
13465 if (str == NULL)
13466 return -1;
13467
13468 writer->readonly = 1;
13469 writer->buffer = str;
13470 _PyUnicodeWriter_Update(writer);
13471 writer->pos += len;
13472 return 0;
13473 }
13474
13475 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13476 return -1;
13477
13478 switch (writer->kind)
13479 {
13480 case PyUnicode_1BYTE_KIND:
13481 {
13482 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13483 Py_UCS1 *data = writer->data;
13484
13485 Py_MEMCPY(data + writer->pos, str, len);
13486 break;
13487 }
13488 case PyUnicode_2BYTE_KIND:
13489 {
13490 _PyUnicode_CONVERT_BYTES(
13491 Py_UCS1, Py_UCS2,
13492 ascii, ascii + len,
13493 (Py_UCS2 *)writer->data + writer->pos);
13494 break;
13495 }
13496 case PyUnicode_4BYTE_KIND:
13497 {
13498 _PyUnicode_CONVERT_BYTES(
13499 Py_UCS1, Py_UCS4,
13500 ascii, ascii + len,
13501 (Py_UCS4 *)writer->data + writer->pos);
13502 break;
13503 }
13504 default:
13505 assert(0);
13506 }
13507
13508 writer->pos += len;
13509 return 0;
13510}
13511
13512int
13513_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13514 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013515{
13516 Py_UCS4 maxchar;
13517
13518 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13519 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13520 return -1;
13521 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13522 writer->pos += len;
13523 return 0;
13524}
13525
Victor Stinnerd3f08822012-05-29 12:57:52 +020013526PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013527_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013528{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013529 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013530 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013531 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013532 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013534 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013535 str = writer->buffer;
13536 writer->buffer = NULL;
13537 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13538 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539 }
13540 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13541 PyObject *newbuffer;
13542 newbuffer = resize_compact(writer->buffer, writer->pos);
13543 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013544 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013545 return NULL;
13546 }
13547 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013548 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013549 str = writer->buffer;
13550 writer->buffer = NULL;
13551 assert(_PyUnicode_CheckConsistency(str, 1));
13552 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013553}
13554
Victor Stinnerd3f08822012-05-29 12:57:52 +020013555void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013556_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013557{
13558 Py_CLEAR(writer->buffer);
13559}
13560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013561#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013562
13563PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013565\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013566Return a formatted version of S, using substitutions from args and kwargs.\n\
13567The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013568
Eric Smith27bbca62010-11-04 17:06:58 +000013569PyDoc_STRVAR(format_map__doc__,
13570 "S.format_map(mapping) -> str\n\
13571\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013572Return a formatted version of S, using substitutions from mapping.\n\
13573The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013574
Eric Smith4a7d76d2008-05-30 18:10:19 +000013575static PyObject *
13576unicode__format__(PyObject* self, PyObject* args)
13577{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013578 PyObject *format_spec;
13579 _PyUnicodeWriter writer;
13580 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013581
13582 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13583 return NULL;
13584
Victor Stinnerd3f08822012-05-29 12:57:52 +020013585 if (PyUnicode_READY(self) == -1)
13586 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013587 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013588 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13589 self, format_spec, 0,
13590 PyUnicode_GET_LENGTH(format_spec));
13591 if (ret == -1) {
13592 _PyUnicodeWriter_Dealloc(&writer);
13593 return NULL;
13594 }
13595 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013596}
13597
Eric Smith8c663262007-08-25 02:26:07 +000013598PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013599 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013600\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013601Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013602
13603static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013604unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013605{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013606 Py_ssize_t size;
13607
13608 /* If it's a compact object, account for base structure +
13609 character data. */
13610 if (PyUnicode_IS_COMPACT_ASCII(v))
13611 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13612 else if (PyUnicode_IS_COMPACT(v))
13613 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013614 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 else {
13616 /* If it is a two-block object, account for base object, and
13617 for character block if present. */
13618 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013619 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013621 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013622 }
13623 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013624 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013625 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013627 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013628 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629
13630 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013631}
13632
13633PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013635
13636static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013637unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013638{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013639 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013640 if (!copy)
13641 return NULL;
13642 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013643}
13644
Guido van Rossumd57fd912000-03-10 22:53:23 +000013645static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013646 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013647 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013648 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13649 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013650 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13651 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013652 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013653 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13654 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13655 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013656 {"expandtabs", (PyCFunction) unicode_expandtabs,
13657 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013658 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013659 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013660 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13661 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13662 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013663 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013664 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13665 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13666 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013667 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013668 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013669 {"splitlines", (PyCFunction) unicode_splitlines,
13670 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013671 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013672 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13673 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13674 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13675 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13676 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13677 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13678 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13679 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13680 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13681 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13682 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13683 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13684 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13685 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013686 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013687 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013688 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013689 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013690 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013691 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013692 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013693 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013694#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013695 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013696 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013697#endif
13698
Benjamin Peterson14339b62009-01-31 16:36:08 +000013699 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013700 {NULL, NULL}
13701};
13702
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013703static PyObject *
13704unicode_mod(PyObject *v, PyObject *w)
13705{
Brian Curtindfc80e32011-08-10 20:28:54 -050013706 if (!PyUnicode_Check(v))
13707 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013708 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013709}
13710
13711static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013712 0, /*nb_add*/
13713 0, /*nb_subtract*/
13714 0, /*nb_multiply*/
13715 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013716};
13717
Guido van Rossumd57fd912000-03-10 22:53:23 +000013718static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013719 (lenfunc) unicode_length, /* sq_length */
13720 PyUnicode_Concat, /* sq_concat */
13721 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13722 (ssizeargfunc) unicode_getitem, /* sq_item */
13723 0, /* sq_slice */
13724 0, /* sq_ass_item */
13725 0, /* sq_ass_slice */
13726 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013727};
13728
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013729static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013730unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013732 if (PyUnicode_READY(self) == -1)
13733 return NULL;
13734
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013735 if (PyIndex_Check(item)) {
13736 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013737 if (i == -1 && PyErr_Occurred())
13738 return NULL;
13739 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013740 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013741 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013742 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013743 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013744 PyObject *result;
13745 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013746 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013747 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013748
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013749 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013750 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013751 return NULL;
13752 }
13753
13754 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013755 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013756 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013757 slicelength == PyUnicode_GET_LENGTH(self)) {
13758 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013759 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013760 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013761 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013762 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013763 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013764 src_kind = PyUnicode_KIND(self);
13765 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013766 if (!PyUnicode_IS_ASCII(self)) {
13767 kind_limit = kind_maxchar_limit(src_kind);
13768 max_char = 0;
13769 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13770 ch = PyUnicode_READ(src_kind, src_data, cur);
13771 if (ch > max_char) {
13772 max_char = ch;
13773 if (max_char >= kind_limit)
13774 break;
13775 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013776 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013777 }
Victor Stinner55c99112011-10-13 01:17:06 +020013778 else
13779 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013780 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013781 if (result == NULL)
13782 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013783 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013784 dest_data = PyUnicode_DATA(result);
13785
13786 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013787 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13788 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013789 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013790 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013791 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013792 } else {
13793 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13794 return NULL;
13795 }
13796}
13797
13798static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013799 (lenfunc)unicode_length, /* mp_length */
13800 (binaryfunc)unicode_subscript, /* mp_subscript */
13801 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013802};
13803
Guido van Rossumd57fd912000-03-10 22:53:23 +000013804
Guido van Rossumd57fd912000-03-10 22:53:23 +000013805/* Helpers for PyUnicode_Format() */
13806
Victor Stinnera47082312012-10-04 02:19:54 +020013807struct unicode_formatter_t {
13808 PyObject *args;
13809 int args_owned;
13810 Py_ssize_t arglen, argidx;
13811 PyObject *dict;
13812
13813 enum PyUnicode_Kind fmtkind;
13814 Py_ssize_t fmtcnt, fmtpos;
13815 void *fmtdata;
13816 PyObject *fmtstr;
13817
13818 _PyUnicodeWriter writer;
13819};
13820
13821struct unicode_format_arg_t {
13822 Py_UCS4 ch;
13823 int flags;
13824 Py_ssize_t width;
13825 int prec;
13826 int sign;
13827};
13828
Guido van Rossumd57fd912000-03-10 22:53:23 +000013829static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013830unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013831{
Victor Stinnera47082312012-10-04 02:19:54 +020013832 Py_ssize_t argidx = ctx->argidx;
13833
13834 if (argidx < ctx->arglen) {
13835 ctx->argidx++;
13836 if (ctx->arglen < 0)
13837 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013838 else
Victor Stinnera47082312012-10-04 02:19:54 +020013839 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013840 }
13841 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013842 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013843 return NULL;
13844}
13845
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013846/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013847
Victor Stinnera47082312012-10-04 02:19:54 +020013848/* Format a float into the writer if the writer is not NULL, or into *p_output
13849 otherwise.
13850
13851 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013852static int
Victor Stinnera47082312012-10-04 02:19:54 +020013853formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13854 PyObject **p_output,
13855 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013856{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013857 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013859 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013860 int prec;
13861 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013862
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863 x = PyFloat_AsDouble(v);
13864 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013865 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013866
Victor Stinnera47082312012-10-04 02:19:54 +020013867 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013870
Victor Stinnera47082312012-10-04 02:19:54 +020013871 if (arg->flags & F_ALT)
13872 dtoa_flags = Py_DTSF_ALT;
13873 else
13874 dtoa_flags = 0;
13875 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013876 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013877 return -1;
13878 len = strlen(p);
13879 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013880 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013881 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013882 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013883 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013884 }
13885 else
13886 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013887 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013888 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013889}
13890
Victor Stinnerd0880d52012-04-27 23:40:13 +020013891/* formatlong() emulates the format codes d, u, o, x and X, and
13892 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13893 * Python's regular ints.
13894 * Return value: a new PyUnicodeObject*, or NULL if error.
13895 * The output string is of the form
13896 * "-"? ("0x" | "0X")? digit+
13897 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13898 * set in flags. The case of hex digits will be correct,
13899 * There will be at least prec digits, zero-filled on the left if
13900 * necessary to get that many.
13901 * val object to be converted
13902 * flags bitmask of format flags; only F_ALT is looked at
13903 * prec minimum number of digits; 0-fill on left if needed
13904 * type a character in [duoxX]; u acts the same as d
13905 *
13906 * CAUTION: o, x and X conversions on regular ints can never
13907 * produce a '-' sign, but can for Python's unbounded ints.
13908 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013909static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013910formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013911{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013912 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013913 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013914 Py_ssize_t i;
13915 int sign; /* 1 if '-', else 0 */
13916 int len; /* number of characters */
13917 Py_ssize_t llen;
13918 int numdigits; /* len == numnondigits + numdigits */
13919 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013920 int prec = arg->prec;
13921 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013922
Victor Stinnerd0880d52012-04-27 23:40:13 +020013923 /* Avoid exceeding SSIZE_T_MAX */
13924 if (prec > INT_MAX-3) {
13925 PyErr_SetString(PyExc_OverflowError,
13926 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013927 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013928 }
13929
13930 assert(PyLong_Check(val));
13931
13932 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013933 default:
13934 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013935 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013936 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013937 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013938 /* int and int subclasses should print numerically when a numeric */
13939 /* format code is used (see issue18780) */
13940 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013941 break;
13942 case 'o':
13943 numnondigits = 2;
13944 result = PyNumber_ToBase(val, 8);
13945 break;
13946 case 'x':
13947 case 'X':
13948 numnondigits = 2;
13949 result = PyNumber_ToBase(val, 16);
13950 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013951 }
13952 if (!result)
13953 return NULL;
13954
13955 assert(unicode_modifiable(result));
13956 assert(PyUnicode_IS_READY(result));
13957 assert(PyUnicode_IS_ASCII(result));
13958
13959 /* To modify the string in-place, there can only be one reference. */
13960 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013961 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013962 PyErr_BadInternalCall();
13963 return NULL;
13964 }
13965 buf = PyUnicode_DATA(result);
13966 llen = PyUnicode_GET_LENGTH(result);
13967 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013968 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013969 PyErr_SetString(PyExc_ValueError,
13970 "string too large in _PyBytes_FormatLong");
13971 return NULL;
13972 }
13973 len = (int)llen;
13974 sign = buf[0] == '-';
13975 numnondigits += sign;
13976 numdigits = len - numnondigits;
13977 assert(numdigits > 0);
13978
13979 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013980 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013981 (type == 'o' || type == 'x' || type == 'X'))) {
13982 assert(buf[sign] == '0');
13983 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13984 buf[sign+1] == 'o');
13985 numnondigits -= 2;
13986 buf += 2;
13987 len -= 2;
13988 if (sign)
13989 buf[0] = '-';
13990 assert(len == numnondigits + numdigits);
13991 assert(numdigits > 0);
13992 }
13993
13994 /* Fill with leading zeroes to meet minimum width. */
13995 if (prec > numdigits) {
13996 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13997 numnondigits + prec);
13998 char *b1;
13999 if (!r1) {
14000 Py_DECREF(result);
14001 return NULL;
14002 }
14003 b1 = PyBytes_AS_STRING(r1);
14004 for (i = 0; i < numnondigits; ++i)
14005 *b1++ = *buf++;
14006 for (i = 0; i < prec - numdigits; i++)
14007 *b1++ = '0';
14008 for (i = 0; i < numdigits; i++)
14009 *b1++ = *buf++;
14010 *b1 = '\0';
14011 Py_DECREF(result);
14012 result = r1;
14013 buf = PyBytes_AS_STRING(result);
14014 len = numnondigits + prec;
14015 }
14016
14017 /* Fix up case for hex conversions. */
14018 if (type == 'X') {
14019 /* Need to convert all lower case letters to upper case.
14020 and need to convert 0x to 0X (and -0x to -0X). */
14021 for (i = 0; i < len; i++)
14022 if (buf[i] >= 'a' && buf[i] <= 'x')
14023 buf[i] -= 'a'-'A';
14024 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014025 if (!PyUnicode_Check(result)
14026 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014027 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014028 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014029 Py_DECREF(result);
14030 result = unicode;
14031 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014032 else if (len != PyUnicode_GET_LENGTH(result)) {
14033 if (PyUnicode_Resize(&result, len) < 0)
14034 Py_CLEAR(result);
14035 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014036 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014037}
14038
Ethan Furmandf3ed242014-01-05 06:50:30 -080014039/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014040 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014041 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014042 * -1 and raise an exception on error */
14043static int
Victor Stinnera47082312012-10-04 02:19:54 +020014044mainformatlong(PyObject *v,
14045 struct unicode_format_arg_t *arg,
14046 PyObject **p_output,
14047 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014048{
14049 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014050 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014051
14052 if (!PyNumber_Check(v))
14053 goto wrongtype;
14054
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014055 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014056 /* if not, issue deprecation warning for now */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014057 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014058 if (type == 'o' || type == 'x' || type == 'X') {
14059 iobj = PyNumber_Index(v);
14060 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014061 PyErr_Clear();
14062 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14063 "automatic int conversions have been deprecated",
14064 1)) {
14065 return -1;
14066 }
14067 iobj = PyNumber_Long(v);
14068 if (iobj == NULL ) {
14069 if (PyErr_ExceptionMatches(PyExc_TypeError))
14070 goto wrongtype;
14071 return -1;
14072 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014073 }
14074 }
14075 else {
14076 iobj = PyNumber_Long(v);
14077 if (iobj == NULL ) {
14078 if (PyErr_ExceptionMatches(PyExc_TypeError))
14079 goto wrongtype;
14080 return -1;
14081 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014082 }
14083 assert(PyLong_Check(iobj));
14084 }
14085 else {
14086 iobj = v;
14087 Py_INCREF(iobj);
14088 }
14089
14090 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014091 && arg->width == -1 && arg->prec == -1
14092 && !(arg->flags & (F_SIGN | F_BLANK))
14093 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014094 {
14095 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014096 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014097 int base;
14098
Victor Stinnera47082312012-10-04 02:19:54 +020014099 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014100 {
14101 default:
14102 assert(0 && "'type' not in [diuoxX]");
14103 case 'd':
14104 case 'i':
14105 case 'u':
14106 base = 10;
14107 break;
14108 case 'o':
14109 base = 8;
14110 break;
14111 case 'x':
14112 case 'X':
14113 base = 16;
14114 break;
14115 }
14116
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014117 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14118 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014119 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014120 }
14121 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014122 return 1;
14123 }
14124
Victor Stinnera47082312012-10-04 02:19:54 +020014125 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014126 Py_DECREF(iobj);
14127 if (res == NULL)
14128 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014129 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014130 return 0;
14131
14132wrongtype:
14133 PyErr_Format(PyExc_TypeError,
14134 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014135 "not %.200s",
14136 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014137 return -1;
14138}
14139
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014140static Py_UCS4
14141formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014142{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014143 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014144 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014145 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014146 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014147 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014148 goto onError;
14149 }
14150 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014151 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014152 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014153 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014154 /* if not, issue deprecation warning for now */
Ethan Furmandf3ed242014-01-05 06:50:30 -080014155 if (!PyLong_Check(v)) {
14156 iobj = PyNumber_Index(v);
14157 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014158 PyErr_Clear();
14159 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14160 "automatic int conversions have been deprecated",
14161 1)) {
14162 return -1;
14163 }
14164 iobj = PyNumber_Long(v);
14165 if (iobj == NULL ) {
14166 if (PyErr_ExceptionMatches(PyExc_TypeError))
14167 goto onError;
14168 return -1;
14169 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014170 }
14171 v = iobj;
14172 Py_DECREF(iobj);
14173 }
14174 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014175 x = PyLong_AsLong(v);
14176 if (x == -1 && PyErr_Occurred())
14177 goto onError;
14178
Victor Stinner8faf8212011-12-08 22:14:11 +010014179 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014180 PyErr_SetString(PyExc_OverflowError,
14181 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014182 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014183 }
14184
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014185 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014187
Benjamin Peterson29060642009-01-31 22:14:21 +000014188 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014189 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014190 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014191 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014192}
14193
Victor Stinnera47082312012-10-04 02:19:54 +020014194/* Parse options of an argument: flags, width, precision.
14195 Handle also "%(name)" syntax.
14196
14197 Return 0 if the argument has been formatted into arg->str.
14198 Return 1 if the argument has been written into ctx->writer,
14199 Raise an exception and return -1 on error. */
14200static int
14201unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14202 struct unicode_format_arg_t *arg)
14203{
14204#define FORMAT_READ(ctx) \
14205 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14206
14207 PyObject *v;
14208
Victor Stinnera47082312012-10-04 02:19:54 +020014209 if (arg->ch == '(') {
14210 /* Get argument value from a dictionary. Example: "%(name)s". */
14211 Py_ssize_t keystart;
14212 Py_ssize_t keylen;
14213 PyObject *key;
14214 int pcount = 1;
14215
14216 if (ctx->dict == NULL) {
14217 PyErr_SetString(PyExc_TypeError,
14218 "format requires a mapping");
14219 return -1;
14220 }
14221 ++ctx->fmtpos;
14222 --ctx->fmtcnt;
14223 keystart = ctx->fmtpos;
14224 /* Skip over balanced parentheses */
14225 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14226 arg->ch = FORMAT_READ(ctx);
14227 if (arg->ch == ')')
14228 --pcount;
14229 else if (arg->ch == '(')
14230 ++pcount;
14231 ctx->fmtpos++;
14232 }
14233 keylen = ctx->fmtpos - keystart - 1;
14234 if (ctx->fmtcnt < 0 || pcount > 0) {
14235 PyErr_SetString(PyExc_ValueError,
14236 "incomplete format key");
14237 return -1;
14238 }
14239 key = PyUnicode_Substring(ctx->fmtstr,
14240 keystart, keystart + keylen);
14241 if (key == NULL)
14242 return -1;
14243 if (ctx->args_owned) {
14244 Py_DECREF(ctx->args);
14245 ctx->args_owned = 0;
14246 }
14247 ctx->args = PyObject_GetItem(ctx->dict, key);
14248 Py_DECREF(key);
14249 if (ctx->args == NULL)
14250 return -1;
14251 ctx->args_owned = 1;
14252 ctx->arglen = -1;
14253 ctx->argidx = -2;
14254 }
14255
14256 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014257 while (--ctx->fmtcnt >= 0) {
14258 arg->ch = FORMAT_READ(ctx);
14259 ctx->fmtpos++;
14260 switch (arg->ch) {
14261 case '-': arg->flags |= F_LJUST; continue;
14262 case '+': arg->flags |= F_SIGN; continue;
14263 case ' ': arg->flags |= F_BLANK; continue;
14264 case '#': arg->flags |= F_ALT; continue;
14265 case '0': arg->flags |= F_ZERO; continue;
14266 }
14267 break;
14268 }
14269
14270 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014271 if (arg->ch == '*') {
14272 v = unicode_format_getnextarg(ctx);
14273 if (v == NULL)
14274 return -1;
14275 if (!PyLong_Check(v)) {
14276 PyErr_SetString(PyExc_TypeError,
14277 "* wants int");
14278 return -1;
14279 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014280 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014281 if (arg->width == -1 && PyErr_Occurred())
14282 return -1;
14283 if (arg->width < 0) {
14284 arg->flags |= F_LJUST;
14285 arg->width = -arg->width;
14286 }
14287 if (--ctx->fmtcnt >= 0) {
14288 arg->ch = FORMAT_READ(ctx);
14289 ctx->fmtpos++;
14290 }
14291 }
14292 else if (arg->ch >= '0' && arg->ch <= '9') {
14293 arg->width = arg->ch - '0';
14294 while (--ctx->fmtcnt >= 0) {
14295 arg->ch = FORMAT_READ(ctx);
14296 ctx->fmtpos++;
14297 if (arg->ch < '0' || arg->ch > '9')
14298 break;
14299 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14300 mixing signed and unsigned comparison. Since arg->ch is between
14301 '0' and '9', casting to int is safe. */
14302 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14303 PyErr_SetString(PyExc_ValueError,
14304 "width too big");
14305 return -1;
14306 }
14307 arg->width = arg->width*10 + (arg->ch - '0');
14308 }
14309 }
14310
14311 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014312 if (arg->ch == '.') {
14313 arg->prec = 0;
14314 if (--ctx->fmtcnt >= 0) {
14315 arg->ch = FORMAT_READ(ctx);
14316 ctx->fmtpos++;
14317 }
14318 if (arg->ch == '*') {
14319 v = unicode_format_getnextarg(ctx);
14320 if (v == NULL)
14321 return -1;
14322 if (!PyLong_Check(v)) {
14323 PyErr_SetString(PyExc_TypeError,
14324 "* wants int");
14325 return -1;
14326 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014327 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014328 if (arg->prec == -1 && PyErr_Occurred())
14329 return -1;
14330 if (arg->prec < 0)
14331 arg->prec = 0;
14332 if (--ctx->fmtcnt >= 0) {
14333 arg->ch = FORMAT_READ(ctx);
14334 ctx->fmtpos++;
14335 }
14336 }
14337 else if (arg->ch >= '0' && arg->ch <= '9') {
14338 arg->prec = arg->ch - '0';
14339 while (--ctx->fmtcnt >= 0) {
14340 arg->ch = FORMAT_READ(ctx);
14341 ctx->fmtpos++;
14342 if (arg->ch < '0' || arg->ch > '9')
14343 break;
14344 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14345 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014346 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014347 return -1;
14348 }
14349 arg->prec = arg->prec*10 + (arg->ch - '0');
14350 }
14351 }
14352 }
14353
14354 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14355 if (ctx->fmtcnt >= 0) {
14356 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14357 if (--ctx->fmtcnt >= 0) {
14358 arg->ch = FORMAT_READ(ctx);
14359 ctx->fmtpos++;
14360 }
14361 }
14362 }
14363 if (ctx->fmtcnt < 0) {
14364 PyErr_SetString(PyExc_ValueError,
14365 "incomplete format");
14366 return -1;
14367 }
14368 return 0;
14369
14370#undef FORMAT_READ
14371}
14372
14373/* Format one argument. Supported conversion specifiers:
14374
14375 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014376 - "i", "d", "u": int or float
14377 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014378 - "e", "E", "f", "F", "g", "G": float
14379 - "c": int or str (1 character)
14380
Victor Stinner8dbd4212012-12-04 09:30:24 +010014381 When possible, the output is written directly into the Unicode writer
14382 (ctx->writer). A string is created when padding is required.
14383
Victor Stinnera47082312012-10-04 02:19:54 +020014384 Return 0 if the argument has been formatted into *p_str,
14385 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014386 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014387static int
14388unicode_format_arg_format(struct unicode_formatter_t *ctx,
14389 struct unicode_format_arg_t *arg,
14390 PyObject **p_str)
14391{
14392 PyObject *v;
14393 _PyUnicodeWriter *writer = &ctx->writer;
14394
14395 if (ctx->fmtcnt == 0)
14396 ctx->writer.overallocate = 0;
14397
14398 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014399 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014400 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014401 return 1;
14402 }
14403
14404 v = unicode_format_getnextarg(ctx);
14405 if (v == NULL)
14406 return -1;
14407
Victor Stinnera47082312012-10-04 02:19:54 +020014408
14409 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014410 case 's':
14411 case 'r':
14412 case 'a':
14413 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14414 /* Fast path */
14415 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14416 return -1;
14417 return 1;
14418 }
14419
14420 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14421 *p_str = v;
14422 Py_INCREF(*p_str);
14423 }
14424 else {
14425 if (arg->ch == 's')
14426 *p_str = PyObject_Str(v);
14427 else if (arg->ch == 'r')
14428 *p_str = PyObject_Repr(v);
14429 else
14430 *p_str = PyObject_ASCII(v);
14431 }
14432 break;
14433
14434 case 'i':
14435 case 'd':
14436 case 'u':
14437 case 'o':
14438 case 'x':
14439 case 'X':
14440 {
14441 int ret = mainformatlong(v, arg, p_str, writer);
14442 if (ret != 0)
14443 return ret;
14444 arg->sign = 1;
14445 break;
14446 }
14447
14448 case 'e':
14449 case 'E':
14450 case 'f':
14451 case 'F':
14452 case 'g':
14453 case 'G':
14454 if (arg->width == -1 && arg->prec == -1
14455 && !(arg->flags & (F_SIGN | F_BLANK)))
14456 {
14457 /* Fast path */
14458 if (formatfloat(v, arg, NULL, writer) == -1)
14459 return -1;
14460 return 1;
14461 }
14462
14463 arg->sign = 1;
14464 if (formatfloat(v, arg, p_str, NULL) == -1)
14465 return -1;
14466 break;
14467
14468 case 'c':
14469 {
14470 Py_UCS4 ch = formatchar(v);
14471 if (ch == (Py_UCS4) -1)
14472 return -1;
14473 if (arg->width == -1 && arg->prec == -1) {
14474 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014475 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014476 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014477 return 1;
14478 }
14479 *p_str = PyUnicode_FromOrdinal(ch);
14480 break;
14481 }
14482
14483 default:
14484 PyErr_Format(PyExc_ValueError,
14485 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014486 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014487 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14488 (int)arg->ch,
14489 ctx->fmtpos - 1);
14490 return -1;
14491 }
14492 if (*p_str == NULL)
14493 return -1;
14494 assert (PyUnicode_Check(*p_str));
14495 return 0;
14496}
14497
14498static int
14499unicode_format_arg_output(struct unicode_formatter_t *ctx,
14500 struct unicode_format_arg_t *arg,
14501 PyObject *str)
14502{
14503 Py_ssize_t len;
14504 enum PyUnicode_Kind kind;
14505 void *pbuf;
14506 Py_ssize_t pindex;
14507 Py_UCS4 signchar;
14508 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014509 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014510 Py_ssize_t sublen;
14511 _PyUnicodeWriter *writer = &ctx->writer;
14512 Py_UCS4 fill;
14513
14514 fill = ' ';
14515 if (arg->sign && arg->flags & F_ZERO)
14516 fill = '0';
14517
14518 if (PyUnicode_READY(str) == -1)
14519 return -1;
14520
14521 len = PyUnicode_GET_LENGTH(str);
14522 if ((arg->width == -1 || arg->width <= len)
14523 && (arg->prec == -1 || arg->prec >= len)
14524 && !(arg->flags & (F_SIGN | F_BLANK)))
14525 {
14526 /* Fast path */
14527 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14528 return -1;
14529 return 0;
14530 }
14531
14532 /* Truncate the string for "s", "r" and "a" formats
14533 if the precision is set */
14534 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14535 if (arg->prec >= 0 && len > arg->prec)
14536 len = arg->prec;
14537 }
14538
14539 /* Adjust sign and width */
14540 kind = PyUnicode_KIND(str);
14541 pbuf = PyUnicode_DATA(str);
14542 pindex = 0;
14543 signchar = '\0';
14544 if (arg->sign) {
14545 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14546 if (ch == '-' || ch == '+') {
14547 signchar = ch;
14548 len--;
14549 pindex++;
14550 }
14551 else if (arg->flags & F_SIGN)
14552 signchar = '+';
14553 else if (arg->flags & F_BLANK)
14554 signchar = ' ';
14555 else
14556 arg->sign = 0;
14557 }
14558 if (arg->width < len)
14559 arg->width = len;
14560
14561 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014562 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014563 if (!(arg->flags & F_LJUST)) {
14564 if (arg->sign) {
14565 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014566 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014567 }
14568 else {
14569 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014570 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014571 }
14572 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014573 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14574 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014575 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014576 }
14577
Victor Stinnera47082312012-10-04 02:19:54 +020014578 buflen = arg->width;
14579 if (arg->sign && len == arg->width)
14580 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014581 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014582 return -1;
14583
14584 /* Write the sign if needed */
14585 if (arg->sign) {
14586 if (fill != ' ') {
14587 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14588 writer->pos += 1;
14589 }
14590 if (arg->width > len)
14591 arg->width--;
14592 }
14593
14594 /* Write the numeric prefix for "x", "X" and "o" formats
14595 if the alternate form is used.
14596 For example, write "0x" for the "%#x" format. */
14597 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14598 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14599 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14600 if (fill != ' ') {
14601 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14602 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14603 writer->pos += 2;
14604 pindex += 2;
14605 }
14606 arg->width -= 2;
14607 if (arg->width < 0)
14608 arg->width = 0;
14609 len -= 2;
14610 }
14611
14612 /* Pad left with the fill character if needed */
14613 if (arg->width > len && !(arg->flags & F_LJUST)) {
14614 sublen = arg->width - len;
14615 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14616 writer->pos += sublen;
14617 arg->width = len;
14618 }
14619
14620 /* If padding with spaces: write sign if needed and/or numeric prefix if
14621 the alternate form is used */
14622 if (fill == ' ') {
14623 if (arg->sign) {
14624 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14625 writer->pos += 1;
14626 }
14627 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14628 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14629 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14630 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14631 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14632 writer->pos += 2;
14633 pindex += 2;
14634 }
14635 }
14636
14637 /* Write characters */
14638 if (len) {
14639 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14640 str, pindex, len);
14641 writer->pos += len;
14642 }
14643
14644 /* Pad right with the fill character if needed */
14645 if (arg->width > len) {
14646 sublen = arg->width - len;
14647 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14648 writer->pos += sublen;
14649 }
14650 return 0;
14651}
14652
14653/* Helper of PyUnicode_Format(): format one arg.
14654 Return 0 on success, raise an exception and return -1 on error. */
14655static int
14656unicode_format_arg(struct unicode_formatter_t *ctx)
14657{
14658 struct unicode_format_arg_t arg;
14659 PyObject *str;
14660 int ret;
14661
Victor Stinner8dbd4212012-12-04 09:30:24 +010014662 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14663 arg.flags = 0;
14664 arg.width = -1;
14665 arg.prec = -1;
14666 arg.sign = 0;
14667 str = NULL;
14668
Victor Stinnera47082312012-10-04 02:19:54 +020014669 ret = unicode_format_arg_parse(ctx, &arg);
14670 if (ret == -1)
14671 return -1;
14672
14673 ret = unicode_format_arg_format(ctx, &arg, &str);
14674 if (ret == -1)
14675 return -1;
14676
14677 if (ret != 1) {
14678 ret = unicode_format_arg_output(ctx, &arg, str);
14679 Py_DECREF(str);
14680 if (ret == -1)
14681 return -1;
14682 }
14683
14684 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14685 PyErr_SetString(PyExc_TypeError,
14686 "not all arguments converted during string formatting");
14687 return -1;
14688 }
14689 return 0;
14690}
14691
Alexander Belopolsky40018472011-02-26 01:02:56 +000014692PyObject *
14693PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014694{
Victor Stinnera47082312012-10-04 02:19:54 +020014695 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014696
Guido van Rossumd57fd912000-03-10 22:53:23 +000014697 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014698 PyErr_BadInternalCall();
14699 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014700 }
Victor Stinnera47082312012-10-04 02:19:54 +020014701
14702 ctx.fmtstr = PyUnicode_FromObject(format);
14703 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014704 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014705 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14706 Py_DECREF(ctx.fmtstr);
14707 return NULL;
14708 }
14709 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14710 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14711 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14712 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014713
Victor Stinner8f674cc2013-04-17 23:02:17 +020014714 _PyUnicodeWriter_Init(&ctx.writer);
14715 ctx.writer.min_length = ctx.fmtcnt + 100;
14716 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014717
Guido van Rossumd57fd912000-03-10 22:53:23 +000014718 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014719 ctx.arglen = PyTuple_Size(args);
14720 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014721 }
14722 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014723 ctx.arglen = -1;
14724 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014725 }
Victor Stinnera47082312012-10-04 02:19:54 +020014726 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014727 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014728 ctx.dict = args;
14729 else
14730 ctx.dict = NULL;
14731 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014732
Victor Stinnera47082312012-10-04 02:19:54 +020014733 while (--ctx.fmtcnt >= 0) {
14734 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014735 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014736
14737 nonfmtpos = ctx.fmtpos++;
14738 while (ctx.fmtcnt >= 0 &&
14739 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14740 ctx.fmtpos++;
14741 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014742 }
Victor Stinnera47082312012-10-04 02:19:54 +020014743 if (ctx.fmtcnt < 0) {
14744 ctx.fmtpos--;
14745 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014746 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014747
Victor Stinnercfc4c132013-04-03 01:48:39 +020014748 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14749 nonfmtpos, ctx.fmtpos) < 0)
14750 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014751 }
14752 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014753 ctx.fmtpos++;
14754 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014755 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014756 }
14757 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014758
Victor Stinnera47082312012-10-04 02:19:54 +020014759 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014760 PyErr_SetString(PyExc_TypeError,
14761 "not all arguments converted during string formatting");
14762 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014763 }
14764
Victor Stinnera47082312012-10-04 02:19:54 +020014765 if (ctx.args_owned) {
14766 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014767 }
Victor Stinnera47082312012-10-04 02:19:54 +020014768 Py_DECREF(ctx.fmtstr);
14769 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014770
Benjamin Peterson29060642009-01-31 22:14:21 +000014771 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014772 Py_DECREF(ctx.fmtstr);
14773 _PyUnicodeWriter_Dealloc(&ctx.writer);
14774 if (ctx.args_owned) {
14775 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014776 }
14777 return NULL;
14778}
14779
Jeremy Hylton938ace62002-07-17 16:30:39 +000014780static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014781unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14782
Tim Peters6d6c1a32001-08-02 04:15:00 +000014783static PyObject *
14784unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14785{
Benjamin Peterson29060642009-01-31 22:14:21 +000014786 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014787 static char *kwlist[] = {"object", "encoding", "errors", 0};
14788 char *encoding = NULL;
14789 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014790
Benjamin Peterson14339b62009-01-31 16:36:08 +000014791 if (type != &PyUnicode_Type)
14792 return unicode_subtype_new(type, args, kwds);
14793 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014794 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014795 return NULL;
14796 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014797 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014798 if (encoding == NULL && errors == NULL)
14799 return PyObject_Str(x);
14800 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014801 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014802}
14803
Guido van Rossume023fe02001-08-30 03:12:59 +000014804static PyObject *
14805unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14806{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014807 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014808 Py_ssize_t length, char_size;
14809 int share_wstr, share_utf8;
14810 unsigned int kind;
14811 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014812
Benjamin Peterson14339b62009-01-31 16:36:08 +000014813 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014814
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014815 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014816 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014817 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014818 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014819 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014820 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014821 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014822 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014823
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014824 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014825 if (self == NULL) {
14826 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014827 return NULL;
14828 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014829 kind = PyUnicode_KIND(unicode);
14830 length = PyUnicode_GET_LENGTH(unicode);
14831
14832 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014833#ifdef Py_DEBUG
14834 _PyUnicode_HASH(self) = -1;
14835#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014836 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014837#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014838 _PyUnicode_STATE(self).interned = 0;
14839 _PyUnicode_STATE(self).kind = kind;
14840 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014841 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014842 _PyUnicode_STATE(self).ready = 1;
14843 _PyUnicode_WSTR(self) = NULL;
14844 _PyUnicode_UTF8_LENGTH(self) = 0;
14845 _PyUnicode_UTF8(self) = NULL;
14846 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014847 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014848
14849 share_utf8 = 0;
14850 share_wstr = 0;
14851 if (kind == PyUnicode_1BYTE_KIND) {
14852 char_size = 1;
14853 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14854 share_utf8 = 1;
14855 }
14856 else if (kind == PyUnicode_2BYTE_KIND) {
14857 char_size = 2;
14858 if (sizeof(wchar_t) == 2)
14859 share_wstr = 1;
14860 }
14861 else {
14862 assert(kind == PyUnicode_4BYTE_KIND);
14863 char_size = 4;
14864 if (sizeof(wchar_t) == 4)
14865 share_wstr = 1;
14866 }
14867
14868 /* Ensure we won't overflow the length. */
14869 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14870 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014871 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014872 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014873 data = PyObject_MALLOC((length + 1) * char_size);
14874 if (data == NULL) {
14875 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014876 goto onError;
14877 }
14878
Victor Stinnerc3c74152011-10-02 20:39:55 +020014879 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014880 if (share_utf8) {
14881 _PyUnicode_UTF8_LENGTH(self) = length;
14882 _PyUnicode_UTF8(self) = data;
14883 }
14884 if (share_wstr) {
14885 _PyUnicode_WSTR_LENGTH(self) = length;
14886 _PyUnicode_WSTR(self) = (wchar_t *)data;
14887 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014888
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014889 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014890 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014891 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014892#ifdef Py_DEBUG
14893 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14894#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014895 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014896 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014897
14898onError:
14899 Py_DECREF(unicode);
14900 Py_DECREF(self);
14901 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014902}
14903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014904PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014905"str(object='') -> str\n\
14906str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014907\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014908Create a new string object from the given object. If encoding or\n\
14909errors is specified, then the object must expose a data buffer\n\
14910that will be decoded using the given encoding and error handler.\n\
14911Otherwise, returns the result of object.__str__() (if defined)\n\
14912or repr(object).\n\
14913encoding defaults to sys.getdefaultencoding().\n\
14914errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014915
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014916static PyObject *unicode_iter(PyObject *seq);
14917
Guido van Rossumd57fd912000-03-10 22:53:23 +000014918PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014919 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014920 "str", /* tp_name */
14921 sizeof(PyUnicodeObject), /* tp_size */
14922 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014923 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014924 (destructor)unicode_dealloc, /* tp_dealloc */
14925 0, /* tp_print */
14926 0, /* tp_getattr */
14927 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014928 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014929 unicode_repr, /* tp_repr */
14930 &unicode_as_number, /* tp_as_number */
14931 &unicode_as_sequence, /* tp_as_sequence */
14932 &unicode_as_mapping, /* tp_as_mapping */
14933 (hashfunc) unicode_hash, /* tp_hash*/
14934 0, /* tp_call*/
14935 (reprfunc) unicode_str, /* tp_str */
14936 PyObject_GenericGetAttr, /* tp_getattro */
14937 0, /* tp_setattro */
14938 0, /* tp_as_buffer */
14939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014940 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 unicode_doc, /* tp_doc */
14942 0, /* tp_traverse */
14943 0, /* tp_clear */
14944 PyUnicode_RichCompare, /* tp_richcompare */
14945 0, /* tp_weaklistoffset */
14946 unicode_iter, /* tp_iter */
14947 0, /* tp_iternext */
14948 unicode_methods, /* tp_methods */
14949 0, /* tp_members */
14950 0, /* tp_getset */
14951 &PyBaseObject_Type, /* tp_base */
14952 0, /* tp_dict */
14953 0, /* tp_descr_get */
14954 0, /* tp_descr_set */
14955 0, /* tp_dictoffset */
14956 0, /* tp_init */
14957 0, /* tp_alloc */
14958 unicode_new, /* tp_new */
14959 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014960};
14961
14962/* Initialize the Unicode implementation */
14963
Victor Stinner3a50e702011-10-18 21:21:00 +020014964int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014965{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014966 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014967 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014968 0x000A, /* LINE FEED */
14969 0x000D, /* CARRIAGE RETURN */
14970 0x001C, /* FILE SEPARATOR */
14971 0x001D, /* GROUP SEPARATOR */
14972 0x001E, /* RECORD SEPARATOR */
14973 0x0085, /* NEXT LINE */
14974 0x2028, /* LINE SEPARATOR */
14975 0x2029, /* PARAGRAPH SEPARATOR */
14976 };
14977
Fred Drakee4315f52000-05-09 19:53:39 +000014978 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014979 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014980 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014981 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014982 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014983
Guido van Rossumcacfc072002-05-24 19:01:59 +000014984 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014985 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014986
14987 /* initialize the linebreak bloom filter */
14988 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014989 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014990 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014991
Christian Heimes26532f72013-07-20 14:57:16 +020014992 if (PyType_Ready(&EncodingMapType) < 0)
14993 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014994
Benjamin Petersonc4311282012-10-30 23:21:10 -040014995 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14996 Py_FatalError("Can't initialize field name iterator type");
14997
14998 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14999 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015000
Victor Stinner3a50e702011-10-18 21:21:00 +020015001#ifdef HAVE_MBCS
15002 winver.dwOSVersionInfoSize = sizeof(winver);
15003 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
15004 PyErr_SetFromWindowsErr(0);
15005 return -1;
15006 }
15007#endif
15008 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015009}
15010
15011/* Finalize the Unicode implementation */
15012
Christian Heimesa156e092008-02-16 07:38:31 +000015013int
15014PyUnicode_ClearFreeList(void)
15015{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015016 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015017}
15018
Guido van Rossumd57fd912000-03-10 22:53:23 +000015019void
Thomas Wouters78890102000-07-22 19:25:51 +000015020_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015021{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015022 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015023
Serhiy Storchaka05997252013-01-26 12:14:02 +020015024 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015025
Serhiy Storchaka05997252013-01-26 12:14:02 +020015026 for (i = 0; i < 256; i++)
15027 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015028 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015029 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015030}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015031
Walter Dörwald16807132007-05-25 13:52:07 +000015032void
15033PyUnicode_InternInPlace(PyObject **p)
15034{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015035 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015037#ifdef Py_DEBUG
15038 assert(s != NULL);
15039 assert(_PyUnicode_CHECK(s));
15040#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015041 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015042 return;
15043#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015044 /* If it's a subclass, we don't really know what putting
15045 it in the interned dict might do. */
15046 if (!PyUnicode_CheckExact(s))
15047 return;
15048 if (PyUnicode_CHECK_INTERNED(s))
15049 return;
15050 if (interned == NULL) {
15051 interned = PyDict_New();
15052 if (interned == NULL) {
15053 PyErr_Clear(); /* Don't leave an exception */
15054 return;
15055 }
15056 }
15057 /* It might be that the GetItem call fails even
15058 though the key is present in the dictionary,
15059 namely when this happens during a stack overflow. */
15060 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015061 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015062 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015063
Victor Stinnerf0335102013-04-14 19:13:03 +020015064 if (t) {
15065 Py_INCREF(t);
15066 Py_DECREF(*p);
15067 *p = t;
15068 return;
15069 }
Walter Dörwald16807132007-05-25 13:52:07 +000015070
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015072 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015073 PyErr_Clear();
15074 PyThreadState_GET()->recursion_critical = 0;
15075 return;
15076 }
15077 PyThreadState_GET()->recursion_critical = 0;
15078 /* The two references in interned are not counted by refcnt.
15079 The deallocator will take care of this */
15080 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015081 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015082}
15083
15084void
15085PyUnicode_InternImmortal(PyObject **p)
15086{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 PyUnicode_InternInPlace(p);
15088 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015089 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 Py_INCREF(*p);
15091 }
Walter Dörwald16807132007-05-25 13:52:07 +000015092}
15093
15094PyObject *
15095PyUnicode_InternFromString(const char *cp)
15096{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015097 PyObject *s = PyUnicode_FromString(cp);
15098 if (s == NULL)
15099 return NULL;
15100 PyUnicode_InternInPlace(&s);
15101 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015102}
15103
Alexander Belopolsky40018472011-02-26 01:02:56 +000015104void
15105_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015106{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015108 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015109 Py_ssize_t i, n;
15110 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015111
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 if (interned == NULL || !PyDict_Check(interned))
15113 return;
15114 keys = PyDict_Keys(interned);
15115 if (keys == NULL || !PyList_Check(keys)) {
15116 PyErr_Clear();
15117 return;
15118 }
Walter Dörwald16807132007-05-25 13:52:07 +000015119
Benjamin Peterson14339b62009-01-31 16:36:08 +000015120 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15121 detector, interned unicode strings are not forcibly deallocated;
15122 rather, we give them their stolen references back, and then clear
15123 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015124
Benjamin Peterson14339b62009-01-31 16:36:08 +000015125 n = PyList_GET_SIZE(keys);
15126 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015127 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015129 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015130 if (PyUnicode_READY(s) == -1) {
15131 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015132 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015134 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015135 case SSTATE_NOT_INTERNED:
15136 /* XXX Shouldn't happen */
15137 break;
15138 case SSTATE_INTERNED_IMMORTAL:
15139 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015140 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 break;
15142 case SSTATE_INTERNED_MORTAL:
15143 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015144 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 break;
15146 default:
15147 Py_FatalError("Inconsistent interned string state.");
15148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015149 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 }
15151 fprintf(stderr, "total size of all interned strings: "
15152 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15153 "mortal/immortal\n", mortal_size, immortal_size);
15154 Py_DECREF(keys);
15155 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015156 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015157}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015158
15159
15160/********************* Unicode Iterator **************************/
15161
15162typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015163 PyObject_HEAD
15164 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015165 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015166} unicodeiterobject;
15167
15168static void
15169unicodeiter_dealloc(unicodeiterobject *it)
15170{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015171 _PyObject_GC_UNTRACK(it);
15172 Py_XDECREF(it->it_seq);
15173 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015174}
15175
15176static int
15177unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15178{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015179 Py_VISIT(it->it_seq);
15180 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015181}
15182
15183static PyObject *
15184unicodeiter_next(unicodeiterobject *it)
15185{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015186 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015187
Benjamin Peterson14339b62009-01-31 16:36:08 +000015188 assert(it != NULL);
15189 seq = it->it_seq;
15190 if (seq == NULL)
15191 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015192 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015194 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15195 int kind = PyUnicode_KIND(seq);
15196 void *data = PyUnicode_DATA(seq);
15197 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15198 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015199 if (item != NULL)
15200 ++it->it_index;
15201 return item;
15202 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015203
Benjamin Peterson14339b62009-01-31 16:36:08 +000015204 Py_DECREF(seq);
15205 it->it_seq = NULL;
15206 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015207}
15208
15209static PyObject *
15210unicodeiter_len(unicodeiterobject *it)
15211{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015212 Py_ssize_t len = 0;
15213 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015214 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015216}
15217
15218PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15219
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015220static PyObject *
15221unicodeiter_reduce(unicodeiterobject *it)
15222{
15223 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015224 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015225 it->it_seq, it->it_index);
15226 } else {
15227 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15228 if (u == NULL)
15229 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015230 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015231 }
15232}
15233
15234PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15235
15236static PyObject *
15237unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15238{
15239 Py_ssize_t index = PyLong_AsSsize_t(state);
15240 if (index == -1 && PyErr_Occurred())
15241 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015242 if (it->it_seq != NULL) {
15243 if (index < 0)
15244 index = 0;
15245 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15246 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15247 it->it_index = index;
15248 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015249 Py_RETURN_NONE;
15250}
15251
15252PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15253
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015254static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015255 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015256 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015257 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15258 reduce_doc},
15259 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15260 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015261 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015262};
15263
15264PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15266 "str_iterator", /* tp_name */
15267 sizeof(unicodeiterobject), /* tp_basicsize */
15268 0, /* tp_itemsize */
15269 /* methods */
15270 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15271 0, /* tp_print */
15272 0, /* tp_getattr */
15273 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015274 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015275 0, /* tp_repr */
15276 0, /* tp_as_number */
15277 0, /* tp_as_sequence */
15278 0, /* tp_as_mapping */
15279 0, /* tp_hash */
15280 0, /* tp_call */
15281 0, /* tp_str */
15282 PyObject_GenericGetAttr, /* tp_getattro */
15283 0, /* tp_setattro */
15284 0, /* tp_as_buffer */
15285 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15286 0, /* tp_doc */
15287 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15288 0, /* tp_clear */
15289 0, /* tp_richcompare */
15290 0, /* tp_weaklistoffset */
15291 PyObject_SelfIter, /* tp_iter */
15292 (iternextfunc)unicodeiter_next, /* tp_iternext */
15293 unicodeiter_methods, /* tp_methods */
15294 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015295};
15296
15297static PyObject *
15298unicode_iter(PyObject *seq)
15299{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015300 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015301
Benjamin Peterson14339b62009-01-31 16:36:08 +000015302 if (!PyUnicode_Check(seq)) {
15303 PyErr_BadInternalCall();
15304 return NULL;
15305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015306 if (PyUnicode_READY(seq) == -1)
15307 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015308 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15309 if (it == NULL)
15310 return NULL;
15311 it->it_index = 0;
15312 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015313 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015314 _PyObject_GC_TRACK(it);
15315 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015316}
15317
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015318
15319size_t
15320Py_UNICODE_strlen(const Py_UNICODE *u)
15321{
15322 int res = 0;
15323 while(*u++)
15324 res++;
15325 return res;
15326}
15327
15328Py_UNICODE*
15329Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15330{
15331 Py_UNICODE *u = s1;
15332 while ((*u++ = *s2++));
15333 return s1;
15334}
15335
15336Py_UNICODE*
15337Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15338{
15339 Py_UNICODE *u = s1;
15340 while ((*u++ = *s2++))
15341 if (n-- == 0)
15342 break;
15343 return s1;
15344}
15345
15346Py_UNICODE*
15347Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15348{
15349 Py_UNICODE *u1 = s1;
15350 u1 += Py_UNICODE_strlen(u1);
15351 Py_UNICODE_strcpy(u1, s2);
15352 return s1;
15353}
15354
15355int
15356Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15357{
15358 while (*s1 && *s2 && *s1 == *s2)
15359 s1++, s2++;
15360 if (*s1 && *s2)
15361 return (*s1 < *s2) ? -1 : +1;
15362 if (*s1)
15363 return 1;
15364 if (*s2)
15365 return -1;
15366 return 0;
15367}
15368
15369int
15370Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15371{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015372 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015373 for (; n != 0; n--) {
15374 u1 = *s1;
15375 u2 = *s2;
15376 if (u1 != u2)
15377 return (u1 < u2) ? -1 : +1;
15378 if (u1 == '\0')
15379 return 0;
15380 s1++;
15381 s2++;
15382 }
15383 return 0;
15384}
15385
15386Py_UNICODE*
15387Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15388{
15389 const Py_UNICODE *p;
15390 for (p = s; *p; p++)
15391 if (*p == c)
15392 return (Py_UNICODE*)p;
15393 return NULL;
15394}
15395
15396Py_UNICODE*
15397Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15398{
15399 const Py_UNICODE *p;
15400 p = s + Py_UNICODE_strlen(s);
15401 while (p != s) {
15402 p--;
15403 if (*p == c)
15404 return (Py_UNICODE*)p;
15405 }
15406 return NULL;
15407}
Victor Stinner331ea922010-08-10 16:37:20 +000015408
Victor Stinner71133ff2010-09-01 23:43:53 +000015409Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015410PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015411{
Victor Stinner577db2c2011-10-11 22:12:48 +020015412 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015413 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015415 if (!PyUnicode_Check(unicode)) {
15416 PyErr_BadArgument();
15417 return NULL;
15418 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015419 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015420 if (u == NULL)
15421 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015422 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015423 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015424 PyErr_NoMemory();
15425 return NULL;
15426 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015427 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015428 size *= sizeof(Py_UNICODE);
15429 copy = PyMem_Malloc(size);
15430 if (copy == NULL) {
15431 PyErr_NoMemory();
15432 return NULL;
15433 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015434 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015435 return copy;
15436}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015437
Georg Brandl66c221e2010-10-14 07:04:07 +000015438/* A _string module, to export formatter_parser and formatter_field_name_split
15439 to the string.Formatter class implemented in Python. */
15440
15441static PyMethodDef _string_methods[] = {
15442 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15443 METH_O, PyDoc_STR("split the argument as a field name")},
15444 {"formatter_parser", (PyCFunction) formatter_parser,
15445 METH_O, PyDoc_STR("parse the argument as a format string")},
15446 {NULL, NULL}
15447};
15448
15449static struct PyModuleDef _string_module = {
15450 PyModuleDef_HEAD_INIT,
15451 "_string",
15452 PyDoc_STR("string helper module"),
15453 0,
15454 _string_methods,
15455 NULL,
15456 NULL,
15457 NULL,
15458 NULL
15459};
15460
15461PyMODINIT_FUNC
15462PyInit__string(void)
15463{
15464 return PyModule_Create(&_string_module);
15465}
15466
15467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015468#ifdef __cplusplus
15469}
15470#endif