blob: e494e4a14643923bea0f8362ea9cd5b5647fedef [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Larry Hastings61272b72014-01-07 12:41:53 -080050/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080051class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080052[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080053/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080054
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055/* --- Globals ------------------------------------------------------------
56
Serhiy Storchaka05997252013-01-26 12:14:02 +020057NOTE: In the interpreter's initialization phase, some globals are currently
58 initialized dynamically as needed. In the process Unicode objects may
59 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000060
61*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64#ifdef __cplusplus
65extern "C" {
66#endif
67
Victor Stinner8faf8212011-12-08 22:14:11 +010068/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
69#define MAX_UNICODE 0x10ffff
70
Victor Stinner910337b2011-10-03 03:20:16 +020071#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020072# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020073#else
74# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
75#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020076
Victor Stinnere90fe6a2011-10-01 16:48:13 +020077#define _PyUnicode_UTF8(op) \
78 (((PyCompactUnicodeObject*)(op))->utf8)
79#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020080 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 assert(PyUnicode_IS_READY(op)), \
82 PyUnicode_IS_COMPACT_ASCII(op) ? \
83 ((char*)((PyASCIIObject*)(op) + 1)) : \
84 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020085#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020086 (((PyCompactUnicodeObject*)(op))->utf8_length)
87#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020088 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 assert(PyUnicode_IS_READY(op)), \
90 PyUnicode_IS_COMPACT_ASCII(op) ? \
91 ((PyASCIIObject*)(op))->length : \
92 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020093#define _PyUnicode_WSTR(op) \
94 (((PyASCIIObject*)(op))->wstr)
95#define _PyUnicode_WSTR_LENGTH(op) \
96 (((PyCompactUnicodeObject*)(op))->wstr_length)
97#define _PyUnicode_LENGTH(op) \
98 (((PyASCIIObject *)(op))->length)
99#define _PyUnicode_STATE(op) \
100 (((PyASCIIObject *)(op))->state)
101#define _PyUnicode_HASH(op) \
102 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200103#define _PyUnicode_KIND(op) \
104 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200105 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_GET_LENGTH(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_DATA_ANY(op) \
110 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200130 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200131 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200132 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
133
Victor Stinner03490912011-10-03 23:45:12 +0200134/* true if the Unicode object has an allocated wstr memory block
135 (not shared with other data) */
136#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200137 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100148 to_type *_to = (to_type *)(to); \
149 const from_type *_iter = (from_type *)(begin); \
150 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200153 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Walter Dörwald16807132007-05-25 13:52:07 +0000165/* This dictionary holds all interned unicode strings. Note that references
166 to strings in this dictionary are *not* counted in the string's ob_refcnt.
167 When the interned string reaches a refcnt of 0 the string deallocation
168 function will delete the reference from this dictionary.
169
170 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000171 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000172*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200173static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000174
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000175/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200176static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200177
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179 do { \
180 if (unicode_empty != NULL) \
181 Py_INCREF(unicode_empty); \
182 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183 unicode_empty = PyUnicode_New(0, 0); \
184 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200185 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
187 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191#define _Py_RETURN_UNICODE_EMPTY() \
192 do { \
193 _Py_INCREF_UNICODE_EMPTY(); \
194 return unicode_empty; \
195 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200197/* Forward declaration */
198Py_LOCAL_INLINE(int)
199_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
200
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200206static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100242static int unicode_modifiable(PyObject *unicode);
243
Victor Stinnerfe226c02011-10-03 03:52:20 +0200244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100246_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200247static PyObject *
248_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
249static PyObject *
250_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
251
252static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100255 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
257
Alexander Belopolsky40018472011-02-26 01:02:56 +0000258static void
259raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300260 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100261 PyObject *unicode,
262 Py_ssize_t startpos, Py_ssize_t endpos,
263 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Same for linebreaks */
266static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000268/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* 0x000B, * LINE TABULATION */
270/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x001C, * FILE SEPARATOR */
275/* 0x001D, * GROUP SEPARATOR */
276/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 1, 1, 1, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000282
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000291};
292
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300293/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
294 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000296PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000298#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 /* This is actually an illegal character, so it should
302 not be passed to unichr. */
303 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000304#endif
305}
306
Victor Stinner910337b2011-10-03 03:20:16 +0200307#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200308int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100309_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200310{
311 PyASCIIObject *ascii;
312 unsigned int kind;
313
314 assert(PyUnicode_Check(op));
315
316 ascii = (PyASCIIObject *)op;
317 kind = ascii->state.kind;
318
Victor Stinnera3b334d2011-10-03 13:53:37 +0200319 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200325 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200326
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 if (ascii->state.compact == 1) {
328 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(kind == PyUnicode_1BYTE_KIND
330 || kind == PyUnicode_2BYTE_KIND
331 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200333 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100335 }
336 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
338
339 data = unicode->data.any;
340 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->length == 0);
342 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100346 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200347 assert(ascii->wstr != NULL);
348 assert(data == NULL);
349 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200391 void *data;
392 Py_UCS4 ch;
393
394 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 for (i=0; i < ascii->length; i++)
396 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 if (ch > maxchar)
399 maxchar = ch;
400 }
401 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100402 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 255);
405 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 else
407 assert(maxchar < 128);
408 }
Victor Stinner77faf692011-11-20 18:56:05 +0100409 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 assert(maxchar <= 0xFFFF);
412 }
413 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200414 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100415 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100416 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200417 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200418 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100423static PyObject*
424unicode_result_wchar(PyObject *unicode)
425{
426#ifndef Py_DEBUG
427 Py_ssize_t len;
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 len = _PyUnicode_WSTR_LENGTH(unicode);
430 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200432 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 }
434
435 if (len == 1) {
436 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100437 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
439 Py_DECREF(unicode);
440 return latin1_char;
441 }
442 }
443
444 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200445 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 return NULL;
447 }
448#else
Victor Stinneraa771272012-10-04 02:32:58 +0200449 assert(Py_REFCNT(unicode) == 1);
450
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100451 /* don't make the result ready in debug mode to ensure that the caller
452 makes the string ready before using it */
453 assert(_PyUnicode_CheckConsistency(unicode, 1));
454#endif
455 return unicode;
456}
457
458static PyObject*
459unicode_result_ready(PyObject *unicode)
460{
461 Py_ssize_t length;
462
463 length = PyUnicode_GET_LENGTH(unicode);
464 if (length == 0) {
465 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200467 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 }
469 return unicode_empty;
470 }
471
472 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200473 void *data = PyUnicode_DATA(unicode);
474 int kind = PyUnicode_KIND(unicode);
475 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 if (ch < 256) {
477 PyObject *latin1_char = unicode_latin1[ch];
478 if (latin1_char != NULL) {
479 if (unicode != latin1_char) {
480 Py_INCREF(latin1_char);
481 Py_DECREF(unicode);
482 }
483 return latin1_char;
484 }
485 else {
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 Py_INCREF(unicode);
488 unicode_latin1[ch] = unicode;
489 return unicode;
490 }
491 }
492 }
493
494 assert(_PyUnicode_CheckConsistency(unicode, 1));
495 return unicode;
496}
497
498static PyObject*
499unicode_result(PyObject *unicode)
500{
501 assert(_PyUnicode_CHECK(unicode));
502 if (PyUnicode_IS_READY(unicode))
503 return unicode_result_ready(unicode);
504 else
505 return unicode_result_wchar(unicode);
506}
507
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508static PyObject*
509unicode_result_unchanged(PyObject *unicode)
510{
511 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500512 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100513 return NULL;
514 Py_INCREF(unicode);
515 return unicode;
516 }
517 else
518 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100519 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100520}
521
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522/* --- Bloom Filters ----------------------------------------------------- */
523
524/* stuff to implement simple "bloom filters" for Unicode characters.
525 to keep things simple, we use a single bitmask, using the least 5
526 bits from each unicode characters as the bit index. */
527
528/* the linebreak mask is set up by Unicode_Init below */
529
Antoine Pitrouf068f942010-01-13 14:19:12 +0000530#if LONG_BIT >= 128
531#define BLOOM_WIDTH 128
532#elif LONG_BIT >= 64
533#define BLOOM_WIDTH 64
534#elif LONG_BIT >= 32
535#define BLOOM_WIDTH 32
536#else
537#error "LONG_BIT is smaller than 32"
538#endif
539
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540#define BLOOM_MASK unsigned long
541
Serhiy Storchaka05997252013-01-26 12:14:02 +0200542static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543
Antoine Pitrouf068f942010-01-13 14:19:12 +0000544#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
Benjamin Peterson29060642009-01-31 22:14:21 +0000546#define BLOOM_LINEBREAK(ch) \
547 ((ch) < 128U ? ascii_linebreak[(ch)] : \
548 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Alexander Belopolsky40018472011-02-26 01:02:56 +0000550Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200551make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552{
Victor Stinnera85af502013-04-09 21:53:54 +0200553#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
554 do { \
555 TYPE *data = (TYPE *)PTR; \
556 TYPE *end = data + LEN; \
557 Py_UCS4 ch; \
558 for (; data != end; data++) { \
559 ch = *data; \
560 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
561 } \
562 break; \
563 } while (0)
564
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 /* calculate simple bloom-style bitmask for a given unicode string */
566
Antoine Pitrouf068f942010-01-13 14:19:12 +0000567 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568
569 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200570 switch (kind) {
571 case PyUnicode_1BYTE_KIND:
572 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
573 break;
574 case PyUnicode_2BYTE_KIND:
575 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
576 break;
577 case PyUnicode_4BYTE_KIND:
578 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
579 break;
580 default:
581 assert(0);
582 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200584
585#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586}
587
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200588/* Compilation of templated routines */
589
590#include "stringlib/asciilib.h"
591#include "stringlib/fastsearch.h"
592#include "stringlib/partition.h"
593#include "stringlib/split.h"
594#include "stringlib/count.h"
595#include "stringlib/find.h"
596#include "stringlib/find_max_char.h"
597#include "stringlib/localeutil.h"
598#include "stringlib/undef.h"
599
600#include "stringlib/ucs1lib.h"
601#include "stringlib/fastsearch.h"
602#include "stringlib/partition.h"
603#include "stringlib/split.h"
604#include "stringlib/count.h"
605#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300606#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200607#include "stringlib/find_max_char.h"
608#include "stringlib/localeutil.h"
609#include "stringlib/undef.h"
610
611#include "stringlib/ucs2lib.h"
612#include "stringlib/fastsearch.h"
613#include "stringlib/partition.h"
614#include "stringlib/split.h"
615#include "stringlib/count.h"
616#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300617#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200618#include "stringlib/find_max_char.h"
619#include "stringlib/localeutil.h"
620#include "stringlib/undef.h"
621
622#include "stringlib/ucs4lib.h"
623#include "stringlib/fastsearch.h"
624#include "stringlib/partition.h"
625#include "stringlib/split.h"
626#include "stringlib/count.h"
627#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300628#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200629#include "stringlib/find_max_char.h"
630#include "stringlib/localeutil.h"
631#include "stringlib/undef.h"
632
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200633#include "stringlib/unicodedefs.h"
634#include "stringlib/fastsearch.h"
635#include "stringlib/count.h"
636#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100637#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200638
Guido van Rossumd57fd912000-03-10 22:53:23 +0000639/* --- Unicode Object ----------------------------------------------------- */
640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200642fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200643
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200644Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200645 Py_ssize_t size, Py_UCS4 ch,
646 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
649
650 switch (kind) {
651 case PyUnicode_1BYTE_KIND:
652 {
653 Py_UCS1 ch1 = (Py_UCS1) ch;
654 if (ch1 == ch)
655 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
656 else
657 return -1;
658 }
659 case PyUnicode_2BYTE_KIND:
660 {
661 Py_UCS2 ch2 = (Py_UCS2) ch;
662 if (ch2 == ch)
663 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
664 else
665 return -1;
666 }
667 case PyUnicode_4BYTE_KIND:
668 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
669 default:
670 assert(0);
671 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200672 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200673}
674
Victor Stinnerafffce42012-10-03 23:03:17 +0200675#ifdef Py_DEBUG
676/* Fill the data of an Unicode string with invalid characters to detect bugs
677 earlier.
678
679 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
680 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
681 invalid character in Unicode 6.0. */
682static void
683unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
684{
685 int kind = PyUnicode_KIND(unicode);
686 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
687 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
688 if (length <= old_length)
689 return;
690 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
691}
692#endif
693
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694static PyObject*
695resize_compact(PyObject *unicode, Py_ssize_t length)
696{
697 Py_ssize_t char_size;
698 Py_ssize_t struct_size;
699 Py_ssize_t new_size;
700 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100701 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200702#ifdef Py_DEBUG
703 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
704#endif
705
Victor Stinner79891572012-05-03 13:43:07 +0200706 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200707 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100708 assert(PyUnicode_IS_COMPACT(unicode));
709
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200710 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100711 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200712 struct_size = sizeof(PyASCIIObject);
713 else
714 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200715 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716
Victor Stinnerfe226c02011-10-03 03:52:20 +0200717 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
718 PyErr_NoMemory();
719 return NULL;
720 }
721 new_size = (struct_size + (length + 1) * char_size);
722
Victor Stinner84def372011-12-11 20:04:56 +0100723 _Py_DEC_REFTOTAL;
724 _Py_ForgetReference(unicode);
725
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300726 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100727 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100728 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200729 PyErr_NoMemory();
730 return NULL;
731 }
Victor Stinner84def372011-12-11 20:04:56 +0100732 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100734
Victor Stinnerfe226c02011-10-03 03:52:20 +0200735 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200736 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100738 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200739 _PyUnicode_WSTR_LENGTH(unicode) = length;
740 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100741 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
742 PyObject_DEL(_PyUnicode_WSTR(unicode));
743 _PyUnicode_WSTR(unicode) = NULL;
744 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200745#ifdef Py_DEBUG
746 unicode_fill_invalid(unicode, old_length);
747#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200748 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
749 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200750 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200751 return unicode;
752}
753
Alexander Belopolsky40018472011-02-26 01:02:56 +0000754static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200755resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000756{
Victor Stinner95663112011-10-04 01:03:50 +0200757 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100758 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200759 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000761
Victor Stinnerfe226c02011-10-03 03:52:20 +0200762 if (PyUnicode_IS_READY(unicode)) {
763 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200764 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200766#ifdef Py_DEBUG
767 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
768#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769
770 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200771 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200772 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
773 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774
775 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
776 PyErr_NoMemory();
777 return -1;
778 }
779 new_size = (length + 1) * char_size;
780
Victor Stinner7a9105a2011-12-12 00:13:42 +0100781 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
782 {
783 PyObject_DEL(_PyUnicode_UTF8(unicode));
784 _PyUnicode_UTF8(unicode) = NULL;
785 _PyUnicode_UTF8_LENGTH(unicode) = 0;
786 }
787
Victor Stinnerfe226c02011-10-03 03:52:20 +0200788 data = (PyObject *)PyObject_REALLOC(data, new_size);
789 if (data == NULL) {
790 PyErr_NoMemory();
791 return -1;
792 }
793 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200794 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200795 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200796 _PyUnicode_WSTR_LENGTH(unicode) = length;
797 }
798 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200799 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 _PyUnicode_UTF8_LENGTH(unicode) = length;
801 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200802 _PyUnicode_LENGTH(unicode) = length;
803 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200804#ifdef Py_DEBUG
805 unicode_fill_invalid(unicode, old_length);
806#endif
Victor Stinner95663112011-10-04 01:03:50 +0200807 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200808 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200809 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200810 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200811 }
Victor Stinner95663112011-10-04 01:03:50 +0200812 assert(_PyUnicode_WSTR(unicode) != NULL);
813
814 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700815 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200816 PyErr_NoMemory();
817 return -1;
818 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100819 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200820 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100821 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200822 if (!wstr) {
823 PyErr_NoMemory();
824 return -1;
825 }
826 _PyUnicode_WSTR(unicode) = wstr;
827 _PyUnicode_WSTR(unicode)[length] = 0;
828 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200829 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000830 return 0;
831}
832
Victor Stinnerfe226c02011-10-03 03:52:20 +0200833static PyObject*
834resize_copy(PyObject *unicode, Py_ssize_t length)
835{
836 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100837 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200838 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100839
Benjamin Petersonbac79492012-01-14 13:34:47 -0500840 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100841 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842
843 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
844 if (copy == NULL)
845 return NULL;
846
847 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200848 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200849 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200850 }
851 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200852 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100853
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200854 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200855 if (w == NULL)
856 return NULL;
857 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
858 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200859 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
860 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200861 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200862 }
863}
864
Guido van Rossumd57fd912000-03-10 22:53:23 +0000865/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000866 Ux0000 terminated; some code (e.g. new_identifier)
867 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000868
869 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000870 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000871
872*/
873
Alexander Belopolsky40018472011-02-26 01:02:56 +0000874static PyUnicodeObject *
875_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000876{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200877 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200878 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000879
Thomas Wouters477c8d52006-05-27 19:21:47 +0000880 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000881 if (length == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000884 }
885
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000886 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700887 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000888 return (PyUnicodeObject *)PyErr_NoMemory();
889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200890 if (length < 0) {
891 PyErr_SetString(PyExc_SystemError,
892 "Negative size passed to _PyUnicode_New");
893 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000894 }
895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
897 if (unicode == NULL)
898 return NULL;
899 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100900
901 _PyUnicode_WSTR_LENGTH(unicode) = length;
902 _PyUnicode_HASH(unicode) = -1;
903 _PyUnicode_STATE(unicode).interned = 0;
904 _PyUnicode_STATE(unicode).kind = 0;
905 _PyUnicode_STATE(unicode).compact = 0;
906 _PyUnicode_STATE(unicode).ready = 0;
907 _PyUnicode_STATE(unicode).ascii = 0;
908 _PyUnicode_DATA_ANY(unicode) = NULL;
909 _PyUnicode_LENGTH(unicode) = 0;
910 _PyUnicode_UTF8(unicode) = NULL;
911 _PyUnicode_UTF8_LENGTH(unicode) = 0;
912
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
914 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100915 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000916 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100917 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200919
Jeremy Hyltond8082792003-09-16 19:41:39 +0000920 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000921 * the caller fails before initializing str -- unicode_resize()
922 * reads str[0], and the Keep-Alive optimization can keep memory
923 * allocated for str alive across a call to unicode_dealloc(unicode).
924 * We don't want unicode_resize to read uninitialized memory in
925 * that case.
926 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927 _PyUnicode_WSTR(unicode)[0] = 0;
928 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100929
Victor Stinner7931d9a2011-11-04 00:22:48 +0100930 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000931 return unicode;
932}
933
Victor Stinnerf42dc442011-10-02 23:33:16 +0200934static const char*
935unicode_kind_name(PyObject *unicode)
936{
Victor Stinner42dfd712011-10-03 14:41:45 +0200937 /* don't check consistency: unicode_kind_name() is called from
938 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200939 if (!PyUnicode_IS_COMPACT(unicode))
940 {
941 if (!PyUnicode_IS_READY(unicode))
942 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600943 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200944 {
945 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200946 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200947 return "legacy ascii";
948 else
949 return "legacy latin1";
950 case PyUnicode_2BYTE_KIND:
951 return "legacy UCS2";
952 case PyUnicode_4BYTE_KIND:
953 return "legacy UCS4";
954 default:
955 return "<legacy invalid kind>";
956 }
957 }
958 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600959 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200960 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200961 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200962 return "ascii";
963 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200966 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200967 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 default:
970 return "<invalid compact kind>";
971 }
972}
973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975/* Functions wrapping macros for use in debugger */
976char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200977 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978}
979
980void *_PyUnicode_compact_data(void *unicode) {
981 return _PyUnicode_COMPACT_DATA(unicode);
982}
983void *_PyUnicode_data(void *unicode){
984 printf("obj %p\n", unicode);
985 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
986 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
987 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
988 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
989 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
990 return PyUnicode_DATA(unicode);
991}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200992
993void
994_PyUnicode_Dump(PyObject *op)
995{
996 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200997 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
998 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
999 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001000
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001002 {
1003 if (ascii->state.ascii)
1004 data = (ascii + 1);
1005 else
1006 data = (compact + 1);
1007 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001008 else
1009 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001010 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1011 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001012
Victor Stinnera849a4b2011-10-03 12:12:11 +02001013 if (ascii->wstr == data)
1014 printf("shared ");
1015 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001016
Victor Stinnera3b334d2011-10-03 13:53:37 +02001017 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001018 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001019 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1020 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001021 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1022 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001023 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001024 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001025}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001026#endif
1027
1028PyObject *
1029PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1030{
1031 PyObject *obj;
1032 PyCompactUnicodeObject *unicode;
1033 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001034 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001035 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001036 Py_ssize_t char_size;
1037 Py_ssize_t struct_size;
1038
1039 /* Optimization for empty strings */
1040 if (size == 0 && unicode_empty != NULL) {
1041 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001042 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 }
1044
Victor Stinner9e9d6892011-10-04 01:02:02 +02001045 is_ascii = 0;
1046 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 struct_size = sizeof(PyCompactUnicodeObject);
1048 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001049 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 char_size = 1;
1051 is_ascii = 1;
1052 struct_size = sizeof(PyASCIIObject);
1053 }
1054 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001055 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 char_size = 1;
1057 }
1058 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001059 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 char_size = 2;
1061 if (sizeof(wchar_t) == 2)
1062 is_sharing = 1;
1063 }
1064 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001065 if (maxchar > MAX_UNICODE) {
1066 PyErr_SetString(PyExc_SystemError,
1067 "invalid maximum character passed to PyUnicode_New");
1068 return NULL;
1069 }
Victor Stinner8f825062012-04-27 13:55:39 +02001070 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071 char_size = 4;
1072 if (sizeof(wchar_t) == 4)
1073 is_sharing = 1;
1074 }
1075
1076 /* Ensure we won't overflow the size. */
1077 if (size < 0) {
1078 PyErr_SetString(PyExc_SystemError,
1079 "Negative size passed to PyUnicode_New");
1080 return NULL;
1081 }
1082 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1083 return PyErr_NoMemory();
1084
1085 /* Duplicated allocation code from _PyObject_New() instead of a call to
1086 * PyObject_New() so we are able to allocate space for the object and
1087 * it's data buffer.
1088 */
1089 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1090 if (obj == NULL)
1091 return PyErr_NoMemory();
1092 obj = PyObject_INIT(obj, &PyUnicode_Type);
1093 if (obj == NULL)
1094 return NULL;
1095
1096 unicode = (PyCompactUnicodeObject *)obj;
1097 if (is_ascii)
1098 data = ((PyASCIIObject*)obj) + 1;
1099 else
1100 data = unicode + 1;
1101 _PyUnicode_LENGTH(unicode) = size;
1102 _PyUnicode_HASH(unicode) = -1;
1103 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001104 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 _PyUnicode_STATE(unicode).compact = 1;
1106 _PyUnicode_STATE(unicode).ready = 1;
1107 _PyUnicode_STATE(unicode).ascii = is_ascii;
1108 if (is_ascii) {
1109 ((char*)data)[size] = 0;
1110 _PyUnicode_WSTR(unicode) = NULL;
1111 }
Victor Stinner8f825062012-04-27 13:55:39 +02001112 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001113 ((char*)data)[size] = 0;
1114 _PyUnicode_WSTR(unicode) = NULL;
1115 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001117 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001118 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 else {
1120 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001121 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001122 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001124 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 ((Py_UCS4*)data)[size] = 0;
1126 if (is_sharing) {
1127 _PyUnicode_WSTR_LENGTH(unicode) = size;
1128 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1129 }
1130 else {
1131 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1132 _PyUnicode_WSTR(unicode) = NULL;
1133 }
1134 }
Victor Stinner8f825062012-04-27 13:55:39 +02001135#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001136 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001137#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001138 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139 return obj;
1140}
1141
1142#if SIZEOF_WCHAR_T == 2
1143/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1144 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001145 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146
1147 This function assumes that unicode can hold one more code point than wstr
1148 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001149static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001151 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152{
1153 const wchar_t *iter;
1154 Py_UCS4 *ucs4_out;
1155
Victor Stinner910337b2011-10-03 03:20:16 +02001156 assert(unicode != NULL);
1157 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001158 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1159 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1160
1161 for (iter = begin; iter < end; ) {
1162 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1163 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001164 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1165 && (iter+1) < end
1166 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167 {
Victor Stinner551ac952011-11-29 22:58:13 +01001168 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169 iter += 2;
1170 }
1171 else {
1172 *ucs4_out++ = *iter;
1173 iter++;
1174 }
1175 }
1176 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1177 _PyUnicode_GET_LENGTH(unicode)));
1178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179}
1180#endif
1181
Victor Stinnercd9950f2011-10-02 00:34:53 +02001182static int
Victor Stinner488fa492011-12-12 00:01:39 +01001183unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001184{
Victor Stinner488fa492011-12-12 00:01:39 +01001185 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001186 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001187 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001188 return -1;
1189 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001190 return 0;
1191}
1192
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001193static int
1194_copy_characters(PyObject *to, Py_ssize_t to_start,
1195 PyObject *from, Py_ssize_t from_start,
1196 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001197{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001198 unsigned int from_kind, to_kind;
1199 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200
Victor Stinneree4544c2012-05-09 22:24:08 +02001201 assert(0 <= how_many);
1202 assert(0 <= from_start);
1203 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001204 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001205 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001206 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207
Victor Stinnerd3f08822012-05-29 12:57:52 +02001208 assert(PyUnicode_Check(to));
1209 assert(PyUnicode_IS_READY(to));
1210 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1211
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001212 if (how_many == 0)
1213 return 0;
1214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001215 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001216 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219
Victor Stinnerf1852262012-06-16 16:38:26 +02001220#ifdef Py_DEBUG
1221 if (!check_maxchar
1222 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1223 {
1224 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1225 Py_UCS4 ch;
1226 Py_ssize_t i;
1227 for (i=0; i < how_many; i++) {
1228 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1229 assert(ch <= to_maxchar);
1230 }
1231 }
1232#endif
1233
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001234 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001235 if (check_maxchar
1236 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1237 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001238 /* Writing Latin-1 characters into an ASCII string requires to
1239 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001240 Py_UCS4 max_char;
1241 max_char = ucs1lib_find_max_char(from_data,
1242 (Py_UCS1*)from_data + how_many);
1243 if (max_char >= 128)
1244 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001245 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001246 Py_MEMCPY((char*)to_data + to_kind * to_start,
1247 (char*)from_data + from_kind * from_start,
1248 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001249 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001250 else if (from_kind == PyUnicode_1BYTE_KIND
1251 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001252 {
1253 _PyUnicode_CONVERT_BYTES(
1254 Py_UCS1, Py_UCS2,
1255 PyUnicode_1BYTE_DATA(from) + from_start,
1256 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1257 PyUnicode_2BYTE_DATA(to) + to_start
1258 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001259 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001260 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001261 && to_kind == PyUnicode_4BYTE_KIND)
1262 {
1263 _PyUnicode_CONVERT_BYTES(
1264 Py_UCS1, Py_UCS4,
1265 PyUnicode_1BYTE_DATA(from) + from_start,
1266 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1267 PyUnicode_4BYTE_DATA(to) + to_start
1268 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001269 }
1270 else if (from_kind == PyUnicode_2BYTE_KIND
1271 && to_kind == PyUnicode_4BYTE_KIND)
1272 {
1273 _PyUnicode_CONVERT_BYTES(
1274 Py_UCS2, Py_UCS4,
1275 PyUnicode_2BYTE_DATA(from) + from_start,
1276 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1277 PyUnicode_4BYTE_DATA(to) + to_start
1278 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001279 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001280 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001281 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1282
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001283 if (!check_maxchar) {
1284 if (from_kind == PyUnicode_2BYTE_KIND
1285 && to_kind == PyUnicode_1BYTE_KIND)
1286 {
1287 _PyUnicode_CONVERT_BYTES(
1288 Py_UCS2, Py_UCS1,
1289 PyUnicode_2BYTE_DATA(from) + from_start,
1290 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1291 PyUnicode_1BYTE_DATA(to) + to_start
1292 );
1293 }
1294 else if (from_kind == PyUnicode_4BYTE_KIND
1295 && to_kind == PyUnicode_1BYTE_KIND)
1296 {
1297 _PyUnicode_CONVERT_BYTES(
1298 Py_UCS4, Py_UCS1,
1299 PyUnicode_4BYTE_DATA(from) + from_start,
1300 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1301 PyUnicode_1BYTE_DATA(to) + to_start
1302 );
1303 }
1304 else if (from_kind == PyUnicode_4BYTE_KIND
1305 && to_kind == PyUnicode_2BYTE_KIND)
1306 {
1307 _PyUnicode_CONVERT_BYTES(
1308 Py_UCS4, Py_UCS2,
1309 PyUnicode_4BYTE_DATA(from) + from_start,
1310 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1311 PyUnicode_2BYTE_DATA(to) + to_start
1312 );
1313 }
1314 else {
1315 assert(0);
1316 return -1;
1317 }
1318 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001319 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001320 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001321 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001322 Py_ssize_t i;
1323
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 for (i=0; i < how_many; i++) {
1325 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001326 if (ch > to_maxchar)
1327 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001328 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1329 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001330 }
1331 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001332 return 0;
1333}
1334
Victor Stinnerd3f08822012-05-29 12:57:52 +02001335void
1336_PyUnicode_FastCopyCharacters(
1337 PyObject *to, Py_ssize_t to_start,
1338 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001339{
1340 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1341}
1342
1343Py_ssize_t
1344PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1345 PyObject *from, Py_ssize_t from_start,
1346 Py_ssize_t how_many)
1347{
1348 int err;
1349
1350 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1351 PyErr_BadInternalCall();
1352 return -1;
1353 }
1354
Benjamin Petersonbac79492012-01-14 13:34:47 -05001355 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001356 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001357 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001358 return -1;
1359
Victor Stinnerd3f08822012-05-29 12:57:52 +02001360 if (from_start < 0) {
1361 PyErr_SetString(PyExc_IndexError, "string index out of range");
1362 return -1;
1363 }
1364 if (to_start < 0) {
1365 PyErr_SetString(PyExc_IndexError, "string index out of range");
1366 return -1;
1367 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001368 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1369 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1370 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001371 "Cannot write %zi characters at %zi "
1372 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001373 how_many, to_start, PyUnicode_GET_LENGTH(to));
1374 return -1;
1375 }
1376
1377 if (how_many == 0)
1378 return 0;
1379
Victor Stinner488fa492011-12-12 00:01:39 +01001380 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001381 return -1;
1382
1383 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1384 if (err) {
1385 PyErr_Format(PyExc_SystemError,
1386 "Cannot copy %s characters "
1387 "into a string of %s characters",
1388 unicode_kind_name(from),
1389 unicode_kind_name(to));
1390 return -1;
1391 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001392 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393}
1394
Victor Stinner17222162011-09-28 22:15:37 +02001395/* Find the maximum code point and count the number of surrogate pairs so a
1396 correct string length can be computed before converting a string to UCS4.
1397 This function counts single surrogates as a character and not as a pair.
1398
1399 Return 0 on success, or -1 on error. */
1400static int
1401find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1402 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403{
1404 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001405 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406
Victor Stinnerc53be962011-10-02 21:33:54 +02001407 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 *num_surrogates = 0;
1409 *maxchar = 0;
1410
1411 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001413 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1414 && (iter+1) < end
1415 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1416 {
1417 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1418 ++(*num_surrogates);
1419 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420 }
1421 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001422#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001423 {
1424 ch = *iter;
1425 iter++;
1426 }
1427 if (ch > *maxchar) {
1428 *maxchar = ch;
1429 if (*maxchar > MAX_UNICODE) {
1430 PyErr_Format(PyExc_ValueError,
1431 "character U+%x is not in range [U+0000; U+10ffff]",
1432 ch);
1433 return -1;
1434 }
1435 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001436 }
1437 return 0;
1438}
1439
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001440int
1441_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001442{
1443 wchar_t *end;
1444 Py_UCS4 maxchar = 0;
1445 Py_ssize_t num_surrogates;
1446#if SIZEOF_WCHAR_T == 2
1447 Py_ssize_t length_wo_surrogates;
1448#endif
1449
Georg Brandl7597add2011-10-05 16:36:47 +02001450 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001451 strings were created using _PyObject_New() and where no canonical
1452 representation (the str field) has been set yet aka strings
1453 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001454 assert(_PyUnicode_CHECK(unicode));
1455 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001457 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001458 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001459 /* Actually, it should neither be interned nor be anything else: */
1460 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001463 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001464 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466
1467 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1469 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470 PyErr_NoMemory();
1471 return -1;
1472 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001473 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 _PyUnicode_WSTR(unicode), end,
1475 PyUnicode_1BYTE_DATA(unicode));
1476 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1477 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1478 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1479 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001480 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001481 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001482 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001483 }
1484 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001485 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001486 _PyUnicode_UTF8(unicode) = NULL;
1487 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001488 }
1489 PyObject_FREE(_PyUnicode_WSTR(unicode));
1490 _PyUnicode_WSTR(unicode) = NULL;
1491 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1492 }
1493 /* In this case we might have to convert down from 4-byte native
1494 wchar_t to 2-byte unicode. */
1495 else if (maxchar < 65536) {
1496 assert(num_surrogates == 0 &&
1497 "FindMaxCharAndNumSurrogatePairs() messed up");
1498
Victor Stinner506f5922011-09-28 22:34:18 +02001499#if SIZEOF_WCHAR_T == 2
1500 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001501 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001502 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1503 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1504 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001505 _PyUnicode_UTF8(unicode) = NULL;
1506 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001507#else
1508 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001509 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001510 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001511 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001512 PyErr_NoMemory();
1513 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001514 }
Victor Stinner506f5922011-09-28 22:34:18 +02001515 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1516 _PyUnicode_WSTR(unicode), end,
1517 PyUnicode_2BYTE_DATA(unicode));
1518 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1519 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1520 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001521 _PyUnicode_UTF8(unicode) = NULL;
1522 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001523 PyObject_FREE(_PyUnicode_WSTR(unicode));
1524 _PyUnicode_WSTR(unicode) = NULL;
1525 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1526#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001527 }
1528 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1529 else {
1530#if SIZEOF_WCHAR_T == 2
1531 /* in case the native representation is 2-bytes, we need to allocate a
1532 new normalized 4-byte version. */
1533 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001534 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1535 PyErr_NoMemory();
1536 return -1;
1537 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001538 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1539 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyErr_NoMemory();
1541 return -1;
1542 }
1543 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1544 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001545 _PyUnicode_UTF8(unicode) = NULL;
1546 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001547 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1548 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001549 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 PyObject_FREE(_PyUnicode_WSTR(unicode));
1551 _PyUnicode_WSTR(unicode) = NULL;
1552 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1553#else
1554 assert(num_surrogates == 0);
1555
Victor Stinnerc3c74152011-10-02 20:39:55 +02001556 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001558 _PyUnicode_UTF8(unicode) = NULL;
1559 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1561#endif
1562 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1563 }
1564 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 return 0;
1567}
1568
Alexander Belopolsky40018472011-02-26 01:02:56 +00001569static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001570unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571{
Walter Dörwald16807132007-05-25 13:52:07 +00001572 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 case SSTATE_NOT_INTERNED:
1574 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001575
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 case SSTATE_INTERNED_MORTAL:
1577 /* revive dead object temporarily for DelItem */
1578 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001579 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 Py_FatalError(
1581 "deletion of interned string failed");
1582 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001583
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 case SSTATE_INTERNED_IMMORTAL:
1585 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001586
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 default:
1588 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001589 }
1590
Victor Stinner03490912011-10-03 23:45:12 +02001591 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001593 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001594 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001595 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1596 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001598 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001599}
1600
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001601#ifdef Py_DEBUG
1602static int
1603unicode_is_singleton(PyObject *unicode)
1604{
1605 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1606 if (unicode == unicode_empty)
1607 return 1;
1608 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1609 {
1610 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1611 if (ch < 256 && unicode_latin1[ch] == unicode)
1612 return 1;
1613 }
1614 return 0;
1615}
1616#endif
1617
Alexander Belopolsky40018472011-02-26 01:02:56 +00001618static int
Victor Stinner488fa492011-12-12 00:01:39 +01001619unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001620{
Victor Stinner488fa492011-12-12 00:01:39 +01001621 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001622 if (Py_REFCNT(unicode) != 1)
1623 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001624 if (_PyUnicode_HASH(unicode) != -1)
1625 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 if (PyUnicode_CHECK_INTERNED(unicode))
1627 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001628 if (!PyUnicode_CheckExact(unicode))
1629 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001630#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001631 /* singleton refcount is greater than 1 */
1632 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001633#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634 return 1;
1635}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636
Victor Stinnerfe226c02011-10-03 03:52:20 +02001637static int
1638unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1639{
1640 PyObject *unicode;
1641 Py_ssize_t old_length;
1642
1643 assert(p_unicode != NULL);
1644 unicode = *p_unicode;
1645
1646 assert(unicode != NULL);
1647 assert(PyUnicode_Check(unicode));
1648 assert(0 <= length);
1649
Victor Stinner910337b2011-10-03 03:20:16 +02001650 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001651 old_length = PyUnicode_WSTR_LENGTH(unicode);
1652 else
1653 old_length = PyUnicode_GET_LENGTH(unicode);
1654 if (old_length == length)
1655 return 0;
1656
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001657 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001658 _Py_INCREF_UNICODE_EMPTY();
1659 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001660 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 Py_DECREF(*p_unicode);
1662 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001663 return 0;
1664 }
1665
Victor Stinner488fa492011-12-12 00:01:39 +01001666 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001667 PyObject *copy = resize_copy(unicode, length);
1668 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 Py_DECREF(*p_unicode);
1671 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001672 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673 }
1674
Victor Stinnerfe226c02011-10-03 03:52:20 +02001675 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001676 PyObject *new_unicode = resize_compact(unicode, length);
1677 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001679 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001680 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001681 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001682 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001683}
1684
Alexander Belopolsky40018472011-02-26 01:02:56 +00001685int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001687{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001688 PyObject *unicode;
1689 if (p_unicode == NULL) {
1690 PyErr_BadInternalCall();
1691 return -1;
1692 }
1693 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001694 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695 {
1696 PyErr_BadInternalCall();
1697 return -1;
1698 }
1699 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001700}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001701
Victor Stinnerc5166102012-02-22 13:55:02 +01001702/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001703
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001704 WARNING: The function doesn't copy the terminating null character and
1705 doesn't check the maximum character (may write a latin1 character in an
1706 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001707static void
1708unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1709 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001710{
1711 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1712 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001713 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001714
1715 switch (kind) {
1716 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001717 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001718#ifdef Py_DEBUG
1719 if (PyUnicode_IS_ASCII(unicode)) {
1720 Py_UCS4 maxchar = ucs1lib_find_max_char(
1721 (const Py_UCS1*)str,
1722 (const Py_UCS1*)str + len);
1723 assert(maxchar < 128);
1724 }
1725#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001726 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001727 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 }
1729 case PyUnicode_2BYTE_KIND: {
1730 Py_UCS2 *start = (Py_UCS2 *)data + index;
1731 Py_UCS2 *ucs2 = start;
1732 assert(index <= PyUnicode_GET_LENGTH(unicode));
1733
Victor Stinner184252a2012-06-16 02:57:41 +02001734 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 *ucs2 = (Py_UCS2)*str;
1736
1737 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001738 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 }
1740 default: {
1741 Py_UCS4 *start = (Py_UCS4 *)data + index;
1742 Py_UCS4 *ucs4 = start;
1743 assert(kind == PyUnicode_4BYTE_KIND);
1744 assert(index <= PyUnicode_GET_LENGTH(unicode));
1745
Victor Stinner184252a2012-06-16 02:57:41 +02001746 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001747 *ucs4 = (Py_UCS4)*str;
1748
1749 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 }
1751 }
1752}
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754static PyObject*
1755get_latin1_char(unsigned char ch)
1756{
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001759 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 if (!unicode)
1761 return NULL;
1762 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001763 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 unicode_latin1[ch] = unicode;
1765 }
1766 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001767 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768}
1769
Victor Stinner985a82a2014-01-03 12:53:47 +01001770static PyObject*
1771unicode_char(Py_UCS4 ch)
1772{
1773 PyObject *unicode;
1774
1775 assert(ch <= MAX_UNICODE);
1776
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001777 if (ch < 256)
1778 return get_latin1_char(ch);
1779
Victor Stinner985a82a2014-01-03 12:53:47 +01001780 unicode = PyUnicode_New(1, ch);
1781 if (unicode == NULL)
1782 return NULL;
1783 switch (PyUnicode_KIND(unicode)) {
1784 case PyUnicode_1BYTE_KIND:
1785 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1786 break;
1787 case PyUnicode_2BYTE_KIND:
1788 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1789 break;
1790 default:
1791 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1792 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1793 }
1794 assert(_PyUnicode_CheckConsistency(unicode, 1));
1795 return unicode;
1796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001800{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001801 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 Py_UCS4 maxchar = 0;
1803 Py_ssize_t num_surrogates;
1804
1805 if (u == NULL)
1806 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808 /* If the Unicode data is known at construction time, we can apply
1809 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001812 if (size == 0)
1813 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 /* Single character Unicode objects in the Latin-1 range are
1816 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001817 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 return get_latin1_char((unsigned char)*u);
1819
1820 /* If not empty and not single character, copy the Unicode data
1821 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001822 if (find_maxchar_surrogates(u, u + size,
1823 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 return NULL;
1825
Victor Stinner8faf8212011-12-08 22:14:11 +01001826 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001827 if (!unicode)
1828 return NULL;
1829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 switch (PyUnicode_KIND(unicode)) {
1831 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001832 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1834 break;
1835 case PyUnicode_2BYTE_KIND:
1836#if Py_UNICODE_SIZE == 2
1837 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1838#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001839 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1841#endif
1842 break;
1843 case PyUnicode_4BYTE_KIND:
1844#if SIZEOF_WCHAR_T == 2
1845 /* This is the only case which has to process surrogates, thus
1846 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001847 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848#else
1849 assert(num_surrogates == 0);
1850 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1851#endif
1852 break;
1853 default:
1854 assert(0 && "Impossible state");
1855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001856
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001857 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001858}
1859
Alexander Belopolsky40018472011-02-26 01:02:56 +00001860PyObject *
1861PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001862{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001863 if (size < 0) {
1864 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001866 return NULL;
1867 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001868 if (u != NULL)
1869 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1870 else
1871 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874PyObject *
1875PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001876{
1877 size_t size = strlen(u);
1878 if (size > PY_SSIZE_T_MAX) {
1879 PyErr_SetString(PyExc_OverflowError, "input too long");
1880 return NULL;
1881 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001882 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883}
1884
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001885PyObject *
1886_PyUnicode_FromId(_Py_Identifier *id)
1887{
1888 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001889 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1890 strlen(id->string),
1891 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001892 if (!id->object)
1893 return NULL;
1894 PyUnicode_InternInPlace(&id->object);
1895 assert(!id->next);
1896 id->next = static_strings;
1897 static_strings = id;
1898 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001899 return id->object;
1900}
1901
1902void
1903_PyUnicode_ClearStaticStrings()
1904{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001905 _Py_Identifier *tmp, *s = static_strings;
1906 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001907 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001908 tmp = s->next;
1909 s->next = NULL;
1910 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001911 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001913}
1914
Benjamin Peterson0df54292012-03-26 14:50:32 -04001915/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917PyObject*
1918_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001919{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001921 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001922 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001923#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001924 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001925#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001926 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001927 }
Victor Stinner785938e2011-12-11 20:09:03 +01001928 unicode = PyUnicode_New(size, 127);
1929 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001930 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001931 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1932 assert(_PyUnicode_CheckConsistency(unicode, 1));
1933 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001934}
1935
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001936static Py_UCS4
1937kind_maxchar_limit(unsigned int kind)
1938{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001939 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001940 case PyUnicode_1BYTE_KIND:
1941 return 0x80;
1942 case PyUnicode_2BYTE_KIND:
1943 return 0x100;
1944 case PyUnicode_4BYTE_KIND:
1945 return 0x10000;
1946 default:
1947 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001948 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001949 }
1950}
1951
Victor Stinnere6abb482012-05-02 01:15:40 +02001952Py_LOCAL_INLINE(Py_UCS4)
1953align_maxchar(Py_UCS4 maxchar)
1954{
1955 if (maxchar <= 127)
1956 return 127;
1957 else if (maxchar <= 255)
1958 return 255;
1959 else if (maxchar <= 65535)
1960 return 65535;
1961 else
1962 return MAX_UNICODE;
1963}
1964
Victor Stinner702c7342011-10-05 13:50:52 +02001965static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001966_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001970
Serhiy Storchaka678db842013-01-26 12:16:36 +02001971 if (size == 0)
1972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001974 if (size == 1)
1975 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001978 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 if (!res)
1980 return NULL;
1981 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001982 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001984}
1985
Victor Stinnere57b1c02011-09-28 22:20:48 +02001986static PyObject*
1987_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988{
1989 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001990 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001991
Serhiy Storchaka678db842013-01-26 12:16:36 +02001992 if (size == 0)
1993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001995 if (size == 1)
1996 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001998 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001999 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 if (!res)
2001 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002004 else {
2005 _PyUnicode_CONVERT_BYTES(
2006 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2007 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002008 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 return res;
2010}
2011
Victor Stinnere57b1c02011-09-28 22:20:48 +02002012static PyObject*
2013_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014{
2015 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002016 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017
Serhiy Storchaka678db842013-01-26 12:16:36 +02002018 if (size == 0)
2019 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002020 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002021 if (size == 1)
2022 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002024 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002025 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 if (!res)
2027 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002028 if (max_char < 256)
2029 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2030 PyUnicode_1BYTE_DATA(res));
2031 else if (max_char < 0x10000)
2032 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2033 PyUnicode_2BYTE_DATA(res));
2034 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002036 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 return res;
2038}
2039
2040PyObject*
2041PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2042{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002043 if (size < 0) {
2044 PyErr_SetString(PyExc_ValueError, "size must be positive");
2045 return NULL;
2046 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002047 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002049 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002051 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002053 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002055 PyErr_SetString(PyExc_SystemError, "invalid kind");
2056 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058}
2059
Victor Stinnerece58de2012-04-23 23:36:38 +02002060Py_UCS4
2061_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2062{
2063 enum PyUnicode_Kind kind;
2064 void *startptr, *endptr;
2065
2066 assert(PyUnicode_IS_READY(unicode));
2067 assert(0 <= start);
2068 assert(end <= PyUnicode_GET_LENGTH(unicode));
2069 assert(start <= end);
2070
2071 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2072 return PyUnicode_MAX_CHAR_VALUE(unicode);
2073
2074 if (start == end)
2075 return 127;
2076
Victor Stinner94d558b2012-04-27 22:26:58 +02002077 if (PyUnicode_IS_ASCII(unicode))
2078 return 127;
2079
Victor Stinnerece58de2012-04-23 23:36:38 +02002080 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002081 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002082 endptr = (char *)startptr + end * kind;
2083 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 switch(kind) {
2085 case PyUnicode_1BYTE_KIND:
2086 return ucs1lib_find_max_char(startptr, endptr);
2087 case PyUnicode_2BYTE_KIND:
2088 return ucs2lib_find_max_char(startptr, endptr);
2089 case PyUnicode_4BYTE_KIND:
2090 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002091 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002092 assert(0);
2093 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002094 }
2095}
2096
Victor Stinner25a4b292011-10-06 12:31:55 +02002097/* Ensure that a string uses the most efficient storage, if it is not the
2098 case: create a new string with of the right kind. Write NULL into *p_unicode
2099 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002100static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002101unicode_adjust_maxchar(PyObject **p_unicode)
2102{
2103 PyObject *unicode, *copy;
2104 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002105 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002106 unsigned int kind;
2107
2108 assert(p_unicode != NULL);
2109 unicode = *p_unicode;
2110 assert(PyUnicode_IS_READY(unicode));
2111 if (PyUnicode_IS_ASCII(unicode))
2112 return;
2113
2114 len = PyUnicode_GET_LENGTH(unicode);
2115 kind = PyUnicode_KIND(unicode);
2116 if (kind == PyUnicode_1BYTE_KIND) {
2117 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002118 max_char = ucs1lib_find_max_char(u, u + len);
2119 if (max_char >= 128)
2120 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002121 }
2122 else if (kind == PyUnicode_2BYTE_KIND) {
2123 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002124 max_char = ucs2lib_find_max_char(u, u + len);
2125 if (max_char >= 256)
2126 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 }
2128 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002129 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002131 max_char = ucs4lib_find_max_char(u, u + len);
2132 if (max_char >= 0x10000)
2133 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002135 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002136 if (copy != NULL)
2137 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 Py_DECREF(unicode);
2139 *p_unicode = copy;
2140}
2141
Victor Stinner034f6cf2011-09-30 02:26:44 +02002142PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002143_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002144{
Victor Stinner87af4f22011-11-21 23:03:47 +01002145 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002147
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148 if (!PyUnicode_Check(unicode)) {
2149 PyErr_BadInternalCall();
2150 return NULL;
2151 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002152 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002154
Victor Stinner87af4f22011-11-21 23:03:47 +01002155 length = PyUnicode_GET_LENGTH(unicode);
2156 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157 if (!copy)
2158 return NULL;
2159 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2160
Victor Stinner87af4f22011-11-21 23:03:47 +01002161 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2162 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002163 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002164 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002165}
2166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002167
Victor Stinnerbc603d12011-10-02 01:00:40 +02002168/* Widen Unicode objects to larger buffers. Don't write terminating null
2169 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170
2171void*
2172_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2173{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 Py_ssize_t len;
2175 void *result;
2176 unsigned int skind;
2177
Benjamin Petersonbac79492012-01-14 13:34:47 -05002178 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002179 return NULL;
2180
2181 len = PyUnicode_GET_LENGTH(s);
2182 skind = PyUnicode_KIND(s);
2183 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002184 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 return NULL;
2186 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002187 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002188 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002189 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002190 if (!result)
2191 return PyErr_NoMemory();
2192 assert(skind == PyUnicode_1BYTE_KIND);
2193 _PyUnicode_CONVERT_BYTES(
2194 Py_UCS1, Py_UCS2,
2195 PyUnicode_1BYTE_DATA(s),
2196 PyUnicode_1BYTE_DATA(s) + len,
2197 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002200 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002201 if (!result)
2202 return PyErr_NoMemory();
2203 if (skind == PyUnicode_2BYTE_KIND) {
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS2, Py_UCS4,
2206 PyUnicode_2BYTE_DATA(s),
2207 PyUnicode_2BYTE_DATA(s) + len,
2208 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 else {
2211 assert(skind == PyUnicode_1BYTE_KIND);
2212 _PyUnicode_CONVERT_BYTES(
2213 Py_UCS1, Py_UCS4,
2214 PyUnicode_1BYTE_DATA(s),
2215 PyUnicode_1BYTE_DATA(s) + len,
2216 result);
2217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 default:
2220 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 }
Victor Stinner01698042011-10-04 00:04:26 +02002222 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 return NULL;
2224}
2225
2226static Py_UCS4*
2227as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
2230 int kind;
2231 void *data;
2232 Py_ssize_t len, targetlen;
2233 if (PyUnicode_READY(string) == -1)
2234 return NULL;
2235 kind = PyUnicode_KIND(string);
2236 data = PyUnicode_DATA(string);
2237 len = PyUnicode_GET_LENGTH(string);
2238 targetlen = len;
2239 if (copy_null)
2240 targetlen++;
2241 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002242 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002243 if (!target) {
2244 PyErr_NoMemory();
2245 return NULL;
2246 }
2247 }
2248 else {
2249 if (targetsize < targetlen) {
2250 PyErr_Format(PyExc_SystemError,
2251 "string is longer than the buffer");
2252 if (copy_null && 0 < targetsize)
2253 target[0] = 0;
2254 return NULL;
2255 }
2256 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002257 if (kind == PyUnicode_1BYTE_KIND) {
2258 Py_UCS1 *start = (Py_UCS1 *) data;
2259 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002261 else if (kind == PyUnicode_2BYTE_KIND) {
2262 Py_UCS2 *start = (Py_UCS2 *) data;
2263 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2264 }
2265 else {
2266 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002269 if (copy_null)
2270 target[len] = 0;
2271 return target;
2272}
2273
2274Py_UCS4*
2275PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2276 int copy_null)
2277{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002278 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002279 PyErr_BadInternalCall();
2280 return NULL;
2281 }
2282 return as_ucs4(string, target, targetsize, copy_null);
2283}
2284
2285Py_UCS4*
2286PyUnicode_AsUCS4Copy(PyObject *string)
2287{
2288 return as_ucs4(string, NULL, 0, 1);
2289}
2290
2291#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002292
Alexander Belopolsky40018472011-02-26 01:02:56 +00002293PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002294PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002295{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002296 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002297 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002298 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002299 PyErr_BadInternalCall();
2300 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002301 }
2302
Martin v. Löwis790465f2008-04-05 20:41:37 +00002303 if (size == -1) {
2304 size = wcslen(w);
2305 }
2306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002308}
2309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002311
Victor Stinner15a11362012-10-06 23:48:20 +02002312/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002313 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2314 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2315#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002316
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002317static int
2318unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2319 Py_ssize_t width, Py_ssize_t precision)
2320{
2321 Py_ssize_t length, fill, arglen;
2322 Py_UCS4 maxchar;
2323
2324 if (PyUnicode_READY(str) == -1)
2325 return -1;
2326
2327 length = PyUnicode_GET_LENGTH(str);
2328 if ((precision == -1 || precision >= length)
2329 && width <= length)
2330 return _PyUnicodeWriter_WriteStr(writer, str);
2331
2332 if (precision != -1)
2333 length = Py_MIN(precision, length);
2334
2335 arglen = Py_MAX(length, width);
2336 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2337 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2338 else
2339 maxchar = writer->maxchar;
2340
2341 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2342 return -1;
2343
2344 if (width > length) {
2345 fill = width - length;
2346 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2347 return -1;
2348 writer->pos += fill;
2349 }
2350
2351 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2352 str, 0, length);
2353 writer->pos += length;
2354 return 0;
2355}
2356
2357static int
2358unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2359 Py_ssize_t width, Py_ssize_t precision)
2360{
2361 /* UTF-8 */
2362 Py_ssize_t length;
2363 PyObject *unicode;
2364 int res;
2365
2366 length = strlen(str);
2367 if (precision != -1)
2368 length = Py_MIN(length, precision);
2369 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2370 if (unicode == NULL)
2371 return -1;
2372
2373 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2374 Py_DECREF(unicode);
2375 return res;
2376}
2377
Victor Stinner96865452011-03-01 23:44:09 +00002378static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002379unicode_fromformat_arg(_PyUnicodeWriter *writer,
2380 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002381{
Victor Stinnere215d962012-10-06 23:03:36 +02002382 const char *p;
2383 Py_ssize_t len;
2384 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002385 Py_ssize_t width;
2386 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002387 int longflag;
2388 int longlongflag;
2389 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002390 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002391
2392 p = f;
2393 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002394 zeropad = 0;
2395 if (*f == '0') {
2396 zeropad = 1;
2397 f++;
2398 }
Victor Stinner96865452011-03-01 23:44:09 +00002399
2400 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002401 width = -1;
2402 if (Py_ISDIGIT((unsigned)*f)) {
2403 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002404 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002405 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002406 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002407 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002408 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002409 return NULL;
2410 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002411 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002412 f++;
2413 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002414 }
2415 precision = -1;
2416 if (*f == '.') {
2417 f++;
2418 if (Py_ISDIGIT((unsigned)*f)) {
2419 precision = (*f - '0');
2420 f++;
2421 while (Py_ISDIGIT((unsigned)*f)) {
2422 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2423 PyErr_SetString(PyExc_ValueError,
2424 "precision too big");
2425 return NULL;
2426 }
2427 precision = (precision * 10) + (*f - '0');
2428 f++;
2429 }
2430 }
Victor Stinner96865452011-03-01 23:44:09 +00002431 if (*f == '%') {
2432 /* "%.3%s" => f points to "3" */
2433 f--;
2434 }
2435 }
2436 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002437 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002438 f--;
2439 }
Victor Stinner96865452011-03-01 23:44:09 +00002440
2441 /* Handle %ld, %lu, %lld and %llu. */
2442 longflag = 0;
2443 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002444 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002445 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002446 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002447 longflag = 1;
2448 ++f;
2449 }
2450#ifdef HAVE_LONG_LONG
2451 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002452 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002453 longlongflag = 1;
2454 f += 2;
2455 }
2456#endif
2457 }
2458 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002459 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002460 size_tflag = 1;
2461 ++f;
2462 }
Victor Stinnere215d962012-10-06 23:03:36 +02002463
2464 if (f[1] == '\0')
2465 writer->overallocate = 0;
2466
2467 switch (*f) {
2468 case 'c':
2469 {
2470 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002471 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002472 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002473 "character argument not in range(0x110000)");
2474 return NULL;
2475 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002476 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002477 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002478 break;
2479 }
2480
2481 case 'i':
2482 case 'd':
2483 case 'u':
2484 case 'x':
2485 {
2486 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002487 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002488 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002489
2490 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002491 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002492 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002493 va_arg(*vargs, unsigned long));
2494#ifdef HAVE_LONG_LONG
2495 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002496 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002497 va_arg(*vargs, unsigned PY_LONG_LONG));
2498#endif
2499 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002500 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002501 va_arg(*vargs, size_t));
2502 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002503 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002504 va_arg(*vargs, unsigned int));
2505 }
2506 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002507 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002508 }
2509 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002510 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002511 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002512 va_arg(*vargs, long));
2513#ifdef HAVE_LONG_LONG
2514 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002515 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002516 va_arg(*vargs, PY_LONG_LONG));
2517#endif
2518 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002519 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002520 va_arg(*vargs, Py_ssize_t));
2521 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002522 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002523 va_arg(*vargs, int));
2524 }
2525 assert(len >= 0);
2526
Victor Stinnere215d962012-10-06 23:03:36 +02002527 if (precision < len)
2528 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002529
2530 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002531 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2532 return NULL;
2533
Victor Stinnere215d962012-10-06 23:03:36 +02002534 if (width > precision) {
2535 Py_UCS4 fillchar;
2536 fill = width - precision;
2537 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002538 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2539 return NULL;
2540 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002541 }
Victor Stinner15a11362012-10-06 23:48:20 +02002542 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002543 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002544 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2545 return NULL;
2546 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002547 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002548
Victor Stinner4a587072013-11-19 12:54:53 +01002549 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2550 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002551 break;
2552 }
2553
2554 case 'p':
2555 {
2556 char number[MAX_LONG_LONG_CHARS];
2557
2558 len = sprintf(number, "%p", va_arg(*vargs, void*));
2559 assert(len >= 0);
2560
2561 /* %p is ill-defined: ensure leading 0x. */
2562 if (number[1] == 'X')
2563 number[1] = 'x';
2564 else if (number[1] != 'x') {
2565 memmove(number + 2, number,
2566 strlen(number) + 1);
2567 number[0] = '0';
2568 number[1] = 'x';
2569 len += 2;
2570 }
2571
Victor Stinner4a587072013-11-19 12:54:53 +01002572 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002573 return NULL;
2574 break;
2575 }
2576
2577 case 's':
2578 {
2579 /* UTF-8 */
2580 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002581 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002582 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002583 break;
2584 }
2585
2586 case 'U':
2587 {
2588 PyObject *obj = va_arg(*vargs, PyObject *);
2589 assert(obj && _PyUnicode_CHECK(obj));
2590
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002591 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002592 return NULL;
2593 break;
2594 }
2595
2596 case 'V':
2597 {
2598 PyObject *obj = va_arg(*vargs, PyObject *);
2599 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002600 if (obj) {
2601 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002602 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002603 return NULL;
2604 }
2605 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002606 assert(str != NULL);
2607 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002608 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002609 }
2610 break;
2611 }
2612
2613 case 'S':
2614 {
2615 PyObject *obj = va_arg(*vargs, PyObject *);
2616 PyObject *str;
2617 assert(obj);
2618 str = PyObject_Str(obj);
2619 if (!str)
2620 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002621 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002622 Py_DECREF(str);
2623 return NULL;
2624 }
2625 Py_DECREF(str);
2626 break;
2627 }
2628
2629 case 'R':
2630 {
2631 PyObject *obj = va_arg(*vargs, PyObject *);
2632 PyObject *repr;
2633 assert(obj);
2634 repr = PyObject_Repr(obj);
2635 if (!repr)
2636 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002637 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002638 Py_DECREF(repr);
2639 return NULL;
2640 }
2641 Py_DECREF(repr);
2642 break;
2643 }
2644
2645 case 'A':
2646 {
2647 PyObject *obj = va_arg(*vargs, PyObject *);
2648 PyObject *ascii;
2649 assert(obj);
2650 ascii = PyObject_ASCII(obj);
2651 if (!ascii)
2652 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002653 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002654 Py_DECREF(ascii);
2655 return NULL;
2656 }
2657 Py_DECREF(ascii);
2658 break;
2659 }
2660
2661 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002662 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002663 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002664 break;
2665
2666 default:
2667 /* if we stumble upon an unknown formatting code, copy the rest
2668 of the format string to the output string. (we cannot just
2669 skip the code, since there's no way to know what's in the
2670 argument list) */
2671 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002672 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002673 return NULL;
2674 f = p+len;
2675 return f;
2676 }
2677
2678 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002679 return f;
2680}
2681
Walter Dörwaldd2034312007-05-18 16:29:38 +00002682PyObject *
2683PyUnicode_FromFormatV(const char *format, va_list vargs)
2684{
Victor Stinnere215d962012-10-06 23:03:36 +02002685 va_list vargs2;
2686 const char *f;
2687 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002688
Victor Stinner8f674cc2013-04-17 23:02:17 +02002689 _PyUnicodeWriter_Init(&writer);
2690 writer.min_length = strlen(format) + 100;
2691 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002692
2693 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2694 Copy it to be able to pass a reference to a subfunction. */
2695 Py_VA_COPY(vargs2, vargs);
2696
2697 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002699 f = unicode_fromformat_arg(&writer, f, &vargs2);
2700 if (f == NULL)
2701 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002702 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002703 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002704 const char *p;
2705 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002706
Victor Stinnere215d962012-10-06 23:03:36 +02002707 p = f;
2708 do
2709 {
2710 if ((unsigned char)*p > 127) {
2711 PyErr_Format(PyExc_ValueError,
2712 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2713 "string, got a non-ASCII byte: 0x%02x",
2714 (unsigned char)*p);
2715 return NULL;
2716 }
2717 p++;
2718 }
2719 while (*p != '\0' && *p != '%');
2720 len = p - f;
2721
2722 if (*p == '\0')
2723 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002724
2725 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002726 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002727
2728 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002729 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002730 }
Victor Stinnere215d962012-10-06 23:03:36 +02002731 return _PyUnicodeWriter_Finish(&writer);
2732
2733 fail:
2734 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002736}
2737
Walter Dörwaldd2034312007-05-18 16:29:38 +00002738PyObject *
2739PyUnicode_FromFormat(const char *format, ...)
2740{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 PyObject* ret;
2742 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002743
2744#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002746#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002747 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002748#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002749 ret = PyUnicode_FromFormatV(format, vargs);
2750 va_end(vargs);
2751 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002752}
2753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002754#ifdef HAVE_WCHAR_H
2755
Victor Stinner5593d8a2010-10-02 11:11:27 +00002756/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2757 convert a Unicode object to a wide character string.
2758
Victor Stinnerd88d9832011-09-06 02:00:05 +02002759 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002760 character) required to convert the unicode object. Ignore size argument.
2761
Victor Stinnerd88d9832011-09-06 02:00:05 +02002762 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002763 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002764 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002765static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002766unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002767 wchar_t *w,
2768 Py_ssize_t size)
2769{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002770 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002771 const wchar_t *wstr;
2772
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002773 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774 if (wstr == NULL)
2775 return -1;
2776
Victor Stinner5593d8a2010-10-02 11:11:27 +00002777 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002778 if (size > res)
2779 size = res + 1;
2780 else
2781 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002782 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002783 return res;
2784 }
2785 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002787}
2788
2789Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002790PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002791 wchar_t *w,
2792 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002793{
2794 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002795 PyErr_BadInternalCall();
2796 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002797 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002798 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002799}
2800
Victor Stinner137c34c2010-09-29 10:25:54 +00002801wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002802PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002803 Py_ssize_t *size)
2804{
2805 wchar_t* buffer;
2806 Py_ssize_t buflen;
2807
2808 if (unicode == NULL) {
2809 PyErr_BadInternalCall();
2810 return NULL;
2811 }
2812
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002813 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002814 if (buflen == -1)
2815 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002816 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002817 if (buffer == NULL) {
2818 PyErr_NoMemory();
2819 return NULL;
2820 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002821 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002822 if (buflen == -1) {
2823 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002824 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002825 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002826 if (size != NULL)
2827 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002828 return buffer;
2829}
2830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002831#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832
Alexander Belopolsky40018472011-02-26 01:02:56 +00002833PyObject *
2834PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002835{
Victor Stinner8faf8212011-12-08 22:14:11 +01002836 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002837 PyErr_SetString(PyExc_ValueError,
2838 "chr() arg not in range(0x110000)");
2839 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002840 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002841
Victor Stinner985a82a2014-01-03 12:53:47 +01002842 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002843}
2844
Alexander Belopolsky40018472011-02-26 01:02:56 +00002845PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002846PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002847{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002848 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002849 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002850 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002851 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002852 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002853 Py_INCREF(obj);
2854 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002855 }
2856 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 /* For a Unicode subtype that's not a Unicode object,
2858 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002859 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002860 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002861 PyErr_Format(PyExc_TypeError,
2862 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002863 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002864 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002865}
2866
Alexander Belopolsky40018472011-02-26 01:02:56 +00002867PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002868PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002869 const char *encoding,
2870 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002871{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002872 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002873 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002874
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002876 PyErr_BadInternalCall();
2877 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002878 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002879
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002880 /* Decoding bytes objects is the most common case and should be fast */
2881 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002882 if (PyBytes_GET_SIZE(obj) == 0)
2883 _Py_RETURN_UNICODE_EMPTY();
2884 v = PyUnicode_Decode(
2885 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2886 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002887 return v;
2888 }
2889
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002890 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002891 PyErr_SetString(PyExc_TypeError,
2892 "decoding str is not supported");
2893 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002894 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002895
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002896 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2897 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2898 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002899 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002900 Py_TYPE(obj)->tp_name);
2901 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002902 }
Tim Petersced69f82003-09-16 20:30:58 +00002903
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002904 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002905 PyBuffer_Release(&buffer);
2906 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002908
Serhiy Storchaka05997252013-01-26 12:14:02 +02002909 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002910 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002911 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002912}
2913
Victor Stinner600d3be2010-06-10 12:00:55 +00002914/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002915 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2916 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002917int
2918_Py_normalize_encoding(const char *encoding,
2919 char *lower,
2920 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002922 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002923 char *l;
2924 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002925
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002926 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002927 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002928 if (lower_len < 6)
2929 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002930 strcpy(lower, "utf-8");
2931 return 1;
2932 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002933 e = encoding;
2934 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002935 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002936 while (*e) {
2937 if (l == l_end)
2938 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002939 if (Py_ISUPPER(*e)) {
2940 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002941 }
2942 else if (*e == '_') {
2943 *l++ = '-';
2944 e++;
2945 }
2946 else {
2947 *l++ = *e++;
2948 }
2949 }
2950 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002951 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002952}
2953
Alexander Belopolsky40018472011-02-26 01:02:56 +00002954PyObject *
2955PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002956 Py_ssize_t size,
2957 const char *encoding,
2958 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002959{
2960 PyObject *buffer = NULL, *unicode;
2961 Py_buffer info;
2962 char lower[11]; /* Enough for any encoding shortcut */
2963
Fred Drakee4315f52000-05-09 19:53:39 +00002964 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002965 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002966 if ((strcmp(lower, "utf-8") == 0) ||
2967 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002968 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002969 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002970 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01002971 (strcmp(lower, "iso-8859-1") == 0) ||
2972 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002973 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002974#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002975 else if (strcmp(lower, "mbcs") == 0)
2976 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002977#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002978 else if (strcmp(lower, "ascii") == 0)
2979 return PyUnicode_DecodeASCII(s, size, errors);
2980 else if (strcmp(lower, "utf-16") == 0)
2981 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2982 else if (strcmp(lower, "utf-32") == 0)
2983 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002985
2986 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002987 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002988 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002989 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002990 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002991 if (buffer == NULL)
2992 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10002993 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002994 if (unicode == NULL)
2995 goto onError;
2996 if (!PyUnicode_Check(unicode)) {
2997 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10002998 "'%.400s' decoder returned '%.400s' instead of 'str'; "
2999 "use codecs.decode() to decode to arbitrary types",
3000 encoding,
3001 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003002 Py_DECREF(unicode);
3003 goto onError;
3004 }
3005 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003006 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003007
Benjamin Peterson29060642009-01-31 22:14:21 +00003008 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009 Py_XDECREF(buffer);
3010 return NULL;
3011}
3012
Alexander Belopolsky40018472011-02-26 01:02:56 +00003013PyObject *
3014PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003015 const char *encoding,
3016 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003017{
3018 PyObject *v;
3019
3020 if (!PyUnicode_Check(unicode)) {
3021 PyErr_BadArgument();
3022 goto onError;
3023 }
3024
3025 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003027
3028 /* Decode via the codec registry */
3029 v = PyCodec_Decode(unicode, encoding, errors);
3030 if (v == NULL)
3031 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003032 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003033
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003035 return NULL;
3036}
3037
Alexander Belopolsky40018472011-02-26 01:02:56 +00003038PyObject *
3039PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003040 const char *encoding,
3041 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003042{
3043 PyObject *v;
3044
3045 if (!PyUnicode_Check(unicode)) {
3046 PyErr_BadArgument();
3047 goto onError;
3048 }
3049
3050 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003051 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003052
3053 /* Decode via the codec registry */
3054 v = PyCodec_Decode(unicode, encoding, errors);
3055 if (v == NULL)
3056 goto onError;
3057 if (!PyUnicode_Check(v)) {
3058 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003059 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3060 "use codecs.decode() to decode to arbitrary types",
3061 encoding,
3062 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003063 Py_DECREF(v);
3064 goto onError;
3065 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003066 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003067
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003069 return NULL;
3070}
3071
Alexander Belopolsky40018472011-02-26 01:02:56 +00003072PyObject *
3073PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003074 Py_ssize_t size,
3075 const char *encoding,
3076 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077{
3078 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003079
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080 unicode = PyUnicode_FromUnicode(s, size);
3081 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003082 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003083 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3084 Py_DECREF(unicode);
3085 return v;
3086}
3087
Alexander Belopolsky40018472011-02-26 01:02:56 +00003088PyObject *
3089PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003090 const char *encoding,
3091 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003092{
3093 PyObject *v;
3094
3095 if (!PyUnicode_Check(unicode)) {
3096 PyErr_BadArgument();
3097 goto onError;
3098 }
3099
3100 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003101 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003102
3103 /* Encode via the codec registry */
3104 v = PyCodec_Encode(unicode, encoding, errors);
3105 if (v == NULL)
3106 goto onError;
3107 return v;
3108
Benjamin Peterson29060642009-01-31 22:14:21 +00003109 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003110 return NULL;
3111}
3112
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003113static size_t
3114wcstombs_errorpos(const wchar_t *wstr)
3115{
3116 size_t len;
3117#if SIZEOF_WCHAR_T == 2
3118 wchar_t buf[3];
3119#else
3120 wchar_t buf[2];
3121#endif
3122 char outbuf[MB_LEN_MAX];
3123 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003124
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003125#if SIZEOF_WCHAR_T == 2
3126 buf[2] = 0;
3127#else
3128 buf[1] = 0;
3129#endif
3130 start = wstr;
3131 while (*wstr != L'\0')
3132 {
3133 previous = wstr;
3134#if SIZEOF_WCHAR_T == 2
3135 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3136 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3137 {
3138 buf[0] = wstr[0];
3139 buf[1] = wstr[1];
3140 wstr += 2;
3141 }
3142 else {
3143 buf[0] = *wstr;
3144 buf[1] = 0;
3145 wstr++;
3146 }
3147#else
3148 buf[0] = *wstr;
3149 wstr++;
3150#endif
3151 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003152 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003153 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003154 }
3155
3156 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003157 return 0;
3158}
3159
Victor Stinner1b579672011-12-17 05:47:23 +01003160static int
3161locale_error_handler(const char *errors, int *surrogateescape)
3162{
3163 if (errors == NULL) {
3164 *surrogateescape = 0;
3165 return 0;
3166 }
3167
3168 if (strcmp(errors, "strict") == 0) {
3169 *surrogateescape = 0;
3170 return 0;
3171 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003172 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003173 *surrogateescape = 1;
3174 return 0;
3175 }
3176 PyErr_Format(PyExc_ValueError,
3177 "only 'strict' and 'surrogateescape' error handlers "
3178 "are supported, not '%s'",
3179 errors);
3180 return -1;
3181}
3182
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003184PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003185{
3186 Py_ssize_t wlen, wlen2;
3187 wchar_t *wstr;
3188 PyObject *bytes = NULL;
3189 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003190 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003191 PyObject *exc;
3192 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003193 int surrogateescape;
3194
3195 if (locale_error_handler(errors, &surrogateescape) < 0)
3196 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003197
3198 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3199 if (wstr == NULL)
3200 return NULL;
3201
3202 wlen2 = wcslen(wstr);
3203 if (wlen2 != wlen) {
3204 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003205 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003206 return NULL;
3207 }
3208
3209 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003210 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003211 char *str;
3212
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003213 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003214 if (str == NULL) {
3215 if (error_pos == (size_t)-1) {
3216 PyErr_NoMemory();
3217 PyMem_Free(wstr);
3218 return NULL;
3219 }
3220 else {
3221 goto encode_error;
3222 }
3223 }
3224 PyMem_Free(wstr);
3225
3226 bytes = PyBytes_FromString(str);
3227 PyMem_Free(str);
3228 }
3229 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003230 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003231 size_t len, len2;
3232
3233 len = wcstombs(NULL, wstr, 0);
3234 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003235 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236 goto encode_error;
3237 }
3238
3239 bytes = PyBytes_FromStringAndSize(NULL, len);
3240 if (bytes == NULL) {
3241 PyMem_Free(wstr);
3242 return NULL;
3243 }
3244
3245 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3246 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003247 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003248 goto encode_error;
3249 }
3250 PyMem_Free(wstr);
3251 }
3252 return bytes;
3253
3254encode_error:
3255 errmsg = strerror(errno);
3256 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003257
3258 if (error_pos == (size_t)-1)
3259 error_pos = wcstombs_errorpos(wstr);
3260
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003261 PyMem_Free(wstr);
3262 Py_XDECREF(bytes);
3263
Victor Stinner2f197072011-12-17 07:08:30 +01003264 if (errmsg != NULL) {
3265 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003266 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003267 if (wstr != NULL) {
3268 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003269 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003270 } else
3271 errmsg = NULL;
3272 }
3273 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003274 reason = PyUnicode_FromString(
3275 "wcstombs() encountered an unencodable "
3276 "wide character");
3277 if (reason == NULL)
3278 return NULL;
3279
3280 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3281 "locale", unicode,
3282 (Py_ssize_t)error_pos,
3283 (Py_ssize_t)(error_pos+1),
3284 reason);
3285 Py_DECREF(reason);
3286 if (exc != NULL) {
3287 PyCodec_StrictErrors(exc);
3288 Py_XDECREF(exc);
3289 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 return NULL;
3291}
3292
Victor Stinnerad158722010-10-27 00:25:46 +00003293PyObject *
3294PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003295{
Victor Stinner99b95382011-07-04 14:23:54 +02003296#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003297 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003298#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003299 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003300#else
Victor Stinner793b5312011-04-27 00:24:21 +02003301 PyInterpreterState *interp = PyThreadState_GET()->interp;
3302 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3303 cannot use it to encode and decode filenames before it is loaded. Load
3304 the Python codec requires to encode at least its own filename. Use the C
3305 version of the locale codec until the codec registry is initialized and
3306 the Python codec is loaded.
3307
3308 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3309 cannot only rely on it: check also interp->fscodec_initialized for
3310 subinterpreters. */
3311 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003312 return PyUnicode_AsEncodedString(unicode,
3313 Py_FileSystemDefaultEncoding,
3314 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003315 }
3316 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003317 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003318 }
Victor Stinnerad158722010-10-27 00:25:46 +00003319#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320}
3321
Alexander Belopolsky40018472011-02-26 01:02:56 +00003322PyObject *
3323PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003324 const char *encoding,
3325 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003326{
3327 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003328 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003329
Guido van Rossumd57fd912000-03-10 22:53:23 +00003330 if (!PyUnicode_Check(unicode)) {
3331 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003332 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333 }
Fred Drakee4315f52000-05-09 19:53:39 +00003334
Fred Drakee4315f52000-05-09 19:53:39 +00003335 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003336 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003337 if ((strcmp(lower, "utf-8") == 0) ||
3338 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003339 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003340 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003342 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003343 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003344 }
Victor Stinner37296e82010-06-10 13:36:23 +00003345 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003346 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003347 (strcmp(lower, "iso-8859-1") == 0) ||
3348 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003349 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003350#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003351 else if (strcmp(lower, "mbcs") == 0)
3352 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003353#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003354 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003356 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003357
3358 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003359 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003360 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003361 return NULL;
3362
3363 /* The normal path */
3364 if (PyBytes_Check(v))
3365 return v;
3366
3367 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003368 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003369 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003370 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003371
3372 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003373 "encoder %s returned bytearray instead of bytes; "
3374 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003375 encoding);
3376 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 Py_DECREF(v);
3378 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003379 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003380
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003381 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3382 Py_DECREF(v);
3383 return b;
3384 }
3385
3386 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003387 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3388 "use codecs.encode() to encode to arbitrary types",
3389 encoding,
3390 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003391 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003392 return NULL;
3393}
3394
Alexander Belopolsky40018472011-02-26 01:02:56 +00003395PyObject *
3396PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003397 const char *encoding,
3398 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003399{
3400 PyObject *v;
3401
3402 if (!PyUnicode_Check(unicode)) {
3403 PyErr_BadArgument();
3404 goto onError;
3405 }
3406
3407 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003408 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003409
3410 /* Encode via the codec registry */
3411 v = PyCodec_Encode(unicode, encoding, errors);
3412 if (v == NULL)
3413 goto onError;
3414 if (!PyUnicode_Check(v)) {
3415 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003416 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3417 "use codecs.encode() to encode to arbitrary types",
3418 encoding,
3419 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003420 Py_DECREF(v);
3421 goto onError;
3422 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003423 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003424
Benjamin Peterson29060642009-01-31 22:14:21 +00003425 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003426 return NULL;
3427}
3428
Victor Stinner2f197072011-12-17 07:08:30 +01003429static size_t
3430mbstowcs_errorpos(const char *str, size_t len)
3431{
3432#ifdef HAVE_MBRTOWC
3433 const char *start = str;
3434 mbstate_t mbs;
3435 size_t converted;
3436 wchar_t ch;
3437
3438 memset(&mbs, 0, sizeof mbs);
3439 while (len)
3440 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003441 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003442 if (converted == 0)
3443 /* Reached end of string */
3444 break;
3445 if (converted == (size_t)-1 || converted == (size_t)-2) {
3446 /* Conversion error or incomplete character */
3447 return str - start;
3448 }
3449 else {
3450 str += converted;
3451 len -= converted;
3452 }
3453 }
3454 /* failed to find the undecodable byte sequence */
3455 return 0;
3456#endif
3457 return 0;
3458}
3459
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003460PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003461PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003462 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003463{
3464 wchar_t smallbuf[256];
3465 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3466 wchar_t *wstr;
3467 size_t wlen, wlen2;
3468 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003469 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003470 size_t error_pos;
3471 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003472 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3473 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003474
3475 if (locale_error_handler(errors, &surrogateescape) < 0)
3476 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003477
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003478 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3479 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480 return NULL;
3481 }
3482
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003483 if (surrogateescape) {
3484 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003485 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003486 if (wstr == NULL) {
3487 if (wlen == (size_t)-1)
3488 PyErr_NoMemory();
3489 else
3490 PyErr_SetFromErrno(PyExc_OSError);
3491 return NULL;
3492 }
3493
3494 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003495 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003496 }
3497 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003498 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499#ifndef HAVE_BROKEN_MBSTOWCS
3500 wlen = mbstowcs(NULL, str, 0);
3501#else
3502 wlen = len;
3503#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003504 if (wlen == (size_t)-1)
3505 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506 if (wlen+1 <= smallbuf_len) {
3507 wstr = smallbuf;
3508 }
3509 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003510 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003511 if (!wstr)
3512 return PyErr_NoMemory();
3513 }
3514
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003515 wlen2 = mbstowcs(wstr, str, wlen+1);
3516 if (wlen2 == (size_t)-1) {
3517 if (wstr != smallbuf)
3518 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003519 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003520 }
3521#ifdef HAVE_BROKEN_MBSTOWCS
3522 assert(wlen2 == wlen);
3523#endif
3524 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3525 if (wstr != smallbuf)
3526 PyMem_Free(wstr);
3527 }
3528 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003529
3530decode_error:
3531 errmsg = strerror(errno);
3532 assert(errmsg != NULL);
3533
3534 error_pos = mbstowcs_errorpos(str, len);
3535 if (errmsg != NULL) {
3536 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003537 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003538 if (wstr != NULL) {
3539 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003540 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003541 } else
3542 errmsg = NULL;
3543 }
3544 if (errmsg == NULL)
3545 reason = PyUnicode_FromString(
3546 "mbstowcs() encountered an invalid multibyte sequence");
3547 if (reason == NULL)
3548 return NULL;
3549
3550 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3551 "locale", str, len,
3552 (Py_ssize_t)error_pos,
3553 (Py_ssize_t)(error_pos+1),
3554 reason);
3555 Py_DECREF(reason);
3556 if (exc != NULL) {
3557 PyCodec_StrictErrors(exc);
3558 Py_XDECREF(exc);
3559 }
3560 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003561}
3562
3563PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003564PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003565{
3566 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003567 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003568}
3569
3570
3571PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003572PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003573 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003574 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3575}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003576
Christian Heimes5894ba72007-11-04 11:43:14 +00003577PyObject*
3578PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3579{
Victor Stinner99b95382011-07-04 14:23:54 +02003580#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003581 return PyUnicode_DecodeMBCS(s, size, NULL);
3582#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003583 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003584#else
Victor Stinner793b5312011-04-27 00:24:21 +02003585 PyInterpreterState *interp = PyThreadState_GET()->interp;
3586 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3587 cannot use it to encode and decode filenames before it is loaded. Load
3588 the Python codec requires to encode at least its own filename. Use the C
3589 version of the locale codec until the codec registry is initialized and
3590 the Python codec is loaded.
3591
3592 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3593 cannot only rely on it: check also interp->fscodec_initialized for
3594 subinterpreters. */
3595 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003596 return PyUnicode_Decode(s, size,
3597 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003598 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003599 }
3600 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003601 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003602 }
Victor Stinnerad158722010-10-27 00:25:46 +00003603#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003604}
3605
Martin v. Löwis011e8422009-05-05 04:43:17 +00003606
3607int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003608_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003609{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003610 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003611
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003612 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003613 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003614 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3615 PyUnicode_GET_LENGTH(str), '\0', 1);
3616 if (pos == -1)
3617 return 0;
3618 else
3619 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003620}
3621
Antoine Pitrou13348842012-01-29 18:36:34 +01003622int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003623PyUnicode_FSConverter(PyObject* arg, void* addr)
3624{
3625 PyObject *output = NULL;
3626 Py_ssize_t size;
3627 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003628 if (arg == NULL) {
3629 Py_DECREF(*(PyObject**)addr);
3630 return 1;
3631 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003632 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003633 output = arg;
3634 Py_INCREF(output);
3635 }
3636 else {
3637 arg = PyUnicode_FromObject(arg);
3638 if (!arg)
3639 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003640 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003641 Py_DECREF(arg);
3642 if (!output)
3643 return 0;
3644 if (!PyBytes_Check(output)) {
3645 Py_DECREF(output);
3646 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3647 return 0;
3648 }
3649 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003650 size = PyBytes_GET_SIZE(output);
3651 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003652 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003653 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003654 Py_DECREF(output);
3655 return 0;
3656 }
3657 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003658 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003659}
3660
3661
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003662int
3663PyUnicode_FSDecoder(PyObject* arg, void* addr)
3664{
3665 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003666 if (arg == NULL) {
3667 Py_DECREF(*(PyObject**)addr);
3668 return 1;
3669 }
3670 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003671 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003672 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003673 output = arg;
3674 Py_INCREF(output);
3675 }
3676 else {
3677 arg = PyBytes_FromObject(arg);
3678 if (!arg)
3679 return 0;
3680 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3681 PyBytes_GET_SIZE(arg));
3682 Py_DECREF(arg);
3683 if (!output)
3684 return 0;
3685 if (!PyUnicode_Check(output)) {
3686 Py_DECREF(output);
3687 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3688 return 0;
3689 }
3690 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003691 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003692 Py_DECREF(output);
3693 return 0;
3694 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003696 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003697 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003698 Py_DECREF(output);
3699 return 0;
3700 }
3701 *(PyObject**)addr = output;
3702 return Py_CLEANUP_SUPPORTED;
3703}
3704
3705
Martin v. Löwis5b222132007-06-10 09:51:05 +00003706char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003707PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003708{
Christian Heimesf3863112007-11-22 07:46:41 +00003709 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003710
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003711 if (!PyUnicode_Check(unicode)) {
3712 PyErr_BadArgument();
3713 return NULL;
3714 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003715 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003716 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003717
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003718 if (PyUnicode_UTF8(unicode) == NULL) {
3719 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003720 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3721 if (bytes == NULL)
3722 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003723 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3724 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003725 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726 Py_DECREF(bytes);
3727 return NULL;
3728 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003729 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3730 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3731 PyBytes_AS_STRING(bytes),
3732 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003733 Py_DECREF(bytes);
3734 }
3735
3736 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003737 *psize = PyUnicode_UTF8_LENGTH(unicode);
3738 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003739}
3740
3741char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003743{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003744 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3745}
3746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003747Py_UNICODE *
3748PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003750 const unsigned char *one_byte;
3751#if SIZEOF_WCHAR_T == 4
3752 const Py_UCS2 *two_bytes;
3753#else
3754 const Py_UCS4 *four_bytes;
3755 const Py_UCS4 *ucs4_end;
3756 Py_ssize_t num_surrogates;
3757#endif
3758 wchar_t *w;
3759 wchar_t *wchar_end;
3760
3761 if (!PyUnicode_Check(unicode)) {
3762 PyErr_BadArgument();
3763 return NULL;
3764 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003765 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003767 assert(_PyUnicode_KIND(unicode) != 0);
3768 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003770 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003772 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3773 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003774 num_surrogates = 0;
3775
3776 for (; four_bytes < ucs4_end; ++four_bytes) {
3777 if (*four_bytes > 0xFFFF)
3778 ++num_surrogates;
3779 }
3780
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003781 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3782 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3783 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003784 PyErr_NoMemory();
3785 return NULL;
3786 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003787 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003789 w = _PyUnicode_WSTR(unicode);
3790 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3791 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003792 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3793 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003794 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003796 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3797 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798 }
3799 else
3800 *w = *four_bytes;
3801
3802 if (w > wchar_end) {
3803 assert(0 && "Miscalculated string end");
3804 }
3805 }
3806 *w = 0;
3807#else
3808 /* sizeof(wchar_t) == 4 */
3809 Py_FatalError("Impossible unicode object state, wstr and str "
3810 "should share memory already.");
3811 return NULL;
3812#endif
3813 }
3814 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003815 if ((size_t)_PyUnicode_LENGTH(unicode) >
3816 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3817 PyErr_NoMemory();
3818 return NULL;
3819 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003820 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3821 (_PyUnicode_LENGTH(unicode) + 1));
3822 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823 PyErr_NoMemory();
3824 return NULL;
3825 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003826 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3827 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3828 w = _PyUnicode_WSTR(unicode);
3829 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003831 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3832 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833 for (; w < wchar_end; ++one_byte, ++w)
3834 *w = *one_byte;
3835 /* null-terminate the wstr */
3836 *w = 0;
3837 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003838 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 for (; w < wchar_end; ++two_bytes, ++w)
3842 *w = *two_bytes;
3843 /* null-terminate the wstr */
3844 *w = 0;
3845#else
3846 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003847 PyObject_FREE(_PyUnicode_WSTR(unicode));
3848 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 Py_FatalError("Impossible unicode object state, wstr "
3850 "and str should share memory already.");
3851 return NULL;
3852#endif
3853 }
3854 else {
3855 assert(0 && "This should never happen.");
3856 }
3857 }
3858 }
3859 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003860 *size = PyUnicode_WSTR_LENGTH(unicode);
3861 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003862}
3863
Alexander Belopolsky40018472011-02-26 01:02:56 +00003864Py_UNICODE *
3865PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003866{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003867 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003868}
3869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003870
Alexander Belopolsky40018472011-02-26 01:02:56 +00003871Py_ssize_t
3872PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003873{
3874 if (!PyUnicode_Check(unicode)) {
3875 PyErr_BadArgument();
3876 goto onError;
3877 }
3878 return PyUnicode_GET_SIZE(unicode);
3879
Benjamin Peterson29060642009-01-31 22:14:21 +00003880 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003881 return -1;
3882}
3883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884Py_ssize_t
3885PyUnicode_GetLength(PyObject *unicode)
3886{
Victor Stinner07621332012-06-16 04:53:46 +02003887 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003888 PyErr_BadArgument();
3889 return -1;
3890 }
Victor Stinner07621332012-06-16 04:53:46 +02003891 if (PyUnicode_READY(unicode) == -1)
3892 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 return PyUnicode_GET_LENGTH(unicode);
3894}
3895
3896Py_UCS4
3897PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3898{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003899 void *data;
3900 int kind;
3901
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003902 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3903 PyErr_BadArgument();
3904 return (Py_UCS4)-1;
3905 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003906 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003907 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return (Py_UCS4)-1;
3909 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003910 data = PyUnicode_DATA(unicode);
3911 kind = PyUnicode_KIND(unicode);
3912 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913}
3914
3915int
3916PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3917{
3918 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003919 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 return -1;
3921 }
Victor Stinner488fa492011-12-12 00:01:39 +01003922 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003923 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003924 PyErr_SetString(PyExc_IndexError, "string index out of range");
3925 return -1;
3926 }
Victor Stinner488fa492011-12-12 00:01:39 +01003927 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003928 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003929 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3930 PyErr_SetString(PyExc_ValueError, "character out of range");
3931 return -1;
3932 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003933 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3934 index, ch);
3935 return 0;
3936}
3937
Alexander Belopolsky40018472011-02-26 01:02:56 +00003938const char *
3939PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003940{
Victor Stinner42cb4622010-09-01 19:39:01 +00003941 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003942}
3943
Victor Stinner554f3f02010-06-16 23:33:54 +00003944/* create or adjust a UnicodeDecodeError */
3945static void
3946make_decode_exception(PyObject **exceptionObject,
3947 const char *encoding,
3948 const char *input, Py_ssize_t length,
3949 Py_ssize_t startpos, Py_ssize_t endpos,
3950 const char *reason)
3951{
3952 if (*exceptionObject == NULL) {
3953 *exceptionObject = PyUnicodeDecodeError_Create(
3954 encoding, input, length, startpos, endpos, reason);
3955 }
3956 else {
3957 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3958 goto onError;
3959 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3960 goto onError;
3961 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3962 goto onError;
3963 }
3964 return;
3965
3966onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003967 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003968}
3969
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003970#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003971/* error handling callback helper:
3972 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003973 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003974 and adjust various state variables.
3975 return 0 on success, -1 on error
3976*/
3977
Alexander Belopolsky40018472011-02-26 01:02:56 +00003978static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003979unicode_decode_call_errorhandler_wchar(
3980 const char *errors, PyObject **errorHandler,
3981 const char *encoding, const char *reason,
3982 const char **input, const char **inend, Py_ssize_t *startinpos,
3983 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3984 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003985{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003986 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003987
3988 PyObject *restuple = NULL;
3989 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003990 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003991 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003992 Py_ssize_t requiredsize;
3993 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003994 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003995 wchar_t *repwstr;
3996 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003997
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003998 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3999 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004000
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004001 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004002 *errorHandler = PyCodec_LookupError(errors);
4003 if (*errorHandler == NULL)
4004 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004005 }
4006
Victor Stinner554f3f02010-06-16 23:33:54 +00004007 make_decode_exception(exceptionObject,
4008 encoding,
4009 *input, *inend - *input,
4010 *startinpos, *endinpos,
4011 reason);
4012 if (*exceptionObject == NULL)
4013 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014
4015 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4016 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004017 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004018 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004019 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004020 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004021 }
4022 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004023 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004024
4025 /* Copy back the bytes variables, which might have been modified by the
4026 callback */
4027 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4028 if (!inputobj)
4029 goto onError;
4030 if (!PyBytes_Check(inputobj)) {
4031 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4032 }
4033 *input = PyBytes_AS_STRING(inputobj);
4034 insize = PyBytes_GET_SIZE(inputobj);
4035 *inend = *input + insize;
4036 /* we can DECREF safely, as the exception has another reference,
4037 so the object won't go away. */
4038 Py_DECREF(inputobj);
4039
4040 if (newpos<0)
4041 newpos = insize+newpos;
4042 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004043 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004044 goto onError;
4045 }
4046
4047 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4048 if (repwstr == NULL)
4049 goto onError;
4050 /* need more space? (at least enough for what we
4051 have+the replacement+the rest of the string (starting
4052 at the new input position), so we won't have to check space
4053 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004054 requiredsize = *outpos;
4055 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4056 goto overflow;
4057 requiredsize += repwlen;
4058 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4059 goto overflow;
4060 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004061 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004062 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004063 requiredsize = 2*outsize;
4064 if (unicode_resize(output, requiredsize) < 0)
4065 goto onError;
4066 }
4067 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4068 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004069 *endinpos = newpos;
4070 *inptr = *input + newpos;
4071
4072 /* we made it! */
4073 Py_XDECREF(restuple);
4074 return 0;
4075
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004076 overflow:
4077 PyErr_SetString(PyExc_OverflowError,
4078 "decoded result is too long for a Python string");
4079
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004080 onError:
4081 Py_XDECREF(restuple);
4082 return -1;
4083}
4084#endif /* HAVE_MBCS */
4085
4086static int
4087unicode_decode_call_errorhandler_writer(
4088 const char *errors, PyObject **errorHandler,
4089 const char *encoding, const char *reason,
4090 const char **input, const char **inend, Py_ssize_t *startinpos,
4091 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4092 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4093{
4094 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4095
4096 PyObject *restuple = NULL;
4097 PyObject *repunicode = NULL;
4098 Py_ssize_t insize;
4099 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004100 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004101 PyObject *inputobj = NULL;
4102
4103 if (*errorHandler == NULL) {
4104 *errorHandler = PyCodec_LookupError(errors);
4105 if (*errorHandler == NULL)
4106 goto onError;
4107 }
4108
4109 make_decode_exception(exceptionObject,
4110 encoding,
4111 *input, *inend - *input,
4112 *startinpos, *endinpos,
4113 reason);
4114 if (*exceptionObject == NULL)
4115 goto onError;
4116
4117 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4118 if (restuple == NULL)
4119 goto onError;
4120 if (!PyTuple_Check(restuple)) {
4121 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4122 goto onError;
4123 }
4124 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004125 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004126
4127 /* Copy back the bytes variables, which might have been modified by the
4128 callback */
4129 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4130 if (!inputobj)
4131 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004132 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004133 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004134 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004135 *input = PyBytes_AS_STRING(inputobj);
4136 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004137 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004138 /* we can DECREF safely, as the exception has another reference,
4139 so the object won't go away. */
4140 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004141
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004142 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004143 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004144 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004145 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004146 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004147 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004148
Victor Stinner8f674cc2013-04-17 23:02:17 +02004149 if (PyUnicode_READY(repunicode) < 0)
4150 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004151 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004152 if (replen > 1) {
4153 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004154 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004155 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4156 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4157 goto onError;
4158 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004159 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004160 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004161
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004162 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004163 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004164
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004166 Py_XDECREF(restuple);
4167 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004168
Benjamin Peterson29060642009-01-31 22:14:21 +00004169 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004170 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004171 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172}
4173
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004174/* --- UTF-7 Codec -------------------------------------------------------- */
4175
Antoine Pitrou244651a2009-05-04 18:56:13 +00004176/* See RFC2152 for details. We encode conservatively and decode liberally. */
4177
4178/* Three simple macros defining base-64. */
4179
4180/* Is c a base-64 character? */
4181
4182#define IS_BASE64(c) \
4183 (((c) >= 'A' && (c) <= 'Z') || \
4184 ((c) >= 'a' && (c) <= 'z') || \
4185 ((c) >= '0' && (c) <= '9') || \
4186 (c) == '+' || (c) == '/')
4187
4188/* given that c is a base-64 character, what is its base-64 value? */
4189
4190#define FROM_BASE64(c) \
4191 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4192 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4193 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4194 (c) == '+' ? 62 : 63)
4195
4196/* What is the base-64 character of the bottom 6 bits of n? */
4197
4198#define TO_BASE64(n) \
4199 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4200
4201/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4202 * decoded as itself. We are permissive on decoding; the only ASCII
4203 * byte not decoding to itself is the + which begins a base64
4204 * string. */
4205
4206#define DECODE_DIRECT(c) \
4207 ((c) <= 127 && (c) != '+')
4208
4209/* The UTF-7 encoder treats ASCII characters differently according to
4210 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4211 * the above). See RFC2152. This array identifies these different
4212 * sets:
4213 * 0 : "Set D"
4214 * alphanumeric and '(),-./:?
4215 * 1 : "Set O"
4216 * !"#$%&*;<=>@[]^_`{|}
4217 * 2 : "whitespace"
4218 * ht nl cr sp
4219 * 3 : special (must be base64 encoded)
4220 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4221 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004222
Tim Petersced69f82003-09-16 20:30:58 +00004223static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004224char utf7_category[128] = {
4225/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4226 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4227/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4228 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4229/* sp ! " # $ % & ' ( ) * + , - . / */
4230 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4231/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4232 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4233/* @ A B C D E F G H I J K L M N O */
4234 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4235/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4236 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4237/* ` a b c d e f g h i j k l m n o */
4238 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4239/* p q r s t u v w x y z { | } ~ del */
4240 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004241};
4242
Antoine Pitrou244651a2009-05-04 18:56:13 +00004243/* ENCODE_DIRECT: this character should be encoded as itself. The
4244 * answer depends on whether we are encoding set O as itself, and also
4245 * on whether we are encoding whitespace as itself. RFC2152 makes it
4246 * clear that the answers to these questions vary between
4247 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004248
Antoine Pitrou244651a2009-05-04 18:56:13 +00004249#define ENCODE_DIRECT(c, directO, directWS) \
4250 ((c) < 128 && (c) > 0 && \
4251 ((utf7_category[(c)] == 0) || \
4252 (directWS && (utf7_category[(c)] == 2)) || \
4253 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004254
Alexander Belopolsky40018472011-02-26 01:02:56 +00004255PyObject *
4256PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004257 Py_ssize_t size,
4258 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004259{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004260 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4261}
4262
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263/* The decoder. The only state we preserve is our read position,
4264 * i.e. how many characters we have consumed. So if we end in the
4265 * middle of a shift sequence we have to back off the read position
4266 * and the output to the beginning of the sequence, otherwise we lose
4267 * all the shift state (seen bits, number of bits seen, high
4268 * surrogate). */
4269
Alexander Belopolsky40018472011-02-26 01:02:56 +00004270PyObject *
4271PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004272 Py_ssize_t size,
4273 const char *errors,
4274 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004275{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004276 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004277 Py_ssize_t startinpos;
4278 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004279 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004280 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281 const char *errmsg = "";
4282 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004283 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004284 unsigned int base64bits = 0;
4285 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004286 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004287 PyObject *errorHandler = NULL;
4288 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 if (size == 0) {
4291 if (consumed)
4292 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004293 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004294 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004295
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004296 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004297 _PyUnicodeWriter_Init(&writer);
4298 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004299
4300 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004301 e = s + size;
4302
4303 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004304 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004305 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004306 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004307
Antoine Pitrou244651a2009-05-04 18:56:13 +00004308 if (inShift) { /* in a base-64 section */
4309 if (IS_BASE64(ch)) { /* consume a base-64 character */
4310 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4311 base64bits += 6;
4312 s++;
4313 if (base64bits >= 16) {
4314 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004315 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004316 base64bits -= 16;
4317 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004318 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004319 if (surrogate) {
4320 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004321 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4322 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004323 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004324 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004326 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 }
4328 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004329 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004330 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004331 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004332 }
4333 }
Victor Stinner551ac952011-11-29 22:58:13 +01004334 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004335 /* first surrogate */
4336 surrogate = outCh;
4337 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004338 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004339 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004340 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004341 }
4342 }
4343 }
4344 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345 inShift = 0;
4346 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004348 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004349 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004350 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004351 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 if (base64bits > 0) { /* left-over bits */
4353 if (base64bits >= 6) {
4354 /* We've seen at least one base-64 character */
4355 errmsg = "partial character in shift sequence";
4356 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004357 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 else {
4359 /* Some bits remain; they should be zero */
4360 if (base64buffer != 0) {
4361 errmsg = "non-zero padding bits in shift sequence";
4362 goto utf7Error;
4363 }
4364 }
4365 }
4366 if (ch != '-') {
4367 /* '-' is absorbed; other terminating
4368 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004369 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004370 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004372 }
4373 }
4374 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004375 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 s++; /* consume '+' */
4377 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004379 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004380 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 }
4382 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004384 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004386 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
4388 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004391 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004392 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004393 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004394 else {
4395 startinpos = s-starts;
4396 s++;
4397 errmsg = "unexpected special character";
4398 goto utf7Error;
4399 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004401utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004402 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004403 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 errors, &errorHandler,
4405 "utf7", errmsg,
4406 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004407 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004408 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 }
4410
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 /* end of string */
4412
4413 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4414 /* if we're in an inconsistent state, that's an error */
4415 if (surrogate ||
4416 (base64bits >= 6) ||
4417 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004419 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 errors, &errorHandler,
4421 "utf7", "unterminated shift sequence",
4422 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004423 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 goto onError;
4425 if (s < e)
4426 goto restart;
4427 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004428 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004429
4430 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004431 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004433 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004434 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004435 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004436 writer.kind, writer.data, shiftOutStart);
4437 Py_XDECREF(errorHandler);
4438 Py_XDECREF(exc);
4439 _PyUnicodeWriter_Dealloc(&writer);
4440 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004441 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004442 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 }
4444 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004445 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004447 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004448
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004449 Py_XDECREF(errorHandler);
4450 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004451 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452
Benjamin Peterson29060642009-01-31 22:14:21 +00004453 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004454 Py_XDECREF(errorHandler);
4455 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004456 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 return NULL;
4458}
4459
4460
Alexander Belopolsky40018472011-02-26 01:02:56 +00004461PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004462_PyUnicode_EncodeUTF7(PyObject *str,
4463 int base64SetO,
4464 int base64WhiteSpace,
4465 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004467 int kind;
4468 void *data;
4469 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004470 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004472 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 unsigned int base64bits = 0;
4474 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004475 char * out;
4476 char * start;
4477
Benjamin Petersonbac79492012-01-14 13:34:47 -05004478 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004479 return NULL;
4480 kind = PyUnicode_KIND(str);
4481 data = PyUnicode_DATA(str);
4482 len = PyUnicode_GET_LENGTH(str);
4483
4484 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004487 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004488 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004489 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004490 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004491 if (v == NULL)
4492 return NULL;
4493
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004494 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004496 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 if (inShift) {
4499 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4500 /* shifting out */
4501 if (base64bits) { /* output remaining bits */
4502 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4503 base64buffer = 0;
4504 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 }
4506 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 /* Characters not in the BASE64 set implicitly unshift the sequence
4508 so no '-' is required, except if the character is itself a '-' */
4509 if (IS_BASE64(ch) || ch == '-') {
4510 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 *out++ = (char) ch;
4513 }
4514 else {
4515 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004516 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518 else { /* not in a shift sequence */
4519 if (ch == '+') {
4520 *out++ = '+';
4521 *out++ = '-';
4522 }
4523 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4524 *out++ = (char) ch;
4525 }
4526 else {
4527 *out++ = '+';
4528 inShift = 1;
4529 goto encode_char;
4530 }
4531 }
4532 continue;
4533encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004535 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004536
Antoine Pitrou244651a2009-05-04 18:56:13 +00004537 /* code first surrogate */
4538 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004539 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004540 while (base64bits >= 6) {
4541 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4542 base64bits -= 6;
4543 }
4544 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004545 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004546 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 base64bits += 16;
4548 base64buffer = (base64buffer << 16) | ch;
4549 while (base64bits >= 6) {
4550 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4551 base64bits -= 6;
4552 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004553 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 if (base64bits)
4555 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4556 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004557 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004558 if (_PyBytes_Resize(&v, out - start) < 0)
4559 return NULL;
4560 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004561}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004562PyObject *
4563PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4564 Py_ssize_t size,
4565 int base64SetO,
4566 int base64WhiteSpace,
4567 const char *errors)
4568{
4569 PyObject *result;
4570 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4571 if (tmp == NULL)
4572 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004573 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004574 base64WhiteSpace, errors);
4575 Py_DECREF(tmp);
4576 return result;
4577}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004578
Antoine Pitrou244651a2009-05-04 18:56:13 +00004579#undef IS_BASE64
4580#undef FROM_BASE64
4581#undef TO_BASE64
4582#undef DECODE_DIRECT
4583#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584
Guido van Rossumd57fd912000-03-10 22:53:23 +00004585/* --- UTF-8 Codec -------------------------------------------------------- */
4586
Alexander Belopolsky40018472011-02-26 01:02:56 +00004587PyObject *
4588PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004589 Py_ssize_t size,
4590 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004591{
Walter Dörwald69652032004-09-07 20:24:22 +00004592 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4593}
4594
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004595#include "stringlib/asciilib.h"
4596#include "stringlib/codecs.h"
4597#include "stringlib/undef.h"
4598
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004599#include "stringlib/ucs1lib.h"
4600#include "stringlib/codecs.h"
4601#include "stringlib/undef.h"
4602
4603#include "stringlib/ucs2lib.h"
4604#include "stringlib/codecs.h"
4605#include "stringlib/undef.h"
4606
4607#include "stringlib/ucs4lib.h"
4608#include "stringlib/codecs.h"
4609#include "stringlib/undef.h"
4610
Antoine Pitrouab868312009-01-10 15:40:25 +00004611/* Mask to quickly check whether a C 'long' contains a
4612 non-ASCII, UTF8-encoded char. */
4613#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004614# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004615#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004616# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004617#else
4618# error C 'long' size should be either 4 or 8!
4619#endif
4620
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004621static Py_ssize_t
4622ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004623{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004624 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004625 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004626
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004627 /*
4628 * Issue #17237: m68k is a bit different from most architectures in
4629 * that objects do not use "natural alignment" - for example, int and
4630 * long are only aligned at 2-byte boundaries. Therefore the assert()
4631 * won't work; also, tests have shown that skipping the "optimised
4632 * version" will even speed up m68k.
4633 */
4634#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004635#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004636 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4637 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004638 /* Fast path, see in STRINGLIB(utf8_decode) for
4639 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004640 /* Help allocation */
4641 const char *_p = p;
4642 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004643 while (_p < aligned_end) {
4644 unsigned long value = *(const unsigned long *) _p;
4645 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004646 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004647 *((unsigned long *)q) = value;
4648 _p += SIZEOF_LONG;
4649 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004650 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651 p = _p;
4652 while (p < end) {
4653 if ((unsigned char)*p & 0x80)
4654 break;
4655 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004656 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004658 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004659#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004660#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661 while (p < end) {
4662 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4663 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004664 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004665 /* Help allocation */
4666 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 while (_p < aligned_end) {
4668 unsigned long value = *(unsigned long *) _p;
4669 if (value & ASCII_CHAR_MASK)
4670 break;
4671 _p += SIZEOF_LONG;
4672 }
4673 p = _p;
4674 if (_p == end)
4675 break;
4676 }
4677 if ((unsigned char)*p & 0x80)
4678 break;
4679 ++p;
4680 }
4681 memcpy(dest, start, p - start);
4682 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004683}
Antoine Pitrouab868312009-01-10 15:40:25 +00004684
Victor Stinner785938e2011-12-11 20:09:03 +01004685PyObject *
4686PyUnicode_DecodeUTF8Stateful(const char *s,
4687 Py_ssize_t size,
4688 const char *errors,
4689 Py_ssize_t *consumed)
4690{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004691 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004692 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004693 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694
4695 Py_ssize_t startinpos;
4696 Py_ssize_t endinpos;
4697 const char *errmsg = "";
4698 PyObject *errorHandler = NULL;
4699 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004700
4701 if (size == 0) {
4702 if (consumed)
4703 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004704 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004705 }
4706
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004707 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4708 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004709 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004710 *consumed = 1;
4711 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004712 }
4713
Victor Stinner8f674cc2013-04-17 23:02:17 +02004714 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004715 writer.min_length = size;
4716 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004717 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004718
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 writer.pos = ascii_decode(s, end, writer.data);
4720 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004721 while (s < end) {
4722 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004723 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004725 if (PyUnicode_IS_ASCII(writer.buffer))
4726 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004729 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004730 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 } else {
4732 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004733 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734 }
4735
4736 switch (ch) {
4737 case 0:
4738 if (s == end || consumed)
4739 goto End;
4740 errmsg = "unexpected end of data";
4741 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004742 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004743 break;
4744 case 1:
4745 errmsg = "invalid start byte";
4746 startinpos = s - starts;
4747 endinpos = startinpos + 1;
4748 break;
4749 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004750 case 3:
4751 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004752 errmsg = "invalid continuation byte";
4753 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004754 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 break;
4756 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004757 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 goto onError;
4759 continue;
4760 }
4761
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 errors, &errorHandler,
4764 "utf-8", errmsg,
4765 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004766 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004768 }
4769
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004770End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 if (consumed)
4772 *consumed = s - starts;
4773
4774 Py_XDECREF(errorHandler);
4775 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004776 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777
4778onError:
4779 Py_XDECREF(errorHandler);
4780 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004781 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004782 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004783}
4784
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004785#ifdef __APPLE__
4786
4787/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004788 used to decode the command line arguments on Mac OS X.
4789
4790 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004791 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004792
4793wchar_t*
4794_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4795{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004796 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004797 wchar_t *unicode;
4798 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004799
4800 /* Note: size will always be longer than the resulting Unicode
4801 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004802 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004803 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004804 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004805 if (!unicode)
4806 return NULL;
4807
4808 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004809 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004810 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004811 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004812 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004813#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004815#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004816 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 if (ch > 0xFF) {
4819#if SIZEOF_WCHAR_T == 4
4820 assert(0);
4821#else
4822 assert(Py_UNICODE_IS_SURROGATE(ch));
4823 /* compute and append the two surrogates: */
4824 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4825 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4826#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004827 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 else {
4829 if (!ch && s == e)
4830 break;
4831 /* surrogateescape */
4832 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4833 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 return unicode;
4837}
4838
4839#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004841/* Primary internal function which creates utf8 encoded bytes objects.
4842
4843 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004844 and allocate exactly as much space needed at the end. Else allocate the
4845 maximum possible needed (4 result bytes per Unicode character), and return
4846 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004847*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004848PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004849_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004850{
Victor Stinner6099a032011-12-18 14:22:26 +01004851 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 void *data;
4853 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004855 if (!PyUnicode_Check(unicode)) {
4856 PyErr_BadArgument();
4857 return NULL;
4858 }
4859
4860 if (PyUnicode_READY(unicode) == -1)
4861 return NULL;
4862
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004863 if (PyUnicode_UTF8(unicode))
4864 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4865 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004866
4867 kind = PyUnicode_KIND(unicode);
4868 data = PyUnicode_DATA(unicode);
4869 size = PyUnicode_GET_LENGTH(unicode);
4870
Benjamin Petersonead6b532011-12-20 17:23:42 -06004871 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004872 default:
4873 assert(0);
4874 case PyUnicode_1BYTE_KIND:
4875 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4876 assert(!PyUnicode_IS_ASCII(unicode));
4877 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4878 case PyUnicode_2BYTE_KIND:
4879 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4880 case PyUnicode_4BYTE_KIND:
4881 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004882 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004883}
4884
Alexander Belopolsky40018472011-02-26 01:02:56 +00004885PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4887 Py_ssize_t size,
4888 const char *errors)
4889{
4890 PyObject *v, *unicode;
4891
4892 unicode = PyUnicode_FromUnicode(s, size);
4893 if (unicode == NULL)
4894 return NULL;
4895 v = _PyUnicode_AsUTF8String(unicode, errors);
4896 Py_DECREF(unicode);
4897 return v;
4898}
4899
4900PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004901PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004903 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904}
4905
Walter Dörwald41980ca2007-08-16 21:55:45 +00004906/* --- UTF-32 Codec ------------------------------------------------------- */
4907
4908PyObject *
4909PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004910 Py_ssize_t size,
4911 const char *errors,
4912 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004913{
4914 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4915}
4916
4917PyObject *
4918PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004919 Py_ssize_t size,
4920 const char *errors,
4921 int *byteorder,
4922 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004923{
4924 const char *starts = s;
4925 Py_ssize_t startinpos;
4926 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004927 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004928 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004929 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004930 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004932 PyObject *errorHandler = NULL;
4933 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004934
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935 q = (unsigned char *)s;
4936 e = q + size;
4937
4938 if (byteorder)
4939 bo = *byteorder;
4940
4941 /* Check for BOM marks (U+FEFF) in the input and adjust current
4942 byte order setting accordingly. In native mode, the leading BOM
4943 mark is skipped, in all other modes, it is copied to the output
4944 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004945 if (bo == 0 && size >= 4) {
4946 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4947 if (bom == 0x0000FEFF) {
4948 bo = -1;
4949 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004951 else if (bom == 0xFFFE0000) {
4952 bo = 1;
4953 q += 4;
4954 }
4955 if (byteorder)
4956 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004957 }
4958
Victor Stinnere64322e2012-10-30 23:12:47 +01004959 if (q == e) {
4960 if (consumed)
4961 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004962 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963 }
4964
Victor Stinnere64322e2012-10-30 23:12:47 +01004965#ifdef WORDS_BIGENDIAN
4966 le = bo < 0;
4967#else
4968 le = bo <= 0;
4969#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004970 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004971
Victor Stinner8f674cc2013-04-17 23:02:17 +02004972 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004973 writer.min_length = (e - q + 3) / 4;
4974 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004975 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004976
Victor Stinnere64322e2012-10-30 23:12:47 +01004977 while (1) {
4978 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004979 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004980
Victor Stinnere64322e2012-10-30 23:12:47 +01004981 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004982 enum PyUnicode_Kind kind = writer.kind;
4983 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004984 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004985 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004986 if (le) {
4987 do {
4988 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4989 if (ch > maxch)
4990 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004991 if (kind != PyUnicode_1BYTE_KIND &&
4992 Py_UNICODE_IS_SURROGATE(ch))
4993 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004994 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004995 q += 4;
4996 } while (q <= last);
4997 }
4998 else {
4999 do {
5000 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5001 if (ch > maxch)
5002 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005003 if (kind != PyUnicode_1BYTE_KIND &&
5004 Py_UNICODE_IS_SURROGATE(ch))
5005 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005006 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005007 q += 4;
5008 } while (q <= last);
5009 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005010 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005011 }
5012
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005013 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005014 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005015 startinpos = ((const char *)q) - starts;
5016 endinpos = startinpos + 4;
5017 }
5018 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005019 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005022 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005023 startinpos = ((const char *)q) - starts;
5024 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005026 else {
5027 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005028 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005029 goto onError;
5030 q += 4;
5031 continue;
5032 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005033 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005034 startinpos = ((const char *)q) - starts;
5035 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005037
5038 /* The remaining input chars are ignored if the callback
5039 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005040 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005042 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005043 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005044 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005046 }
5047
Walter Dörwald41980ca2007-08-16 21:55:45 +00005048 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051 Py_XDECREF(errorHandler);
5052 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005053 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005056 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057 Py_XDECREF(errorHandler);
5058 Py_XDECREF(exc);
5059 return NULL;
5060}
5061
5062PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005063_PyUnicode_EncodeUTF32(PyObject *str,
5064 const char *errors,
5065 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005067 int kind;
5068 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005069 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005070 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005071 unsigned char *p;
5072 Py_ssize_t nsize, i;
5073 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005074#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005075 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005077 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005078#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005079 const char *encoding;
5080 PyObject *errorHandler = NULL;
5081 PyObject *exc = NULL;
5082 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083
Serhiy Storchaka30793282014-01-04 22:44:01 +02005084#define STORECHAR(CH) \
5085 do { \
5086 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5087 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5088 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5089 p[iorder[0]] = (CH) & 0xff; \
5090 p += 4; \
5091 } while(0)
5092
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005093 if (!PyUnicode_Check(str)) {
5094 PyErr_BadArgument();
5095 return NULL;
5096 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005097 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 return NULL;
5099 kind = PyUnicode_KIND(str);
5100 data = PyUnicode_DATA(str);
5101 len = PyUnicode_GET_LENGTH(str);
5102
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005103 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 if (nsize > PY_SSIZE_T_MAX / 4)
5105 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005106 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107 if (v == NULL)
5108 return NULL;
5109
Serhiy Storchaka30793282014-01-04 22:44:01 +02005110 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005111 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005112 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005113 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005114 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115
Serhiy Storchaka30793282014-01-04 22:44:01 +02005116 if (byteorder == -1) {
5117 /* force LE */
5118 iorder[0] = 0;
5119 iorder[1] = 1;
5120 iorder[2] = 2;
5121 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005122 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005123 }
5124 else if (byteorder == 1) {
5125 /* force BE */
5126 iorder[0] = 3;
5127 iorder[1] = 2;
5128 iorder[2] = 1;
5129 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005130 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005131 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005132 else
5133 encoding = "utf-32";
5134
5135 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005136 for (i = 0; i < len; i++)
5137 STORECHAR(PyUnicode_READ(kind, data, i));
5138 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139 }
5140
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005142 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005143 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5144 i++;
5145 assert(ch <= MAX_UNICODE);
5146 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5147 STORECHAR(ch);
5148 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005149 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005150
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005151 rep = unicode_encode_call_errorhandler(
5152 errors, &errorHandler,
5153 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005154 str, &exc, i-1, i, &i);
5155
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005156 if (!rep)
5157 goto error;
5158
5159 if (PyBytes_Check(rep)) {
5160 repsize = PyBytes_GET_SIZE(rep);
5161 if (repsize & 3) {
5162 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005163 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005164 "surrogates not allowed");
5165 goto error;
5166 }
5167 moreunits = repsize / 4;
5168 }
5169 else {
5170 assert(PyUnicode_Check(rep));
5171 if (PyUnicode_READY(rep) < 0)
5172 goto error;
5173 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5174 if (!PyUnicode_IS_ASCII(rep)) {
5175 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005176 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005177 "surrogates not allowed");
5178 goto error;
5179 }
5180 }
5181
5182 /* four bytes are reserved for each surrogate */
5183 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005184 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005185 Py_ssize_t morebytes = 4 * (moreunits - 1);
5186 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5187 /* integer overflow */
5188 PyErr_NoMemory();
5189 goto error;
5190 }
5191 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5192 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005193 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005194 }
5195
5196 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005197 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5198 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005199 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005200 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005202 repdata = PyUnicode_1BYTE_DATA(rep);
5203 while (repsize--) {
5204 Py_UCS4 ch = *repdata++;
5205 STORECHAR(ch);
5206 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005207 }
5208
5209 Py_CLEAR(rep);
5210 }
5211
5212 /* Cut back to size actually needed. This is necessary for, for example,
5213 encoding of a string containing isolated surrogates and the 'ignore'
5214 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005215 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005216 if (nsize != PyBytes_GET_SIZE(v))
5217 _PyBytes_Resize(&v, nsize);
5218 Py_XDECREF(errorHandler);
5219 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005220 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005221 error:
5222 Py_XDECREF(rep);
5223 Py_XDECREF(errorHandler);
5224 Py_XDECREF(exc);
5225 Py_XDECREF(v);
5226 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005227#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005228}
5229
Alexander Belopolsky40018472011-02-26 01:02:56 +00005230PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005231PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5232 Py_ssize_t size,
5233 const char *errors,
5234 int byteorder)
5235{
5236 PyObject *result;
5237 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5238 if (tmp == NULL)
5239 return NULL;
5240 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5241 Py_DECREF(tmp);
5242 return result;
5243}
5244
5245PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005246PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005247{
Victor Stinnerb960b342011-11-20 19:12:52 +01005248 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249}
5250
Guido van Rossumd57fd912000-03-10 22:53:23 +00005251/* --- UTF-16 Codec ------------------------------------------------------- */
5252
Tim Peters772747b2001-08-09 22:21:55 +00005253PyObject *
5254PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 Py_ssize_t size,
5256 const char *errors,
5257 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005258{
Walter Dörwald69652032004-09-07 20:24:22 +00005259 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5260}
5261
5262PyObject *
5263PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005264 Py_ssize_t size,
5265 const char *errors,
5266 int *byteorder,
5267 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005268{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005269 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005270 Py_ssize_t startinpos;
5271 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005272 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005273 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005274 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005275 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005276 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005277 PyObject *errorHandler = NULL;
5278 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005279 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280
Tim Peters772747b2001-08-09 22:21:55 +00005281 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005282 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005283
5284 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005285 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005286
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005287 /* Check for BOM marks (U+FEFF) in the input and adjust current
5288 byte order setting accordingly. In native mode, the leading BOM
5289 mark is skipped, in all other modes, it is copied to the output
5290 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005291 if (bo == 0 && size >= 2) {
5292 const Py_UCS4 bom = (q[1] << 8) | q[0];
5293 if (bom == 0xFEFF) {
5294 q += 2;
5295 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005296 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005297 else if (bom == 0xFFFE) {
5298 q += 2;
5299 bo = 1;
5300 }
5301 if (byteorder)
5302 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005303 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005304
Antoine Pitrou63065d72012-05-15 23:48:04 +02005305 if (q == e) {
5306 if (consumed)
5307 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005308 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005309 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005310
Christian Heimes743e0cd2012-10-17 23:52:17 +02005311#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005312 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005313 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005314#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005315 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005316 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005317#endif
Tim Peters772747b2001-08-09 22:21:55 +00005318
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319 /* Note: size will always be longer than the resulting Unicode
5320 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005321 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005322 writer.min_length = (e - q + 1) / 2;
5323 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005324 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005325
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 while (1) {
5327 Py_UCS4 ch = 0;
5328 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005330 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005331 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005332 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005333 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 native_ordering);
5335 else
5336 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005337 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005338 native_ordering);
5339 } else if (kind == PyUnicode_2BYTE_KIND) {
5340 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005342 native_ordering);
5343 } else {
5344 assert(kind == PyUnicode_4BYTE_KIND);
5345 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005346 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005347 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005348 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005349 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005350
Antoine Pitrou63065d72012-05-15 23:48:04 +02005351 switch (ch)
5352 {
5353 case 0:
5354 /* remaining byte at the end? (size should be even) */
5355 if (q == e || consumed)
5356 goto End;
5357 errmsg = "truncated data";
5358 startinpos = ((const char *)q) - starts;
5359 endinpos = ((const char *)e) - starts;
5360 break;
5361 /* The remaining input chars are ignored if the callback
5362 chooses to skip the input */
5363 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005364 q -= 2;
5365 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005366 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005368 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369 endinpos = ((const char *)e) - starts;
5370 break;
5371 case 2:
5372 errmsg = "illegal encoding";
5373 startinpos = ((const char *)q) - 2 - starts;
5374 endinpos = startinpos + 2;
5375 break;
5376 case 3:
5377 errmsg = "illegal UTF-16 surrogate";
5378 startinpos = ((const char *)q) - 4 - starts;
5379 endinpos = startinpos + 2;
5380 break;
5381 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005382 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005383 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 continue;
5385 }
5386
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005387 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005388 errors,
5389 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005390 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005391 &starts,
5392 (const char **)&e,
5393 &startinpos,
5394 &endinpos,
5395 &exc,
5396 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005397 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005398 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005399 }
5400
Antoine Pitrou63065d72012-05-15 23:48:04 +02005401End:
Walter Dörwald69652032004-09-07 20:24:22 +00005402 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005403 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005405 Py_XDECREF(errorHandler);
5406 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005407 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005410 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411 Py_XDECREF(errorHandler);
5412 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413 return NULL;
5414}
5415
Tim Peters772747b2001-08-09 22:21:55 +00005416PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005417_PyUnicode_EncodeUTF16(PyObject *str,
5418 const char *errors,
5419 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005421 enum PyUnicode_Kind kind;
5422 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005423 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005424 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005425 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005426 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005427#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005428 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005429#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005430 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005431#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005432 const char *encoding;
5433 Py_ssize_t nsize, pos;
5434 PyObject *errorHandler = NULL;
5435 PyObject *exc = NULL;
5436 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005437
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005438 if (!PyUnicode_Check(str)) {
5439 PyErr_BadArgument();
5440 return NULL;
5441 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005442 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005443 return NULL;
5444 kind = PyUnicode_KIND(str);
5445 data = PyUnicode_DATA(str);
5446 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005447
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005448 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005449 if (kind == PyUnicode_4BYTE_KIND) {
5450 const Py_UCS4 *in = (const Py_UCS4 *)data;
5451 const Py_UCS4 *end = in + len;
5452 while (in < end)
5453 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005454 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005455 }
5456 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005457 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005458 nsize = len + pairs + (byteorder == 0);
5459 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460 if (v == NULL)
5461 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005462
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005463 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005464 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005465 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005466 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005467 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005468 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005469 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005470
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005471 if (kind == PyUnicode_1BYTE_KIND) {
5472 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5473 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005474 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005475
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005476 if (byteorder < 0)
5477 encoding = "utf-16-le";
5478 else if (byteorder > 0)
5479 encoding = "utf-16-be";
5480 else
5481 encoding = "utf-16";
5482
5483 pos = 0;
5484 while (pos < len) {
5485 Py_ssize_t repsize, moreunits;
5486
5487 if (kind == PyUnicode_2BYTE_KIND) {
5488 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5489 &out, native_ordering);
5490 }
5491 else {
5492 assert(kind == PyUnicode_4BYTE_KIND);
5493 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5494 &out, native_ordering);
5495 }
5496 if (pos == len)
5497 break;
5498
5499 rep = unicode_encode_call_errorhandler(
5500 errors, &errorHandler,
5501 encoding, "surrogates not allowed",
5502 str, &exc, pos, pos + 1, &pos);
5503 if (!rep)
5504 goto error;
5505
5506 if (PyBytes_Check(rep)) {
5507 repsize = PyBytes_GET_SIZE(rep);
5508 if (repsize & 1) {
5509 raise_encode_exception(&exc, encoding,
5510 str, pos - 1, pos,
5511 "surrogates not allowed");
5512 goto error;
5513 }
5514 moreunits = repsize / 2;
5515 }
5516 else {
5517 assert(PyUnicode_Check(rep));
5518 if (PyUnicode_READY(rep) < 0)
5519 goto error;
5520 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5521 if (!PyUnicode_IS_ASCII(rep)) {
5522 raise_encode_exception(&exc, encoding,
5523 str, pos - 1, pos,
5524 "surrogates not allowed");
5525 goto error;
5526 }
5527 }
5528
5529 /* two bytes are reserved for each surrogate */
5530 if (moreunits > 1) {
5531 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5532 Py_ssize_t morebytes = 2 * (moreunits - 1);
5533 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5534 /* integer overflow */
5535 PyErr_NoMemory();
5536 goto error;
5537 }
5538 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5539 goto error;
5540 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5541 }
5542
5543 if (PyBytes_Check(rep)) {
5544 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5545 out += moreunits;
5546 } else /* rep is unicode */ {
5547 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5548 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5549 &out, native_ordering);
5550 }
5551
5552 Py_CLEAR(rep);
5553 }
5554
5555 /* Cut back to size actually needed. This is necessary for, for example,
5556 encoding of a string containing isolated surrogates and the 'ignore' handler
5557 is used. */
5558 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5559 if (nsize != PyBytes_GET_SIZE(v))
5560 _PyBytes_Resize(&v, nsize);
5561 Py_XDECREF(errorHandler);
5562 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005563 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005564 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005565 error:
5566 Py_XDECREF(rep);
5567 Py_XDECREF(errorHandler);
5568 Py_XDECREF(exc);
5569 Py_XDECREF(v);
5570 return NULL;
5571#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005572}
5573
Alexander Belopolsky40018472011-02-26 01:02:56 +00005574PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005575PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5576 Py_ssize_t size,
5577 const char *errors,
5578 int byteorder)
5579{
5580 PyObject *result;
5581 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5582 if (tmp == NULL)
5583 return NULL;
5584 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5585 Py_DECREF(tmp);
5586 return result;
5587}
5588
5589PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005590PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005591{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005592 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593}
5594
5595/* --- Unicode Escape Codec ----------------------------------------------- */
5596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005597/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5598 if all the escapes in the string make it still a valid ASCII string.
5599 Returns -1 if any escapes were found which cause the string to
5600 pop out of ASCII range. Otherwise returns the length of the
5601 required buffer to hold the string.
5602 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005603static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005604length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5605{
5606 const unsigned char *p = (const unsigned char *)s;
5607 const unsigned char *end = p + size;
5608 Py_ssize_t length = 0;
5609
5610 if (size < 0)
5611 return -1;
5612
5613 for (; p < end; ++p) {
5614 if (*p > 127) {
5615 /* Non-ASCII */
5616 return -1;
5617 }
5618 else if (*p != '\\') {
5619 /* Normal character */
5620 ++length;
5621 }
5622 else {
5623 /* Backslash-escape, check next char */
5624 ++p;
5625 /* Escape sequence reaches till end of string or
5626 non-ASCII follow-up. */
5627 if (p >= end || *p > 127)
5628 return -1;
5629 switch (*p) {
5630 case '\n':
5631 /* backslash + \n result in zero characters */
5632 break;
5633 case '\\': case '\'': case '\"':
5634 case 'b': case 'f': case 't':
5635 case 'n': case 'r': case 'v': case 'a':
5636 ++length;
5637 break;
5638 case '0': case '1': case '2': case '3':
5639 case '4': case '5': case '6': case '7':
5640 case 'x': case 'u': case 'U': case 'N':
5641 /* these do not guarantee ASCII characters */
5642 return -1;
5643 default:
5644 /* count the backslash + the other character */
5645 length += 2;
5646 }
5647 }
5648 }
5649 return length;
5650}
5651
Fredrik Lundh06d12682001-01-24 07:59:11 +00005652static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005653
Alexander Belopolsky40018472011-02-26 01:02:56 +00005654PyObject *
5655PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005656 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005657 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005659 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005660 Py_ssize_t startinpos;
5661 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005664 char* message;
5665 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 PyObject *errorHandler = NULL;
5667 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005668 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005669
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005670 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005671 if (len == 0)
5672 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005673
5674 /* After length_of_escaped_ascii_string() there are two alternatives,
5675 either the string is pure ASCII with named escapes like \n, etc.
5676 and we determined it's exact size (common case)
5677 or it contains \x, \u, ... escape sequences. then we create a
5678 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005679 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005680 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005681 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005682 }
5683 else {
5684 /* Escaped strings will always be longer than the resulting
5685 Unicode string, so we start with size here and then reduce the
5686 length after conversion to the true value.
5687 (but if the error callback returns a long replacement string
5688 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005689 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005690 }
5691
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005693 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005695
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 while (s < end) {
5697 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005698 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005699 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700
5701 /* Non-escape characters are interpreted as Unicode ordinals */
5702 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005703 x = (unsigned char)*s;
5704 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005705 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005706 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707 continue;
5708 }
5709
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005710 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005711 /* \ - Escapes */
5712 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005713 c = *s++;
5714 if (s > end)
5715 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005716
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005717 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718
Benjamin Peterson29060642009-01-31 22:14:21 +00005719 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005720#define WRITECHAR(ch) \
5721 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005722 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005723 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005724 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005725
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005727 case '\\': WRITECHAR('\\'); break;
5728 case '\'': WRITECHAR('\''); break;
5729 case '\"': WRITECHAR('\"'); break;
5730 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005731 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005732 case 'f': WRITECHAR('\014'); break;
5733 case 't': WRITECHAR('\t'); break;
5734 case 'n': WRITECHAR('\n'); break;
5735 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005736 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005737 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005739 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742 case '0': case '1': case '2': case '3':
5743 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005744 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005745 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005746 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005747 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005748 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005750 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 break;
5752
Benjamin Peterson29060642009-01-31 22:14:21 +00005753 /* hex escapes */
5754 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005756 digits = 2;
5757 message = "truncated \\xXX escape";
5758 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759
Benjamin Peterson29060642009-01-31 22:14:21 +00005760 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005762 digits = 4;
5763 message = "truncated \\uXXXX escape";
5764 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005765
Benjamin Peterson29060642009-01-31 22:14:21 +00005766 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005767 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005768 digits = 8;
5769 message = "truncated \\UXXXXXXXX escape";
5770 hexescape:
5771 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005772 if (end - s < digits) {
5773 /* count only hex digits */
5774 for (; s < end; ++s) {
5775 c = (unsigned char)*s;
5776 if (!Py_ISXDIGIT(c))
5777 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005778 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005779 goto error;
5780 }
5781 for (; digits--; ++s) {
5782 c = (unsigned char)*s;
5783 if (!Py_ISXDIGIT(c))
5784 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005785 chr = (chr<<4) & ~0xF;
5786 if (c >= '0' && c <= '9')
5787 chr += c - '0';
5788 else if (c >= 'a' && c <= 'f')
5789 chr += 10 + c - 'a';
5790 else
5791 chr += 10 + c - 'A';
5792 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005793 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 /* _decoding_error will have already written into the
5795 target buffer. */
5796 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005798 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005799 message = "illegal Unicode character";
5800 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005801 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005802 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005803 break;
5804
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005806 case 'N':
5807 message = "malformed \\N character escape";
5808 if (ucnhash_CAPI == NULL) {
5809 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005810 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5811 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005812 if (ucnhash_CAPI == NULL)
5813 goto ucnhashError;
5814 }
5815 if (*s == '{') {
5816 const char *start = s+1;
5817 /* look for the closing brace */
5818 while (*s != '}' && s < end)
5819 s++;
5820 if (s > start && s < end && *s == '}') {
5821 /* found a name. look it up in the unicode database */
5822 message = "unknown Unicode character name";
5823 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005824 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005825 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005826 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005827 goto store;
5828 }
5829 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005831
5832 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005833 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005834 message = "\\ at end of string";
5835 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005836 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005837 }
5838 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005839 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005840 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005841 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005842 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005844 continue;
5845
5846 error:
5847 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005848 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005849 errors, &errorHandler,
5850 "unicodeescape", message,
5851 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005852 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005853 goto onError;
5854 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005856#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005858 Py_XDECREF(errorHandler);
5859 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005860 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005861
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005863 PyErr_SetString(
5864 PyExc_UnicodeError,
5865 "\\N escapes not supported (can't load unicodedata module)"
5866 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005867 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005868 Py_XDECREF(errorHandler);
5869 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005870 return NULL;
5871
Benjamin Peterson29060642009-01-31 22:14:21 +00005872 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005873 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005874 Py_XDECREF(errorHandler);
5875 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 return NULL;
5877}
5878
5879/* Return a Unicode-Escape string version of the Unicode object.
5880
5881 If quotes is true, the string is enclosed in u"" or u'' quotes as
5882 appropriate.
5883
5884*/
5885
Alexander Belopolsky40018472011-02-26 01:02:56 +00005886PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005887PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005890 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005892 int kind;
5893 void *data;
5894 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895
Ezio Melottie7f90372012-10-05 03:33:31 +03005896 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005897 escape.
5898
Ezio Melottie7f90372012-10-05 03:33:31 +03005899 For UCS1 strings it's '\xxx', 4 bytes per source character.
5900 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5901 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005902 */
5903
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 if (!PyUnicode_Check(unicode)) {
5905 PyErr_BadArgument();
5906 return NULL;
5907 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005908 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005909 return NULL;
5910 len = PyUnicode_GET_LENGTH(unicode);
5911 kind = PyUnicode_KIND(unicode);
5912 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005913 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005914 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5915 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5916 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5917 }
5918
5919 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005920 return PyBytes_FromStringAndSize(NULL, 0);
5921
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005922 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005924
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005925 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005926 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005927 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 if (repr == NULL)
5930 return NULL;
5931
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005932 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005934 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005935 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005936
Walter Dörwald79e913e2007-05-12 11:08:06 +00005937 /* Escape backslashes */
5938 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 *p++ = '\\';
5940 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005941 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005942 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005943
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005944 /* Map 21-bit characters to '\U00xxxxxx' */
5945 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005946 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005947 *p++ = '\\';
5948 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005949 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5950 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5951 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5952 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5953 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5954 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5955 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5956 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005958 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005959
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005961 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 *p++ = '\\';
5963 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005964 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5965 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5966 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5967 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005969
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005970 /* Map special whitespace to '\t', \n', '\r' */
5971 else if (ch == '\t') {
5972 *p++ = '\\';
5973 *p++ = 't';
5974 }
5975 else if (ch == '\n') {
5976 *p++ = '\\';
5977 *p++ = 'n';
5978 }
5979 else if (ch == '\r') {
5980 *p++ = '\\';
5981 *p++ = 'r';
5982 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005983
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005984 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005985 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005987 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005988 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5989 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005990 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005991
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 /* Copy everything else as-is */
5993 else
5994 *p++ = (char) ch;
5995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005997 assert(p - PyBytes_AS_STRING(repr) > 0);
5998 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5999 return NULL;
6000 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001}
6002
Alexander Belopolsky40018472011-02-26 01:02:56 +00006003PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006004PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6005 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006007 PyObject *result;
6008 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6009 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006011 result = PyUnicode_AsUnicodeEscapeString(tmp);
6012 Py_DECREF(tmp);
6013 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014}
6015
6016/* --- Raw Unicode Escape Codec ------------------------------------------- */
6017
Alexander Belopolsky40018472011-02-26 01:02:56 +00006018PyObject *
6019PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006020 Py_ssize_t size,
6021 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006023 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006024 Py_ssize_t startinpos;
6025 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006026 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 const char *end;
6028 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029 PyObject *errorHandler = NULL;
6030 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006031
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006032 if (size == 0)
6033 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006034
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035 /* Escaped strings will always be longer than the resulting
6036 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006037 length after conversion to the true value. (But decoding error
6038 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006039 _PyUnicodeWriter_Init(&writer);
6040 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006041
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 end = s + size;
6043 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 unsigned char c;
6045 Py_UCS4 x;
6046 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006047 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 /* Non-escape characters are interpreted as Unicode ordinals */
6050 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006051 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006052 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006053 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006055 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 startinpos = s-starts;
6057
6058 /* \u-escapes are only interpreted iff the number of leading
6059 backslashes if odd */
6060 bs = s;
6061 for (;s < end;) {
6062 if (*s != '\\')
6063 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006064 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006065 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006066 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 }
6068 if (((s - bs) & 1) == 0 ||
6069 s >= end ||
6070 (*s != 'u' && *s != 'U')) {
6071 continue;
6072 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006073 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006074 count = *s=='u' ? 4 : 8;
6075 s++;
6076
6077 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 for (x = 0, i = 0; i < count; ++i, ++s) {
6079 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006080 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006082 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 errors, &errorHandler,
6084 "rawunicodeescape", "truncated \\uXXXX",
6085 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006086 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 goto onError;
6088 goto nextByte;
6089 }
6090 x = (x<<4) & ~0xF;
6091 if (c >= '0' && c <= '9')
6092 x += c - '0';
6093 else if (c >= 'a' && c <= 'f')
6094 x += 10 + c - 'a';
6095 else
6096 x += 10 + c - 'A';
6097 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006098 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006099 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006100 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006101 }
6102 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006103 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006104 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006105 errors, &errorHandler,
6106 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006108 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006110 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 nextByte:
6112 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006114 Py_XDECREF(errorHandler);
6115 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006116 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006117
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006119 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006120 Py_XDECREF(errorHandler);
6121 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122 return NULL;
6123}
6124
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125
Alexander Belopolsky40018472011-02-26 01:02:56 +00006126PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006129 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 char *p;
6131 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006132 Py_ssize_t expandsize, pos;
6133 int kind;
6134 void *data;
6135 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137 if (!PyUnicode_Check(unicode)) {
6138 PyErr_BadArgument();
6139 return NULL;
6140 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006141 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006142 return NULL;
6143 kind = PyUnicode_KIND(unicode);
6144 data = PyUnicode_DATA(unicode);
6145 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006146 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6147 bytes, and 1 byte characters 4. */
6148 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006149
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006152
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 if (repr == NULL)
6155 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006157 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006158
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006159 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 for (pos = 0; pos < len; pos++) {
6161 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006162 /* Map 32-bit characters to '\Uxxxxxxxx' */
6163 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006164 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006165 *p++ = '\\';
6166 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006167 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6168 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6169 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6170 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6171 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6172 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6173 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6174 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006175 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006177 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 *p++ = '\\';
6179 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006180 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6181 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6182 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6183 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 /* Copy everything else as-is */
6186 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 *p++ = (char) ch;
6188 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006189
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 assert(p > q);
6191 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006192 return NULL;
6193 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194}
6195
Alexander Belopolsky40018472011-02-26 01:02:56 +00006196PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006197PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6198 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 PyObject *result;
6201 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6202 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006203 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006204 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6205 Py_DECREF(tmp);
6206 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207}
6208
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006209/* --- Unicode Internal Codec ------------------------------------------- */
6210
Alexander Belopolsky40018472011-02-26 01:02:56 +00006211PyObject *
6212_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006213 Py_ssize_t size,
6214 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006215{
6216 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006217 Py_ssize_t startinpos;
6218 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006219 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006220 const char *end;
6221 const char *reason;
6222 PyObject *errorHandler = NULL;
6223 PyObject *exc = NULL;
6224
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006225 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006226 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006227 1))
6228 return NULL;
6229
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006230 if (size == 0)
6231 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006232
Victor Stinner8f674cc2013-04-17 23:02:17 +02006233 _PyUnicodeWriter_Init(&writer);
6234 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6235 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006237 }
6238 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006239
Victor Stinner8f674cc2013-04-17 23:02:17 +02006240 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006241 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006242 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006243 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006244 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006245 endinpos = end-starts;
6246 reason = "truncated input";
6247 goto error;
6248 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006249 /* We copy the raw representation one byte at a time because the
6250 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006251 ((char *) &uch)[0] = s[0];
6252 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006253#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006254 ((char *) &uch)[2] = s[2];
6255 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006256#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006257 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006258#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006259 /* We have to sanity check the raw data, otherwise doom looms for
6260 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006261 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006262 endinpos = s - starts + Py_UNICODE_SIZE;
6263 reason = "illegal code point (> 0x10FFFF)";
6264 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006265 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006266#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006267 s += Py_UNICODE_SIZE;
6268#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006269 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006270 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006271 Py_UNICODE uch2;
6272 ((char *) &uch2)[0] = s[0];
6273 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006274 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006275 {
Victor Stinner551ac952011-11-29 22:58:13 +01006276 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006277 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006278 }
6279 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006280#endif
6281
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006282 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006283 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006284 continue;
6285
6286 error:
6287 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006288 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006289 errors, &errorHandler,
6290 "unicode_internal", reason,
6291 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006292 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006293 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006294 }
6295
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 Py_XDECREF(errorHandler);
6297 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006298 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006299
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006301 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006302 Py_XDECREF(errorHandler);
6303 Py_XDECREF(exc);
6304 return NULL;
6305}
6306
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307/* --- Latin-1 Codec ------------------------------------------------------ */
6308
Alexander Belopolsky40018472011-02-26 01:02:56 +00006309PyObject *
6310PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006311 Py_ssize_t size,
6312 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006313{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006315 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316}
6317
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006318/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006319static void
6320make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006321 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006322 PyObject *unicode,
6323 Py_ssize_t startpos, Py_ssize_t endpos,
6324 const char *reason)
6325{
6326 if (*exceptionObject == NULL) {
6327 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006328 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006329 encoding, unicode, startpos, endpos, reason);
6330 }
6331 else {
6332 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6333 goto onError;
6334 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6335 goto onError;
6336 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6337 goto onError;
6338 return;
6339 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006340 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006341 }
6342}
6343
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006344/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006345static void
6346raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006347 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006348 PyObject *unicode,
6349 Py_ssize_t startpos, Py_ssize_t endpos,
6350 const char *reason)
6351{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006352 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006353 encoding, unicode, startpos, endpos, reason);
6354 if (*exceptionObject != NULL)
6355 PyCodec_StrictErrors(*exceptionObject);
6356}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357
6358/* error handling callback helper:
6359 build arguments, call the callback and check the arguments,
6360 put the result into newpos and return the replacement string, which
6361 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006362static PyObject *
6363unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006364 PyObject **errorHandler,
6365 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006366 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006367 Py_ssize_t startpos, Py_ssize_t endpos,
6368 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006370 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006371 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372 PyObject *restuple;
6373 PyObject *resunicode;
6374
6375 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006378 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379 }
6380
Benjamin Petersonbac79492012-01-14 13:34:47 -05006381 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006382 return NULL;
6383 len = PyUnicode_GET_LENGTH(unicode);
6384
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006385 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006386 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006387 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389
6390 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006392 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006395 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 Py_DECREF(restuple);
6397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006399 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 &resunicode, newpos)) {
6401 Py_DECREF(restuple);
6402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006403 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006404 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6405 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6406 Py_DECREF(restuple);
6407 return NULL;
6408 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006410 *newpos = len + *newpos;
6411 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006412 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 Py_DECREF(restuple);
6414 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006415 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 Py_INCREF(resunicode);
6417 Py_DECREF(restuple);
6418 return resunicode;
6419}
6420
Alexander Belopolsky40018472011-02-26 01:02:56 +00006421static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006423 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006424 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006426 /* input state */
6427 Py_ssize_t pos=0, size;
6428 int kind;
6429 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 /* output object */
6431 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 /* pointer into the output */
6433 char *str;
6434 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006435 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006436 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6437 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438 PyObject *errorHandler = NULL;
6439 PyObject *exc = NULL;
6440 /* the following variable is used for caching string comparisons
6441 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6442 int known_errorHandler = -1;
6443
Benjamin Petersonbac79492012-01-14 13:34:47 -05006444 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006445 return NULL;
6446 size = PyUnicode_GET_LENGTH(unicode);
6447 kind = PyUnicode_KIND(unicode);
6448 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 /* allocate enough for a simple encoding without
6450 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006451 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006452 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006453 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006455 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006456 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006457 ressize = size;
6458
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 while (pos < size) {
6460 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 /* can we encode this? */
6463 if (c<limit) {
6464 /* no overflow check, because we know that the space is enough */
6465 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006466 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006467 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 Py_ssize_t requiredsize;
6470 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006471 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006473 Py_ssize_t collstart = pos;
6474 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006476 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 ++collend;
6478 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6479 if (known_errorHandler==-1) {
6480 if ((errors==NULL) || (!strcmp(errors, "strict")))
6481 known_errorHandler = 1;
6482 else if (!strcmp(errors, "replace"))
6483 known_errorHandler = 2;
6484 else if (!strcmp(errors, "ignore"))
6485 known_errorHandler = 3;
6486 else if (!strcmp(errors, "xmlcharrefreplace"))
6487 known_errorHandler = 4;
6488 else
6489 known_errorHandler = 0;
6490 }
6491 switch (known_errorHandler) {
6492 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006493 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006494 goto onError;
6495 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006496 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 *str++ = '?'; /* fall through */
6498 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006499 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 break;
6501 case 4: /* xmlcharrefreplace */
6502 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006503 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006505 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006507 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006509 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006511 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006512 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006513 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006515 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006516 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006517 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006519 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006520 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006521 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006522 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006523 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006524 if (requiredsize > PY_SSIZE_T_MAX - incr)
6525 goto overflow;
6526 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006528 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6529 goto overflow;
6530 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006532 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 requiredsize = 2*ressize;
6534 if (_PyBytes_Resize(&res, requiredsize))
6535 goto onError;
6536 str = PyBytes_AS_STRING(res) + respos;
6537 ressize = requiredsize;
6538 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 /* generate replacement */
6540 for (i = collstart; i < collend; ++i) {
6541 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 break;
6545 default:
6546 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 encoding, reason, unicode, &exc,
6548 collstart, collend, &newpos);
6549 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006550 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006552 if (PyBytes_Check(repunicode)) {
6553 /* Directly copy bytes result to output. */
6554 repsize = PyBytes_Size(repunicode);
6555 if (repsize > 1) {
6556 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006557 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006558 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6559 Py_DECREF(repunicode);
6560 goto overflow;
6561 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006562 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6563 Py_DECREF(repunicode);
6564 goto onError;
6565 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006566 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006567 ressize += repsize-1;
6568 }
6569 memcpy(str, PyBytes_AsString(repunicode), repsize);
6570 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006572 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006573 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006574 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 /* need more space? (at least enough for what we
6576 have+the replacement+the rest of the string, so
6577 we won't have to check space for encodable characters) */
6578 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006579 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006580 requiredsize = respos;
6581 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6582 goto overflow;
6583 requiredsize += repsize;
6584 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6585 goto overflow;
6586 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006587 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006588 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 requiredsize = 2*ressize;
6590 if (_PyBytes_Resize(&res, requiredsize)) {
6591 Py_DECREF(repunicode);
6592 goto onError;
6593 }
6594 str = PyBytes_AS_STRING(res) + respos;
6595 ressize = requiredsize;
6596 }
6597 /* check if there is anything unencodable in the replacement
6598 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 for (i = 0; repsize-->0; ++i, ++str) {
6600 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006602 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006603 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 Py_DECREF(repunicode);
6605 goto onError;
6606 }
6607 *str = (char)c;
6608 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006609 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006610 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006611 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006612 }
6613 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006614 /* Resize if we allocated to much */
6615 size = str - PyBytes_AS_STRING(res);
6616 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006617 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006618 if (_PyBytes_Resize(&res, size) < 0)
6619 goto onError;
6620 }
6621
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006622 Py_XDECREF(errorHandler);
6623 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006624 return res;
6625
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006626 overflow:
6627 PyErr_SetString(PyExc_OverflowError,
6628 "encoded result is too long for a Python string");
6629
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006630 onError:
6631 Py_XDECREF(res);
6632 Py_XDECREF(errorHandler);
6633 Py_XDECREF(exc);
6634 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635}
6636
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638PyObject *
6639PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006640 Py_ssize_t size,
6641 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 PyObject *result;
6644 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6645 if (unicode == NULL)
6646 return NULL;
6647 result = unicode_encode_ucs1(unicode, errors, 256);
6648 Py_DECREF(unicode);
6649 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650}
6651
Alexander Belopolsky40018472011-02-26 01:02:56 +00006652PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006653_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006654{
6655 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 PyErr_BadArgument();
6657 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006659 if (PyUnicode_READY(unicode) == -1)
6660 return NULL;
6661 /* Fast path: if it is a one-byte string, construct
6662 bytes object directly. */
6663 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6664 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6665 PyUnicode_GET_LENGTH(unicode));
6666 /* Non-Latin-1 characters present. Defer to above function to
6667 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006668 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006669}
6670
6671PyObject*
6672PyUnicode_AsLatin1String(PyObject *unicode)
6673{
6674 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006675}
6676
6677/* --- 7-bit ASCII Codec -------------------------------------------------- */
6678
Alexander Belopolsky40018472011-02-26 01:02:56 +00006679PyObject *
6680PyUnicode_DecodeASCII(const char *s,
6681 Py_ssize_t size,
6682 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006683{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006684 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006685 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006686 int kind;
6687 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006688 Py_ssize_t startinpos;
6689 Py_ssize_t endinpos;
6690 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 const char *e;
6692 PyObject *errorHandler = NULL;
6693 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006694
Guido van Rossumd57fd912000-03-10 22:53:23 +00006695 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006696 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006697
Guido van Rossumd57fd912000-03-10 22:53:23 +00006698 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006699 if (size == 1 && (unsigned char)s[0] < 128)
6700 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006701
Victor Stinner8f674cc2013-04-17 23:02:17 +02006702 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006703 writer.min_length = size;
6704 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006705 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006706
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006708 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006709 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006710 writer.pos = outpos;
6711 if (writer.pos == size)
6712 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006713
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006714 s += writer.pos;
6715 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006717 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006719 PyUnicode_WRITE(kind, data, writer.pos, c);
6720 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 ++s;
6722 }
6723 else {
6724 startinpos = s-starts;
6725 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006726 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 errors, &errorHandler,
6728 "ascii", "ordinal not in range(128)",
6729 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006730 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006732 kind = writer.kind;
6733 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006736 Py_XDECREF(errorHandler);
6737 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006738 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006739
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006741 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006742 Py_XDECREF(errorHandler);
6743 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 return NULL;
6745}
6746
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006748PyObject *
6749PyUnicode_EncodeASCII(const Py_UNICODE *p,
6750 Py_ssize_t size,
6751 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006753 PyObject *result;
6754 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6755 if (unicode == NULL)
6756 return NULL;
6757 result = unicode_encode_ucs1(unicode, errors, 128);
6758 Py_DECREF(unicode);
6759 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760}
6761
Alexander Belopolsky40018472011-02-26 01:02:56 +00006762PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006763_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764{
6765 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 PyErr_BadArgument();
6767 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006769 if (PyUnicode_READY(unicode) == -1)
6770 return NULL;
6771 /* Fast path: if it is an ASCII-only string, construct bytes object
6772 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006773 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006774 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6775 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006776 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777}
6778
6779PyObject *
6780PyUnicode_AsASCIIString(PyObject *unicode)
6781{
6782 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006783}
6784
Victor Stinner99b95382011-07-04 14:23:54 +02006785#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006786
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006787/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006788
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006789#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006790#define NEED_RETRY
6791#endif
6792
Victor Stinner3a50e702011-10-18 21:21:00 +02006793#ifndef WC_ERR_INVALID_CHARS
6794# define WC_ERR_INVALID_CHARS 0x0080
6795#endif
6796
6797static char*
6798code_page_name(UINT code_page, PyObject **obj)
6799{
6800 *obj = NULL;
6801 if (code_page == CP_ACP)
6802 return "mbcs";
6803 if (code_page == CP_UTF7)
6804 return "CP_UTF7";
6805 if (code_page == CP_UTF8)
6806 return "CP_UTF8";
6807
6808 *obj = PyBytes_FromFormat("cp%u", code_page);
6809 if (*obj == NULL)
6810 return NULL;
6811 return PyBytes_AS_STRING(*obj);
6812}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006813
Victor Stinner3a50e702011-10-18 21:21:00 +02006814static DWORD
6815decode_code_page_flags(UINT code_page)
6816{
6817 if (code_page == CP_UTF7) {
6818 /* The CP_UTF7 decoder only supports flags=0 */
6819 return 0;
6820 }
6821 else
6822 return MB_ERR_INVALID_CHARS;
6823}
6824
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006825/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006826 * Decode a byte string from a Windows code page into unicode object in strict
6827 * mode.
6828 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006829 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6830 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006831 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006832static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006833decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006834 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006835 const char *in,
6836 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837{
Victor Stinner3a50e702011-10-18 21:21:00 +02006838 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006839 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006840 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006841
6842 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006843 assert(insize > 0);
6844 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6845 if (outsize <= 0)
6846 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006847
6848 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006849 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006850 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006851 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006852 if (*v == NULL)
6853 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006854 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855 }
6856 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006859 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006861 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006862 }
6863
6864 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6866 if (outsize <= 0)
6867 goto error;
6868 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006869
Victor Stinner3a50e702011-10-18 21:21:00 +02006870error:
6871 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6872 return -2;
6873 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006874 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875}
6876
Victor Stinner3a50e702011-10-18 21:21:00 +02006877/*
6878 * Decode a byte string from a code page into unicode object with an error
6879 * handler.
6880 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006881 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006882 * UnicodeDecodeError exception and returns -1 on error.
6883 */
6884static int
6885decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006886 PyObject **v,
6887 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006888 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006889{
6890 const char *startin = in;
6891 const char *endin = in + size;
6892 const DWORD flags = decode_code_page_flags(code_page);
6893 /* Ideally, we should get reason from FormatMessage. This is the Windows
6894 2000 English version of the message. */
6895 const char *reason = "No mapping for the Unicode character exists "
6896 "in the target code page.";
6897 /* each step cannot decode more than 1 character, but a character can be
6898 represented as a surrogate pair */
6899 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006900 int insize;
6901 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 PyObject *errorHandler = NULL;
6903 PyObject *exc = NULL;
6904 PyObject *encoding_obj = NULL;
6905 char *encoding;
6906 DWORD err;
6907 int ret = -1;
6908
6909 assert(size > 0);
6910
6911 encoding = code_page_name(code_page, &encoding_obj);
6912 if (encoding == NULL)
6913 return -1;
6914
Victor Stinner7d00cc12014-03-17 23:08:06 +01006915 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006916 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6917 UnicodeDecodeError. */
6918 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6919 if (exc != NULL) {
6920 PyCodec_StrictErrors(exc);
6921 Py_CLEAR(exc);
6922 }
6923 goto error;
6924 }
6925
6926 if (*v == NULL) {
6927 /* Create unicode object */
6928 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6929 PyErr_NoMemory();
6930 goto error;
6931 }
Victor Stinnerab595942011-12-17 04:59:06 +01006932 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006933 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006934 if (*v == NULL)
6935 goto error;
6936 startout = PyUnicode_AS_UNICODE(*v);
6937 }
6938 else {
6939 /* Extend unicode object */
6940 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6941 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6942 PyErr_NoMemory();
6943 goto error;
6944 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006945 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006946 goto error;
6947 startout = PyUnicode_AS_UNICODE(*v) + n;
6948 }
6949
6950 /* Decode the byte string character per character */
6951 out = startout;
6952 while (in < endin)
6953 {
6954 /* Decode a character */
6955 insize = 1;
6956 do
6957 {
6958 outsize = MultiByteToWideChar(code_page, flags,
6959 in, insize,
6960 buffer, Py_ARRAY_LENGTH(buffer));
6961 if (outsize > 0)
6962 break;
6963 err = GetLastError();
6964 if (err != ERROR_NO_UNICODE_TRANSLATION
6965 && err != ERROR_INSUFFICIENT_BUFFER)
6966 {
6967 PyErr_SetFromWindowsErr(0);
6968 goto error;
6969 }
6970 insize++;
6971 }
6972 /* 4=maximum length of a UTF-8 sequence */
6973 while (insize <= 4 && (in + insize) <= endin);
6974
6975 if (outsize <= 0) {
6976 Py_ssize_t startinpos, endinpos, outpos;
6977
Victor Stinner7d00cc12014-03-17 23:08:06 +01006978 /* last character in partial decode? */
6979 if (in + insize >= endin && !final)
6980 break;
6981
Victor Stinner3a50e702011-10-18 21:21:00 +02006982 startinpos = in - startin;
6983 endinpos = startinpos + 1;
6984 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006985 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006986 errors, &errorHandler,
6987 encoding, reason,
6988 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006989 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006990 {
6991 goto error;
6992 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006993 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006994 }
6995 else {
6996 in += insize;
6997 memcpy(out, buffer, outsize * sizeof(wchar_t));
6998 out += outsize;
6999 }
7000 }
7001
7002 /* write a NUL character at the end */
7003 *out = 0;
7004
7005 /* Extend unicode object */
7006 outsize = out - startout;
7007 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007008 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007009 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007010 /* (in - startin) <= size and size is an int */
7011 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007012
7013error:
7014 Py_XDECREF(encoding_obj);
7015 Py_XDECREF(errorHandler);
7016 Py_XDECREF(exc);
7017 return ret;
7018}
7019
Victor Stinner3a50e702011-10-18 21:21:00 +02007020static PyObject *
7021decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007022 const char *s, Py_ssize_t size,
7023 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007024{
Victor Stinner76a31a62011-11-04 00:05:13 +01007025 PyObject *v = NULL;
7026 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 if (code_page < 0) {
7029 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7030 return NULL;
7031 }
7032
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007033 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007034 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035
Victor Stinner76a31a62011-11-04 00:05:13 +01007036 do
7037 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007038#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007039 if (size > INT_MAX) {
7040 chunk_size = INT_MAX;
7041 final = 0;
7042 done = 0;
7043 }
7044 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007046 {
7047 chunk_size = (int)size;
7048 final = (consumed == NULL);
7049 done = 1;
7050 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007051
Victor Stinner76a31a62011-11-04 00:05:13 +01007052 if (chunk_size == 0 && done) {
7053 if (v != NULL)
7054 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007055 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007056 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 converted = decode_code_page_strict(code_page, &v,
7059 s, chunk_size);
7060 if (converted == -2)
7061 converted = decode_code_page_errors(code_page, &v,
7062 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007063 errors, final);
7064 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007065
7066 if (converted < 0) {
7067 Py_XDECREF(v);
7068 return NULL;
7069 }
7070
7071 if (consumed)
7072 *consumed += converted;
7073
7074 s += converted;
7075 size -= converted;
7076 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007077
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007078 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079}
7080
Alexander Belopolsky40018472011-02-26 01:02:56 +00007081PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007082PyUnicode_DecodeCodePageStateful(int code_page,
7083 const char *s,
7084 Py_ssize_t size,
7085 const char *errors,
7086 Py_ssize_t *consumed)
7087{
7088 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7089}
7090
7091PyObject *
7092PyUnicode_DecodeMBCSStateful(const char *s,
7093 Py_ssize_t size,
7094 const char *errors,
7095 Py_ssize_t *consumed)
7096{
7097 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7098}
7099
7100PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007101PyUnicode_DecodeMBCS(const char *s,
7102 Py_ssize_t size,
7103 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007104{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7106}
7107
Victor Stinner3a50e702011-10-18 21:21:00 +02007108static DWORD
7109encode_code_page_flags(UINT code_page, const char *errors)
7110{
7111 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007112 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 }
7114 else if (code_page == CP_UTF7) {
7115 /* CP_UTF7 only supports flags=0 */
7116 return 0;
7117 }
7118 else {
7119 if (errors != NULL && strcmp(errors, "replace") == 0)
7120 return 0;
7121 else
7122 return WC_NO_BEST_FIT_CHARS;
7123 }
7124}
7125
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 * Encode a Unicode string to a Windows code page into a byte string in strict
7128 * mode.
7129 *
7130 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007131 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007133static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007134encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007135 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007136 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007137{
Victor Stinner554f3f02010-06-16 23:33:54 +00007138 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007139 BOOL *pusedDefaultChar = &usedDefaultChar;
7140 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007141 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007142 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007143 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007144 const DWORD flags = encode_code_page_flags(code_page, NULL);
7145 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007146 /* Create a substring so that we can get the UTF-16 representation
7147 of just the slice under consideration. */
7148 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007149
Martin v. Löwis3d325192011-11-04 18:23:06 +01007150 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007151
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007153 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007154 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007155 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007156
Victor Stinner2fc507f2011-11-04 20:06:39 +01007157 substring = PyUnicode_Substring(unicode, offset, offset+len);
7158 if (substring == NULL)
7159 return -1;
7160 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7161 if (p == NULL) {
7162 Py_DECREF(substring);
7163 return -1;
7164 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007165 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007166
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007167 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007169 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007170 NULL, 0,
7171 NULL, pusedDefaultChar);
7172 if (outsize <= 0)
7173 goto error;
7174 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007175 if (pusedDefaultChar && *pusedDefaultChar) {
7176 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007178 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007179
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007181 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 if (*outbytes == NULL) {
7184 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007185 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007186 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007188 }
7189 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007190 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 const Py_ssize_t n = PyBytes_Size(*outbytes);
7192 if (outsize > PY_SSIZE_T_MAX - n) {
7193 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007194 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007195 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007197 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7198 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007200 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202 }
7203
7204 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007206 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 out, outsize,
7208 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007209 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 if (outsize <= 0)
7211 goto error;
7212 if (pusedDefaultChar && *pusedDefaultChar)
7213 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007214 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007215
Victor Stinner3a50e702011-10-18 21:21:00 +02007216error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7219 return -2;
7220 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007221 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007222}
7223
Victor Stinner3a50e702011-10-18 21:21:00 +02007224/*
7225 * Encode a Unicode string to a Windows code page into a byte string using a
7226 * error handler.
7227 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007228 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 * -1 on other error.
7230 */
7231static int
7232encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007233 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007234 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007235{
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 Py_ssize_t pos = unicode_offset;
7238 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 /* Ideally, we should get reason from FormatMessage. This is the Windows
7240 2000 English version of the message. */
7241 const char *reason = "invalid character";
7242 /* 4=maximum length of a UTF-8 sequence */
7243 char buffer[4];
7244 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7245 Py_ssize_t outsize;
7246 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 PyObject *errorHandler = NULL;
7248 PyObject *exc = NULL;
7249 PyObject *encoding_obj = NULL;
7250 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007251 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 PyObject *rep;
7253 int ret = -1;
7254
7255 assert(insize > 0);
7256
7257 encoding = code_page_name(code_page, &encoding_obj);
7258 if (encoding == NULL)
7259 return -1;
7260
7261 if (errors == NULL || strcmp(errors, "strict") == 0) {
7262 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7263 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007264 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 if (exc != NULL) {
7266 PyCodec_StrictErrors(exc);
7267 Py_DECREF(exc);
7268 }
7269 Py_XDECREF(encoding_obj);
7270 return -1;
7271 }
7272
7273 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7274 pusedDefaultChar = &usedDefaultChar;
7275 else
7276 pusedDefaultChar = NULL;
7277
7278 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7279 PyErr_NoMemory();
7280 goto error;
7281 }
7282 outsize = insize * Py_ARRAY_LENGTH(buffer);
7283
7284 if (*outbytes == NULL) {
7285 /* Create string object */
7286 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7287 if (*outbytes == NULL)
7288 goto error;
7289 out = PyBytes_AS_STRING(*outbytes);
7290 }
7291 else {
7292 /* Extend string object */
7293 Py_ssize_t n = PyBytes_Size(*outbytes);
7294 if (n > PY_SSIZE_T_MAX - outsize) {
7295 PyErr_NoMemory();
7296 goto error;
7297 }
7298 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7299 goto error;
7300 out = PyBytes_AS_STRING(*outbytes) + n;
7301 }
7302
7303 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007304 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007306 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7307 wchar_t chars[2];
7308 int charsize;
7309 if (ch < 0x10000) {
7310 chars[0] = (wchar_t)ch;
7311 charsize = 1;
7312 }
7313 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007314 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7315 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007316 charsize = 2;
7317 }
7318
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007320 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 buffer, Py_ARRAY_LENGTH(buffer),
7322 NULL, pusedDefaultChar);
7323 if (outsize > 0) {
7324 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7325 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007326 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 memcpy(out, buffer, outsize);
7328 out += outsize;
7329 continue;
7330 }
7331 }
7332 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7333 PyErr_SetFromWindowsErr(0);
7334 goto error;
7335 }
7336
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 rep = unicode_encode_call_errorhandler(
7338 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007339 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 if (rep == NULL)
7342 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007344
7345 if (PyBytes_Check(rep)) {
7346 outsize = PyBytes_GET_SIZE(rep);
7347 if (outsize != 1) {
7348 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7349 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7350 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7351 Py_DECREF(rep);
7352 goto error;
7353 }
7354 out = PyBytes_AS_STRING(*outbytes) + offset;
7355 }
7356 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7357 out += outsize;
7358 }
7359 else {
7360 Py_ssize_t i;
7361 enum PyUnicode_Kind kind;
7362 void *data;
7363
Benjamin Petersonbac79492012-01-14 13:34:47 -05007364 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007365 Py_DECREF(rep);
7366 goto error;
7367 }
7368
7369 outsize = PyUnicode_GET_LENGTH(rep);
7370 if (outsize != 1) {
7371 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7372 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7373 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7374 Py_DECREF(rep);
7375 goto error;
7376 }
7377 out = PyBytes_AS_STRING(*outbytes) + offset;
7378 }
7379 kind = PyUnicode_KIND(rep);
7380 data = PyUnicode_DATA(rep);
7381 for (i=0; i < outsize; i++) {
7382 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7383 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007384 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 encoding, unicode,
7386 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 "unable to encode error handler result to ASCII");
7388 Py_DECREF(rep);
7389 goto error;
7390 }
7391 *out = (unsigned char)ch;
7392 out++;
7393 }
7394 }
7395 Py_DECREF(rep);
7396 }
7397 /* write a NUL byte */
7398 *out = 0;
7399 outsize = out - PyBytes_AS_STRING(*outbytes);
7400 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7401 if (_PyBytes_Resize(outbytes, outsize) < 0)
7402 goto error;
7403 ret = 0;
7404
7405error:
7406 Py_XDECREF(encoding_obj);
7407 Py_XDECREF(errorHandler);
7408 Py_XDECREF(exc);
7409 return ret;
7410}
7411
Victor Stinner3a50e702011-10-18 21:21:00 +02007412static PyObject *
7413encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007414 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 const char *errors)
7416{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007417 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007419 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007420 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007421
Victor Stinner29dacf22015-01-26 16:41:32 +01007422 if (!PyUnicode_Check(unicode)) {
7423 PyErr_BadArgument();
7424 return NULL;
7425 }
7426
Benjamin Petersonbac79492012-01-14 13:34:47 -05007427 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 return NULL;
7429 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007430
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 if (code_page < 0) {
7432 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7433 return NULL;
7434 }
7435
Martin v. Löwis3d325192011-11-04 18:23:06 +01007436 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007437 return PyBytes_FromStringAndSize(NULL, 0);
7438
Victor Stinner7581cef2011-11-03 22:32:33 +01007439 offset = 0;
7440 do
7441 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007442#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007443 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007444 chunks. */
7445 if (len > INT_MAX/2) {
7446 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007447 done = 0;
7448 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007449 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007450#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007451 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007452 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007453 done = 1;
7454 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455
Victor Stinner76a31a62011-11-04 00:05:13 +01007456 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007457 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007458 errors);
7459 if (ret == -2)
7460 ret = encode_code_page_errors(code_page, &outbytes,
7461 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007462 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007463 if (ret < 0) {
7464 Py_XDECREF(outbytes);
7465 return NULL;
7466 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007467
Victor Stinner7581cef2011-11-03 22:32:33 +01007468 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007469 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007470 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007471
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 return outbytes;
7473}
7474
7475PyObject *
7476PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7477 Py_ssize_t size,
7478 const char *errors)
7479{
Victor Stinner7581cef2011-11-03 22:32:33 +01007480 PyObject *unicode, *res;
7481 unicode = PyUnicode_FromUnicode(p, size);
7482 if (unicode == NULL)
7483 return NULL;
7484 res = encode_code_page(CP_ACP, unicode, errors);
7485 Py_DECREF(unicode);
7486 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007487}
7488
7489PyObject *
7490PyUnicode_EncodeCodePage(int code_page,
7491 PyObject *unicode,
7492 const char *errors)
7493{
Victor Stinner7581cef2011-11-03 22:32:33 +01007494 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007495}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007496
Alexander Belopolsky40018472011-02-26 01:02:56 +00007497PyObject *
7498PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007499{
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007501}
7502
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503#undef NEED_RETRY
7504
Victor Stinner99b95382011-07-04 14:23:54 +02007505#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007506
Guido van Rossumd57fd912000-03-10 22:53:23 +00007507/* --- Character Mapping Codec -------------------------------------------- */
7508
Victor Stinnerfb161b12013-04-18 01:44:27 +02007509static int
7510charmap_decode_string(const char *s,
7511 Py_ssize_t size,
7512 PyObject *mapping,
7513 const char *errors,
7514 _PyUnicodeWriter *writer)
7515{
7516 const char *starts = s;
7517 const char *e;
7518 Py_ssize_t startinpos, endinpos;
7519 PyObject *errorHandler = NULL, *exc = NULL;
7520 Py_ssize_t maplen;
7521 enum PyUnicode_Kind mapkind;
7522 void *mapdata;
7523 Py_UCS4 x;
7524 unsigned char ch;
7525
7526 if (PyUnicode_READY(mapping) == -1)
7527 return -1;
7528
7529 maplen = PyUnicode_GET_LENGTH(mapping);
7530 mapdata = PyUnicode_DATA(mapping);
7531 mapkind = PyUnicode_KIND(mapping);
7532
7533 e = s + size;
7534
7535 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7536 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7537 * is disabled in encoding aliases, latin1 is preferred because
7538 * its implementation is faster. */
7539 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7540 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7541 Py_UCS4 maxchar = writer->maxchar;
7542
7543 assert (writer->kind == PyUnicode_1BYTE_KIND);
7544 while (s < e) {
7545 ch = *s;
7546 x = mapdata_ucs1[ch];
7547 if (x > maxchar) {
7548 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7549 goto onError;
7550 maxchar = writer->maxchar;
7551 outdata = (Py_UCS1 *)writer->data;
7552 }
7553 outdata[writer->pos] = x;
7554 writer->pos++;
7555 ++s;
7556 }
7557 return 0;
7558 }
7559
7560 while (s < e) {
7561 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7562 enum PyUnicode_Kind outkind = writer->kind;
7563 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7564 if (outkind == PyUnicode_1BYTE_KIND) {
7565 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7566 Py_UCS4 maxchar = writer->maxchar;
7567 while (s < e) {
7568 ch = *s;
7569 x = mapdata_ucs2[ch];
7570 if (x > maxchar)
7571 goto Error;
7572 outdata[writer->pos] = x;
7573 writer->pos++;
7574 ++s;
7575 }
7576 break;
7577 }
7578 else if (outkind == PyUnicode_2BYTE_KIND) {
7579 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7580 while (s < e) {
7581 ch = *s;
7582 x = mapdata_ucs2[ch];
7583 if (x == 0xFFFE)
7584 goto Error;
7585 outdata[writer->pos] = x;
7586 writer->pos++;
7587 ++s;
7588 }
7589 break;
7590 }
7591 }
7592 ch = *s;
7593
7594 if (ch < maplen)
7595 x = PyUnicode_READ(mapkind, mapdata, ch);
7596 else
7597 x = 0xfffe; /* invalid value */
7598Error:
7599 if (x == 0xfffe)
7600 {
7601 /* undefined mapping */
7602 startinpos = s-starts;
7603 endinpos = startinpos+1;
7604 if (unicode_decode_call_errorhandler_writer(
7605 errors, &errorHandler,
7606 "charmap", "character maps to <undefined>",
7607 &starts, &e, &startinpos, &endinpos, &exc, &s,
7608 writer)) {
7609 goto onError;
7610 }
7611 continue;
7612 }
7613
7614 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7615 goto onError;
7616 ++s;
7617 }
7618 Py_XDECREF(errorHandler);
7619 Py_XDECREF(exc);
7620 return 0;
7621
7622onError:
7623 Py_XDECREF(errorHandler);
7624 Py_XDECREF(exc);
7625 return -1;
7626}
7627
7628static int
7629charmap_decode_mapping(const char *s,
7630 Py_ssize_t size,
7631 PyObject *mapping,
7632 const char *errors,
7633 _PyUnicodeWriter *writer)
7634{
7635 const char *starts = s;
7636 const char *e;
7637 Py_ssize_t startinpos, endinpos;
7638 PyObject *errorHandler = NULL, *exc = NULL;
7639 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007640 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007641
7642 e = s + size;
7643
7644 while (s < e) {
7645 ch = *s;
7646
7647 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7648 key = PyLong_FromLong((long)ch);
7649 if (key == NULL)
7650 goto onError;
7651
7652 item = PyObject_GetItem(mapping, key);
7653 Py_DECREF(key);
7654 if (item == NULL) {
7655 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7656 /* No mapping found means: mapping is undefined. */
7657 PyErr_Clear();
7658 goto Undefined;
7659 } else
7660 goto onError;
7661 }
7662
7663 /* Apply mapping */
7664 if (item == Py_None)
7665 goto Undefined;
7666 if (PyLong_Check(item)) {
7667 long value = PyLong_AS_LONG(item);
7668 if (value == 0xFFFE)
7669 goto Undefined;
7670 if (value < 0 || value > MAX_UNICODE) {
7671 PyErr_Format(PyExc_TypeError,
7672 "character mapping must be in range(0x%lx)",
7673 (unsigned long)MAX_UNICODE + 1);
7674 goto onError;
7675 }
7676
7677 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7678 goto onError;
7679 }
7680 else if (PyUnicode_Check(item)) {
7681 if (PyUnicode_READY(item) == -1)
7682 goto onError;
7683 if (PyUnicode_GET_LENGTH(item) == 1) {
7684 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7685 if (value == 0xFFFE)
7686 goto Undefined;
7687 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7688 goto onError;
7689 }
7690 else {
7691 writer->overallocate = 1;
7692 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7693 goto onError;
7694 }
7695 }
7696 else {
7697 /* wrong return value */
7698 PyErr_SetString(PyExc_TypeError,
7699 "character mapping must return integer, None or str");
7700 goto onError;
7701 }
7702 Py_CLEAR(item);
7703 ++s;
7704 continue;
7705
7706Undefined:
7707 /* undefined mapping */
7708 Py_CLEAR(item);
7709 startinpos = s-starts;
7710 endinpos = startinpos+1;
7711 if (unicode_decode_call_errorhandler_writer(
7712 errors, &errorHandler,
7713 "charmap", "character maps to <undefined>",
7714 &starts, &e, &startinpos, &endinpos, &exc, &s,
7715 writer)) {
7716 goto onError;
7717 }
7718 }
7719 Py_XDECREF(errorHandler);
7720 Py_XDECREF(exc);
7721 return 0;
7722
7723onError:
7724 Py_XDECREF(item);
7725 Py_XDECREF(errorHandler);
7726 Py_XDECREF(exc);
7727 return -1;
7728}
7729
Alexander Belopolsky40018472011-02-26 01:02:56 +00007730PyObject *
7731PyUnicode_DecodeCharmap(const char *s,
7732 Py_ssize_t size,
7733 PyObject *mapping,
7734 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007735{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007736 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007737
Guido van Rossumd57fd912000-03-10 22:53:23 +00007738 /* Default to Latin-1 */
7739 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007741
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007743 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007744 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007745 writer.min_length = size;
7746 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007748
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007749 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007750 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7751 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007752 }
7753 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007754 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7755 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007757 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007758
Benjamin Peterson29060642009-01-31 22:14:21 +00007759 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007760 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761 return NULL;
7762}
7763
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764/* Charmap encoding: the lookup table */
7765
Alexander Belopolsky40018472011-02-26 01:02:56 +00007766struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007767 PyObject_HEAD
7768 unsigned char level1[32];
7769 int count2, count3;
7770 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007771};
7772
7773static PyObject*
7774encoding_map_size(PyObject *obj, PyObject* args)
7775{
7776 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007777 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007779}
7780
7781static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007782 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 PyDoc_STR("Return the size (in bytes) of this object") },
7784 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007785};
7786
7787static void
7788encoding_map_dealloc(PyObject* o)
7789{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007790 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007791}
7792
7793static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007794 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 "EncodingMap", /*tp_name*/
7796 sizeof(struct encoding_map), /*tp_basicsize*/
7797 0, /*tp_itemsize*/
7798 /* methods */
7799 encoding_map_dealloc, /*tp_dealloc*/
7800 0, /*tp_print*/
7801 0, /*tp_getattr*/
7802 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007803 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 0, /*tp_repr*/
7805 0, /*tp_as_number*/
7806 0, /*tp_as_sequence*/
7807 0, /*tp_as_mapping*/
7808 0, /*tp_hash*/
7809 0, /*tp_call*/
7810 0, /*tp_str*/
7811 0, /*tp_getattro*/
7812 0, /*tp_setattro*/
7813 0, /*tp_as_buffer*/
7814 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7815 0, /*tp_doc*/
7816 0, /*tp_traverse*/
7817 0, /*tp_clear*/
7818 0, /*tp_richcompare*/
7819 0, /*tp_weaklistoffset*/
7820 0, /*tp_iter*/
7821 0, /*tp_iternext*/
7822 encoding_map_methods, /*tp_methods*/
7823 0, /*tp_members*/
7824 0, /*tp_getset*/
7825 0, /*tp_base*/
7826 0, /*tp_dict*/
7827 0, /*tp_descr_get*/
7828 0, /*tp_descr_set*/
7829 0, /*tp_dictoffset*/
7830 0, /*tp_init*/
7831 0, /*tp_alloc*/
7832 0, /*tp_new*/
7833 0, /*tp_free*/
7834 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007835};
7836
7837PyObject*
7838PyUnicode_BuildEncodingMap(PyObject* string)
7839{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007840 PyObject *result;
7841 struct encoding_map *mresult;
7842 int i;
7843 int need_dict = 0;
7844 unsigned char level1[32];
7845 unsigned char level2[512];
7846 unsigned char *mlevel1, *mlevel2, *mlevel3;
7847 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007848 int kind;
7849 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007850 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007851 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007853 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854 PyErr_BadArgument();
7855 return NULL;
7856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007857 kind = PyUnicode_KIND(string);
7858 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007859 length = PyUnicode_GET_LENGTH(string);
7860 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007861 memset(level1, 0xFF, sizeof level1);
7862 memset(level2, 0xFF, sizeof level2);
7863
7864 /* If there isn't a one-to-one mapping of NULL to \0,
7865 or if there are non-BMP characters, we need to use
7866 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007867 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007869 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007871 ch = PyUnicode_READ(kind, data, i);
7872 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873 need_dict = 1;
7874 break;
7875 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007876 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007877 /* unmapped character */
7878 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007879 l1 = ch >> 11;
7880 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007881 if (level1[l1] == 0xFF)
7882 level1[l1] = count2++;
7883 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007884 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885 }
7886
7887 if (count2 >= 0xFF || count3 >= 0xFF)
7888 need_dict = 1;
7889
7890 if (need_dict) {
7891 PyObject *result = PyDict_New();
7892 PyObject *key, *value;
7893 if (!result)
7894 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007895 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007896 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007897 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007898 if (!key || !value)
7899 goto failed1;
7900 if (PyDict_SetItem(result, key, value) == -1)
7901 goto failed1;
7902 Py_DECREF(key);
7903 Py_DECREF(value);
7904 }
7905 return result;
7906 failed1:
7907 Py_XDECREF(key);
7908 Py_XDECREF(value);
7909 Py_DECREF(result);
7910 return NULL;
7911 }
7912
7913 /* Create a three-level trie */
7914 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7915 16*count2 + 128*count3 - 1);
7916 if (!result)
7917 return PyErr_NoMemory();
7918 PyObject_Init(result, &EncodingMapType);
7919 mresult = (struct encoding_map*)result;
7920 mresult->count2 = count2;
7921 mresult->count3 = count3;
7922 mlevel1 = mresult->level1;
7923 mlevel2 = mresult->level23;
7924 mlevel3 = mresult->level23 + 16*count2;
7925 memcpy(mlevel1, level1, 32);
7926 memset(mlevel2, 0xFF, 16*count2);
7927 memset(mlevel3, 0, 128*count3);
7928 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007929 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007931 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7932 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 /* unmapped character */
7934 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007935 o1 = ch>>11;
7936 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 i2 = 16*mlevel1[o1] + o2;
7938 if (mlevel2[i2] == 0xFF)
7939 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007940 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 i3 = 128*mlevel2[i2] + o3;
7942 mlevel3[i3] = i;
7943 }
7944 return result;
7945}
7946
7947static int
Victor Stinner22168992011-11-20 17:09:18 +01007948encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007949{
7950 struct encoding_map *map = (struct encoding_map*)mapping;
7951 int l1 = c>>11;
7952 int l2 = (c>>7) & 0xF;
7953 int l3 = c & 0x7F;
7954 int i;
7955
Victor Stinner22168992011-11-20 17:09:18 +01007956 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007958 if (c == 0)
7959 return 0;
7960 /* level 1*/
7961 i = map->level1[l1];
7962 if (i == 0xFF) {
7963 return -1;
7964 }
7965 /* level 2*/
7966 i = map->level23[16*i+l2];
7967 if (i == 0xFF) {
7968 return -1;
7969 }
7970 /* level 3 */
7971 i = map->level23[16*map->count2 + 128*i + l3];
7972 if (i == 0) {
7973 return -1;
7974 }
7975 return i;
7976}
7977
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978/* Lookup the character ch in the mapping. If the character
7979 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007980 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007982charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983{
Christian Heimes217cfd12007-12-02 14:31:20 +00007984 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985 PyObject *x;
7986
7987 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007989 x = PyObject_GetItem(mapping, w);
7990 Py_DECREF(w);
7991 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7993 /* No mapping found means: mapping is undefined. */
7994 PyErr_Clear();
7995 x = Py_None;
7996 Py_INCREF(x);
7997 return x;
7998 } else
7999 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008000 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008001 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008002 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008003 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 long value = PyLong_AS_LONG(x);
8005 if (value < 0 || value > 255) {
8006 PyErr_SetString(PyExc_TypeError,
8007 "character mapping must be in range(256)");
8008 Py_DECREF(x);
8009 return NULL;
8010 }
8011 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008012 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008013 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 /* wrong return value */
8017 PyErr_Format(PyExc_TypeError,
8018 "character mapping must return integer, bytes or None, not %.400s",
8019 x->ob_type->tp_name);
8020 Py_DECREF(x);
8021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 }
8023}
8024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008026charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008028 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8029 /* exponentially overallocate to minimize reallocations */
8030 if (requiredsize < 2*outsize)
8031 requiredsize = 2*outsize;
8032 if (_PyBytes_Resize(outobj, requiredsize))
8033 return -1;
8034 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035}
8036
Benjamin Peterson14339b62009-01-31 16:36:08 +00008037typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008039} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008040/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008041 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042 space is available. Return a new reference to the object that
8043 was put in the output buffer, or Py_None, if the mapping was undefined
8044 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008045 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008046static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008047charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008048 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 PyObject *rep;
8051 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008052 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053
Christian Heimes90aa7642007-12-19 02:45:37 +00008054 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008057 if (res == -1)
8058 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 if (outsize<requiredsize)
8060 if (charmapencode_resize(outobj, outpos, requiredsize))
8061 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008062 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 outstart[(*outpos)++] = (char)res;
8064 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065 }
8066
8067 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008068 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 Py_DECREF(rep);
8072 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008074 if (PyLong_Check(rep)) {
8075 Py_ssize_t requiredsize = *outpos+1;
8076 if (outsize<requiredsize)
8077 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8078 Py_DECREF(rep);
8079 return enc_EXCEPTION;
8080 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008081 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008082 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008083 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 else {
8085 const char *repchars = PyBytes_AS_STRING(rep);
8086 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8087 Py_ssize_t requiredsize = *outpos+repsize;
8088 if (outsize<requiredsize)
8089 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8090 Py_DECREF(rep);
8091 return enc_EXCEPTION;
8092 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008093 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 memcpy(outstart + *outpos, repchars, repsize);
8095 *outpos += repsize;
8096 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008097 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 Py_DECREF(rep);
8099 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008100}
8101
8102/* handle an error in PyUnicode_EncodeCharmap
8103 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008104static int
8105charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008106 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008108 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008109 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110{
8111 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008113 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008114 enum PyUnicode_Kind kind;
8115 void *data;
8116 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008118 Py_ssize_t collstartpos = *inpos;
8119 Py_ssize_t collendpos = *inpos+1;
8120 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 char *encoding = "charmap";
8122 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008124 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008125 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008126
Benjamin Petersonbac79492012-01-14 13:34:47 -05008127 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008128 return -1;
8129 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130 /* find all unencodable characters */
8131 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008133 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008134 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008135 val = encoding_map_lookup(ch, mapping);
8136 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 break;
8138 ++collendpos;
8139 continue;
8140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008142 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8143 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 if (rep==NULL)
8145 return -1;
8146 else if (rep!=Py_None) {
8147 Py_DECREF(rep);
8148 break;
8149 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008150 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 }
8153 /* cache callback name lookup
8154 * (if not done yet, i.e. it's the first error) */
8155 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 if ((errors==NULL) || (!strcmp(errors, "strict")))
8157 *known_errorHandler = 1;
8158 else if (!strcmp(errors, "replace"))
8159 *known_errorHandler = 2;
8160 else if (!strcmp(errors, "ignore"))
8161 *known_errorHandler = 3;
8162 else if (!strcmp(errors, "xmlcharrefreplace"))
8163 *known_errorHandler = 4;
8164 else
8165 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008166 }
8167 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008168 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008169 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008170 return -1;
8171 case 2: /* replace */
8172 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 x = charmapencode_output('?', mapping, res, respos);
8174 if (x==enc_EXCEPTION) {
8175 return -1;
8176 }
8177 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008178 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 return -1;
8180 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008181 }
8182 /* fall through */
8183 case 3: /* ignore */
8184 *inpos = collendpos;
8185 break;
8186 case 4: /* xmlcharrefreplace */
8187 /* generate replacement (temporarily (mis)uses p) */
8188 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008189 char buffer[2+29+1+1];
8190 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008191 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 for (cp = buffer; *cp; ++cp) {
8193 x = charmapencode_output(*cp, mapping, res, respos);
8194 if (x==enc_EXCEPTION)
8195 return -1;
8196 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008197 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 return -1;
8199 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008200 }
8201 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008202 *inpos = collendpos;
8203 break;
8204 default:
8205 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008206 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008208 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008210 if (PyBytes_Check(repunicode)) {
8211 /* Directly copy bytes result to output. */
8212 Py_ssize_t outsize = PyBytes_Size(*res);
8213 Py_ssize_t requiredsize;
8214 repsize = PyBytes_Size(repunicode);
8215 requiredsize = *respos + repsize;
8216 if (requiredsize > outsize)
8217 /* Make room for all additional bytes. */
8218 if (charmapencode_resize(res, respos, requiredsize)) {
8219 Py_DECREF(repunicode);
8220 return -1;
8221 }
8222 memcpy(PyBytes_AsString(*res) + *respos,
8223 PyBytes_AsString(repunicode), repsize);
8224 *respos += repsize;
8225 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008226 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008227 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008228 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008229 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008230 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008231 Py_DECREF(repunicode);
8232 return -1;
8233 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008234 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008235 data = PyUnicode_DATA(repunicode);
8236 kind = PyUnicode_KIND(repunicode);
8237 for (index = 0; index < repsize; index++) {
8238 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8239 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008241 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 return -1;
8243 }
8244 else if (x==enc_FAILED) {
8245 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008246 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 return -1;
8248 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008249 }
8250 *inpos = newpos;
8251 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 }
8253 return 0;
8254}
8255
Alexander Belopolsky40018472011-02-26 01:02:56 +00008256PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008257_PyUnicode_EncodeCharmap(PyObject *unicode,
8258 PyObject *mapping,
8259 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008260{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 /* output object */
8262 PyObject *res = NULL;
8263 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008264 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008265 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008267 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 PyObject *errorHandler = NULL;
8269 PyObject *exc = NULL;
8270 /* the following variable is used for caching string comparisons
8271 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8272 * 3=ignore, 4=xmlcharrefreplace */
8273 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008274 void *data;
8275 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276
Benjamin Petersonbac79492012-01-14 13:34:47 -05008277 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008278 return NULL;
8279 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008280 data = PyUnicode_DATA(unicode);
8281 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008282
Guido van Rossumd57fd912000-03-10 22:53:23 +00008283 /* Default to Latin-1 */
8284 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008286
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 /* allocate enough for a simple encoding without
8288 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008289 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 if (res == NULL)
8291 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008292 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008296 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008298 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (x==enc_EXCEPTION) /* error */
8300 goto onError;
8301 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008302 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 &exc,
8304 &known_errorHandler, &errorHandler, errors,
8305 &res, &respos)) {
8306 goto onError;
8307 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 else
8310 /* done with this character => adjust input position */
8311 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008312 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008313
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008315 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008316 if (_PyBytes_Resize(&res, respos) < 0)
8317 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008318
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319 Py_XDECREF(exc);
8320 Py_XDECREF(errorHandler);
8321 return res;
8322
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 Py_XDECREF(res);
8325 Py_XDECREF(exc);
8326 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008327 return NULL;
8328}
8329
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008330/* Deprecated */
8331PyObject *
8332PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8333 Py_ssize_t size,
8334 PyObject *mapping,
8335 const char *errors)
8336{
8337 PyObject *result;
8338 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8339 if (unicode == NULL)
8340 return NULL;
8341 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8342 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008343 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008344}
8345
Alexander Belopolsky40018472011-02-26 01:02:56 +00008346PyObject *
8347PyUnicode_AsCharmapString(PyObject *unicode,
8348 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008349{
8350 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 PyErr_BadArgument();
8352 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008354 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008355}
8356
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008358static void
8359make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008360 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008361 Py_ssize_t startpos, Py_ssize_t endpos,
8362 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008363{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008365 *exceptionObject = _PyUnicodeTranslateError_Create(
8366 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008367 }
8368 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8370 goto onError;
8371 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8372 goto onError;
8373 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8374 goto onError;
8375 return;
8376 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008377 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378 }
8379}
8380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381/* error handling callback helper:
8382 build arguments, call the callback and check the arguments,
8383 put the result into newpos and return the replacement string, which
8384 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008385static PyObject *
8386unicode_translate_call_errorhandler(const char *errors,
8387 PyObject **errorHandler,
8388 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008389 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008390 Py_ssize_t startpos, Py_ssize_t endpos,
8391 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008393 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008395 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008396 PyObject *restuple;
8397 PyObject *resunicode;
8398
8399 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 }
8404
8405 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008406 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409
8410 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008415 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 Py_DECREF(restuple);
8417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 }
8419 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 &resunicode, &i_newpos)) {
8421 Py_DECREF(restuple);
8422 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008424 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008425 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008426 else
8427 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008429 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 Py_DECREF(restuple);
8431 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008432 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433 Py_INCREF(resunicode);
8434 Py_DECREF(restuple);
8435 return resunicode;
8436}
8437
8438/* Lookup the character ch in the mapping and put the result in result,
8439 which must be decrefed by the caller.
8440 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008441static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008443{
Christian Heimes217cfd12007-12-02 14:31:20 +00008444 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445 PyObject *x;
8446
8447 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449 x = PyObject_GetItem(mapping, w);
8450 Py_DECREF(w);
8451 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8453 /* No mapping found means: use 1:1 mapping. */
8454 PyErr_Clear();
8455 *result = NULL;
8456 return 0;
8457 } else
8458 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459 }
8460 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 *result = x;
8462 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008464 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008466 if (value < 0 || value > MAX_UNICODE) {
8467 PyErr_Format(PyExc_ValueError,
8468 "character mapping must be in range(0x%x)",
8469 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 Py_DECREF(x);
8471 return -1;
8472 }
8473 *result = x;
8474 return 0;
8475 }
8476 else if (PyUnicode_Check(x)) {
8477 *result = x;
8478 return 0;
8479 }
8480 else {
8481 /* wrong return value */
8482 PyErr_SetString(PyExc_TypeError,
8483 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008484 Py_DECREF(x);
8485 return -1;
8486 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487}
Victor Stinner1194ea02014-04-04 19:37:40 +02008488
8489/* lookup the character, write the result into the writer.
8490 Return 1 if the result was written into the writer, return 0 if the mapping
8491 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008492static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008493charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8494 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495{
Victor Stinner1194ea02014-04-04 19:37:40 +02008496 PyObject *item;
8497
8498 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008500
8501 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008503 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008506 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008508
8509 if (item == Py_None) {
8510 Py_DECREF(item);
8511 return 0;
8512 }
8513
8514 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008515 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8516 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8517 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008518 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8519 Py_DECREF(item);
8520 return -1;
8521 }
8522 Py_DECREF(item);
8523 return 1;
8524 }
8525
8526 if (!PyUnicode_Check(item)) {
8527 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008529 }
8530
8531 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8532 Py_DECREF(item);
8533 return -1;
8534 }
8535
8536 Py_DECREF(item);
8537 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538}
8539
Victor Stinner89a76ab2014-04-05 11:44:04 +02008540static int
8541unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8542 Py_UCS1 *translate)
8543{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008544 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008545 int ret = 0;
8546
Victor Stinner89a76ab2014-04-05 11:44:04 +02008547 if (charmaptranslate_lookup(ch, mapping, &item)) {
8548 return -1;
8549 }
8550
8551 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008552 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008553 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008554 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008555 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008556 /* not found => default to 1:1 mapping */
8557 translate[ch] = ch;
8558 return 1;
8559 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008560 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008561 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008562 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8563 used it */
8564 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008565 /* invalid character or character outside ASCII:
8566 skip the fast translate */
8567 goto exit;
8568 }
8569 translate[ch] = (Py_UCS1)replace;
8570 }
8571 else if (PyUnicode_Check(item)) {
8572 Py_UCS4 replace;
8573
8574 if (PyUnicode_READY(item) == -1) {
8575 Py_DECREF(item);
8576 return -1;
8577 }
8578 if (PyUnicode_GET_LENGTH(item) != 1)
8579 goto exit;
8580
8581 replace = PyUnicode_READ_CHAR(item, 0);
8582 if (replace > 127)
8583 goto exit;
8584 translate[ch] = (Py_UCS1)replace;
8585 }
8586 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008587 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008588 goto exit;
8589 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008590 ret = 1;
8591
Benjamin Peterson1365de72014-04-07 20:15:41 -04008592 exit:
8593 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008594 return ret;
8595}
8596
8597/* Fast path for ascii => ascii translation. Return 1 if the whole string
8598 was translated into writer, return 0 if the input string was partially
8599 translated into writer, raise an exception and return -1 on error. */
8600static int
8601unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008602 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008603{
Victor Stinner872b2912014-04-05 14:27:07 +02008604 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008605 Py_ssize_t len;
8606 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008607 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008608
8609 if (PyUnicode_READY(input) == -1)
8610 return -1;
8611 if (!PyUnicode_IS_ASCII(input))
8612 return 0;
8613 len = PyUnicode_GET_LENGTH(input);
8614
Victor Stinner872b2912014-04-05 14:27:07 +02008615 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008616
8617 in = PyUnicode_1BYTE_DATA(input);
8618 end = in + len;
8619
8620 assert(PyUnicode_IS_ASCII(writer->buffer));
8621 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8622 out = PyUnicode_1BYTE_DATA(writer->buffer);
8623
Victor Stinner872b2912014-04-05 14:27:07 +02008624 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008625 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008626 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008627 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008628 int translate = unicode_fast_translate_lookup(mapping, ch,
8629 ascii_table);
8630 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008631 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008632 if (translate == 0)
8633 goto exit;
8634 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008635 }
Victor Stinner872b2912014-04-05 14:27:07 +02008636 if (ch2 == 0xfe) {
8637 if (ignore)
8638 continue;
8639 goto exit;
8640 }
8641 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008642 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008643 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008644 }
Victor Stinner872b2912014-04-05 14:27:07 +02008645 res = 1;
8646
8647exit:
8648 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8649 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008650}
8651
Alexander Belopolsky40018472011-02-26 01:02:56 +00008652PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653_PyUnicode_TranslateCharmap(PyObject *input,
8654 PyObject *mapping,
8655 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008656{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008658 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 Py_ssize_t size, i;
8660 int kind;
8661 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008662 _PyUnicodeWriter writer;
8663 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 char *reason = "character maps to <undefined>";
8665 PyObject *errorHandler = NULL;
8666 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008667 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008668 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669
Guido van Rossumd57fd912000-03-10 22:53:23 +00008670 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 PyErr_BadArgument();
8672 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 if (PyUnicode_READY(input) == -1)
8676 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008677 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 kind = PyUnicode_KIND(input);
8679 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008680
8681 if (size == 0) {
8682 Py_INCREF(input);
8683 return input;
8684 }
8685
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 /* allocate enough for a simple 1:1 translation without
8687 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008688 _PyUnicodeWriter_Init(&writer);
8689 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691
Victor Stinner872b2912014-04-05 14:27:07 +02008692 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8693
8694 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008695 if (res < 0) {
8696 _PyUnicodeWriter_Dealloc(&writer);
8697 return NULL;
8698 }
8699 if (res == 1)
8700 return _PyUnicodeWriter_Finish(&writer);
8701
Victor Stinner89a76ab2014-04-05 11:44:04 +02008702 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008705 int translate;
8706 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8707 Py_ssize_t newpos;
8708 /* startpos for collecting untranslatable chars */
8709 Py_ssize_t collstart;
8710 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008711 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008712
Victor Stinner1194ea02014-04-04 19:37:40 +02008713 ch = PyUnicode_READ(kind, data, i);
8714 translate = charmaptranslate_output(ch, mapping, &writer);
8715 if (translate < 0)
8716 goto onError;
8717
8718 if (translate != 0) {
8719 /* it worked => adjust input pointer */
8720 ++i;
8721 continue;
8722 }
8723
8724 /* untranslatable character */
8725 collstart = i;
8726 collend = i+1;
8727
8728 /* find all untranslatable characters */
8729 while (collend < size) {
8730 PyObject *x;
8731 ch = PyUnicode_READ(kind, data, collend);
8732 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008733 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008734 Py_XDECREF(x);
8735 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 ++collend;
8738 }
8739
8740 if (ignore) {
8741 i = collend;
8742 }
8743 else {
8744 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8745 reason, input, &exc,
8746 collstart, collend, &newpos);
8747 if (repunicode == NULL)
8748 goto onError;
8749 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008751 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008752 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008753 Py_DECREF(repunicode);
8754 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008755 }
8756 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008757 Py_XDECREF(exc);
8758 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008759 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008760
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008762 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763 Py_XDECREF(exc);
8764 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765 return NULL;
8766}
8767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008768/* Deprecated. Use PyUnicode_Translate instead. */
8769PyObject *
8770PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8771 Py_ssize_t size,
8772 PyObject *mapping,
8773 const char *errors)
8774{
Christian Heimes5f520f42012-09-11 14:03:25 +02008775 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8777 if (!unicode)
8778 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008779 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8780 Py_DECREF(unicode);
8781 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782}
8783
Alexander Belopolsky40018472011-02-26 01:02:56 +00008784PyObject *
8785PyUnicode_Translate(PyObject *str,
8786 PyObject *mapping,
8787 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008788{
8789 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008790
Guido van Rossumd57fd912000-03-10 22:53:23 +00008791 str = PyUnicode_FromObject(str);
8792 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008793 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008795 Py_DECREF(str);
8796 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008797}
Tim Petersced69f82003-09-16 20:30:58 +00008798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008800fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801{
8802 /* No need to call PyUnicode_READY(self) because this function is only
8803 called as a callback from fixup() which does it already. */
8804 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8805 const int kind = PyUnicode_KIND(self);
8806 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008807 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008808 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008809 Py_ssize_t i;
8810
8811 for (i = 0; i < len; ++i) {
8812 ch = PyUnicode_READ(kind, data, i);
8813 fixed = 0;
8814 if (ch > 127) {
8815 if (Py_UNICODE_ISSPACE(ch))
8816 fixed = ' ';
8817 else {
8818 const int decimal = Py_UNICODE_TODECIMAL(ch);
8819 if (decimal >= 0)
8820 fixed = '0' + decimal;
8821 }
8822 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008823 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008824 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008825 PyUnicode_WRITE(kind, data, i, fixed);
8826 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008827 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008828 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 }
8831
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008832 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833}
8834
8835PyObject *
8836_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8837{
8838 if (!PyUnicode_Check(unicode)) {
8839 PyErr_BadInternalCall();
8840 return NULL;
8841 }
8842 if (PyUnicode_READY(unicode) == -1)
8843 return NULL;
8844 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8845 /* If the string is already ASCII, just return the same string */
8846 Py_INCREF(unicode);
8847 return unicode;
8848 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008849 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008850}
8851
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008852PyObject *
8853PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8854 Py_ssize_t length)
8855{
Victor Stinnerf0124502011-11-21 23:12:56 +01008856 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008857 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008858 Py_UCS4 maxchar;
8859 enum PyUnicode_Kind kind;
8860 void *data;
8861
Victor Stinner99d7ad02012-02-22 13:37:39 +01008862 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008863 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008864 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008865 if (ch > 127) {
8866 int decimal = Py_UNICODE_TODECIMAL(ch);
8867 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008868 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008869 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008870 }
8871 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008872
8873 /* Copy to a new string */
8874 decimal = PyUnicode_New(length, maxchar);
8875 if (decimal == NULL)
8876 return decimal;
8877 kind = PyUnicode_KIND(decimal);
8878 data = PyUnicode_DATA(decimal);
8879 /* Iterate over code points */
8880 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008881 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008882 if (ch > 127) {
8883 int decimal = Py_UNICODE_TODECIMAL(ch);
8884 if (decimal >= 0)
8885 ch = '0' + decimal;
8886 }
8887 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008888 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008889 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008890}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008891/* --- Decimal Encoder ---------------------------------------------------- */
8892
Alexander Belopolsky40018472011-02-26 01:02:56 +00008893int
8894PyUnicode_EncodeDecimal(Py_UNICODE *s,
8895 Py_ssize_t length,
8896 char *output,
8897 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008898{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008899 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008900 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008901 enum PyUnicode_Kind kind;
8902 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008903
8904 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 PyErr_BadArgument();
8906 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008907 }
8908
Victor Stinner42bf7752011-11-21 22:52:58 +01008909 unicode = PyUnicode_FromUnicode(s, length);
8910 if (unicode == NULL)
8911 return -1;
8912
Benjamin Petersonbac79492012-01-14 13:34:47 -05008913 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008914 Py_DECREF(unicode);
8915 return -1;
8916 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008917 kind = PyUnicode_KIND(unicode);
8918 data = PyUnicode_DATA(unicode);
8919
Victor Stinnerb84d7232011-11-22 01:50:07 +01008920 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008921 PyObject *exc;
8922 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008924 Py_ssize_t startpos;
8925
8926 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008927
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008929 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008930 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008932 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008933 decimal = Py_UNICODE_TODECIMAL(ch);
8934 if (decimal >= 0) {
8935 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008936 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008937 continue;
8938 }
8939 if (0 < ch && ch < 256) {
8940 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008941 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 continue;
8943 }
Victor Stinner6345be92011-11-25 20:09:01 +01008944
Victor Stinner42bf7752011-11-21 22:52:58 +01008945 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008946 exc = NULL;
8947 raise_encode_exception(&exc, "decimal", unicode,
8948 startpos, startpos+1,
8949 "invalid decimal Unicode string");
8950 Py_XDECREF(exc);
8951 Py_DECREF(unicode);
8952 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008953 }
8954 /* 0-terminate the output string */
8955 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008956 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008957 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008958}
8959
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960/* --- Helpers ------------------------------------------------------------ */
8961
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008962/* helper macro to fixup start/end slice values */
8963#define ADJUST_INDICES(start, end, len) \
8964 if (end > len) \
8965 end = len; \
8966 else if (end < 0) { \
8967 end += len; \
8968 if (end < 0) \
8969 end = 0; \
8970 } \
8971 if (start < 0) { \
8972 start += len; \
8973 if (start < 0) \
8974 start = 0; \
8975 }
8976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008978any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 Py_ssize_t start,
8980 Py_ssize_t end)
8981{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008982 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 void *buf1, *buf2;
8984 Py_ssize_t len1, len2, result;
8985
8986 kind1 = PyUnicode_KIND(s1);
8987 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008988 if (kind1 < kind2)
8989 return -1;
8990
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008991 len1 = PyUnicode_GET_LENGTH(s1);
8992 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008993 ADJUST_INDICES(start, end, len1);
8994 if (end - start < len2)
8995 return -1;
8996
8997 buf1 = PyUnicode_DATA(s1);
8998 buf2 = PyUnicode_DATA(s2);
8999 if (len2 == 1) {
9000 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9001 result = findchar((const char *)buf1 + kind1*start,
9002 kind1, end - start, ch, direction);
9003 if (result == -1)
9004 return -1;
9005 else
9006 return start + result;
9007 }
9008
9009 if (kind2 != kind1) {
9010 buf2 = _PyUnicode_AsKind(s2, kind1);
9011 if (!buf2)
9012 return -2;
9013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014
Victor Stinner794d5672011-10-10 03:21:36 +02009015 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009016 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009017 case PyUnicode_1BYTE_KIND:
9018 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9019 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9020 else
9021 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9022 break;
9023 case PyUnicode_2BYTE_KIND:
9024 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9025 break;
9026 case PyUnicode_4BYTE_KIND:
9027 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9028 break;
9029 default:
9030 assert(0); result = -2;
9031 }
9032 }
9033 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009034 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009035 case PyUnicode_1BYTE_KIND:
9036 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9037 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9038 else
9039 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9040 break;
9041 case PyUnicode_2BYTE_KIND:
9042 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9043 break;
9044 case PyUnicode_4BYTE_KIND:
9045 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9046 break;
9047 default:
9048 assert(0); result = -2;
9049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050 }
9051
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009052 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 PyMem_Free(buf2);
9054
9055 return result;
9056}
9057
9058Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009059_PyUnicode_InsertThousandsGrouping(
9060 PyObject *unicode, Py_ssize_t index,
9061 Py_ssize_t n_buffer,
9062 void *digits, Py_ssize_t n_digits,
9063 Py_ssize_t min_width,
9064 const char *grouping, PyObject *thousands_sep,
9065 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066{
Victor Stinner41a863c2012-02-24 00:37:51 +01009067 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009068 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009069 Py_ssize_t thousands_sep_len;
9070 Py_ssize_t len;
9071
9072 if (unicode != NULL) {
9073 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009074 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009075 }
9076 else {
9077 kind = PyUnicode_1BYTE_KIND;
9078 data = NULL;
9079 }
9080 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9081 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9082 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9083 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009084 if (thousands_sep_kind < kind) {
9085 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9086 if (!thousands_sep_data)
9087 return -1;
9088 }
9089 else {
9090 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9091 if (!data)
9092 return -1;
9093 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009094 }
9095
Benjamin Petersonead6b532011-12-20 17:23:42 -06009096 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009098 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009100 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009102 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009103 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009104 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009105 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009106 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009107 (Py_UCS1 *) 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_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009110 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009111 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009112 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009113 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009114 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009116 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009117 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009118 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009119 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009120 break;
9121 default:
9122 assert(0);
9123 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009125 if (unicode != NULL && thousands_sep_kind != kind) {
9126 if (thousands_sep_kind < kind)
9127 PyMem_Free(thousands_sep_data);
9128 else
9129 PyMem_Free(data);
9130 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009131 if (unicode == NULL) {
9132 *maxchar = 127;
9133 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009134 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009135 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009136 }
9137 }
9138 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139}
9140
9141
Alexander Belopolsky40018472011-02-26 01:02:56 +00009142Py_ssize_t
9143PyUnicode_Count(PyObject *str,
9144 PyObject *substr,
9145 Py_ssize_t start,
9146 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009148 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009149 PyObject* str_obj;
9150 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009151 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 void *buf1 = NULL, *buf2 = NULL;
9153 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009154
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009155 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009156 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009158 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009159 if (!sub_obj) {
9160 Py_DECREF(str_obj);
9161 return -1;
9162 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009163 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009164 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 Py_DECREF(str_obj);
9166 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009167 }
Tim Petersced69f82003-09-16 20:30:58 +00009168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 kind1 = PyUnicode_KIND(str_obj);
9170 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009171 if (kind1 < kind2) {
9172 Py_DECREF(sub_obj);
9173 Py_DECREF(str_obj);
9174 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009175 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009176
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 len1 = PyUnicode_GET_LENGTH(str_obj);
9178 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009180 if (end - start < len2) {
9181 Py_DECREF(sub_obj);
9182 Py_DECREF(str_obj);
9183 return 0;
9184 }
9185
9186 buf1 = PyUnicode_DATA(str_obj);
9187 buf2 = PyUnicode_DATA(sub_obj);
9188 if (kind2 != kind1) {
9189 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9190 if (!buf2)
9191 goto onError;
9192 }
9193
9194 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009196 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9197 result = asciilib_count(
9198 ((Py_UCS1*)buf1) + start, end - start,
9199 buf2, len2, PY_SSIZE_T_MAX
9200 );
9201 else
9202 result = ucs1lib_count(
9203 ((Py_UCS1*)buf1) + start, end - start,
9204 buf2, len2, PY_SSIZE_T_MAX
9205 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 break;
9207 case PyUnicode_2BYTE_KIND:
9208 result = ucs2lib_count(
9209 ((Py_UCS2*)buf1) + start, end - start,
9210 buf2, len2, PY_SSIZE_T_MAX
9211 );
9212 break;
9213 case PyUnicode_4BYTE_KIND:
9214 result = ucs4lib_count(
9215 ((Py_UCS4*)buf1) + start, end - start,
9216 buf2, len2, PY_SSIZE_T_MAX
9217 );
9218 break;
9219 default:
9220 assert(0); result = 0;
9221 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009222
9223 Py_DECREF(sub_obj);
9224 Py_DECREF(str_obj);
9225
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009226 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009227 PyMem_Free(buf2);
9228
Guido van Rossumd57fd912000-03-10 22:53:23 +00009229 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 onError:
9231 Py_DECREF(sub_obj);
9232 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009233 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 PyMem_Free(buf2);
9235 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236}
9237
Alexander Belopolsky40018472011-02-26 01:02:56 +00009238Py_ssize_t
9239PyUnicode_Find(PyObject *str,
9240 PyObject *sub,
9241 Py_ssize_t start,
9242 Py_ssize_t end,
9243 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009245 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009246
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009248 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009249 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009250 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009251 if (!sub) {
9252 Py_DECREF(str);
9253 return -2;
9254 }
9255 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9256 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009257 Py_DECREF(str);
9258 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009259 }
Tim Petersced69f82003-09-16 20:30:58 +00009260
Victor Stinner794d5672011-10-10 03:21:36 +02009261 result = any_find_slice(direction,
9262 str, sub, start, end
9263 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009264
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009266 Py_DECREF(sub);
9267
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268 return result;
9269}
9270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009271Py_ssize_t
9272PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9273 Py_ssize_t start, Py_ssize_t end,
9274 int direction)
9275{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009277 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009278 if (PyUnicode_READY(str) == -1)
9279 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009280 if (start < 0 || end < 0) {
9281 PyErr_SetString(PyExc_IndexError, "string index out of range");
9282 return -2;
9283 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009284 if (end > PyUnicode_GET_LENGTH(str))
9285 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009286 if (start >= end)
9287 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009289 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9290 kind, end-start, ch, direction);
9291 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009293 else
9294 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295}
9296
Alexander Belopolsky40018472011-02-26 01:02:56 +00009297static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009298tailmatch(PyObject *self,
9299 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009300 Py_ssize_t start,
9301 Py_ssize_t end,
9302 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009303{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304 int kind_self;
9305 int kind_sub;
9306 void *data_self;
9307 void *data_sub;
9308 Py_ssize_t offset;
9309 Py_ssize_t i;
9310 Py_ssize_t end_sub;
9311
9312 if (PyUnicode_READY(self) == -1 ||
9313 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009314 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315
9316 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009317 return 1;
9318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9320 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009321 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009322 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 kind_self = PyUnicode_KIND(self);
9325 data_self = PyUnicode_DATA(self);
9326 kind_sub = PyUnicode_KIND(substring);
9327 data_sub = PyUnicode_DATA(substring);
9328 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9329
9330 if (direction > 0)
9331 offset = end;
9332 else
9333 offset = start;
9334
9335 if (PyUnicode_READ(kind_self, data_self, offset) ==
9336 PyUnicode_READ(kind_sub, data_sub, 0) &&
9337 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9338 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9339 /* If both are of the same kind, memcmp is sufficient */
9340 if (kind_self == kind_sub) {
9341 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009342 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343 data_sub,
9344 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009345 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 }
9347 /* otherwise we have to compare each character by first accesing it */
9348 else {
9349 /* We do not need to compare 0 and len(substring)-1 because
9350 the if statement above ensured already that they are equal
9351 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009352 for (i = 1; i < end_sub; ++i) {
9353 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9354 PyUnicode_READ(kind_sub, data_sub, i))
9355 return 0;
9356 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009357 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009359 }
9360
9361 return 0;
9362}
9363
Alexander Belopolsky40018472011-02-26 01:02:56 +00009364Py_ssize_t
9365PyUnicode_Tailmatch(PyObject *str,
9366 PyObject *substr,
9367 Py_ssize_t start,
9368 Py_ssize_t end,
9369 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009371 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009372
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 str = PyUnicode_FromObject(str);
9374 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009375 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 substr = PyUnicode_FromObject(substr);
9377 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009378 Py_DECREF(str);
9379 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 }
Tim Petersced69f82003-09-16 20:30:58 +00009381
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009382 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 Py_DECREF(str);
9385 Py_DECREF(substr);
9386 return result;
9387}
9388
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389/* Apply fixfct filter to the Unicode object self and return a
9390 reference to the modified object */
9391
Alexander Belopolsky40018472011-02-26 01:02:56 +00009392static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009393fixup(PyObject *self,
9394 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396 PyObject *u;
9397 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009398 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009399
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009400 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009402 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009403 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 /* fix functions return the new maximum character in a string,
9406 if the kind of the resulting unicode object does not change,
9407 everything is fine. Otherwise we need to change the string kind
9408 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009409 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009410
9411 if (maxchar_new == 0) {
9412 /* no changes */;
9413 if (PyUnicode_CheckExact(self)) {
9414 Py_DECREF(u);
9415 Py_INCREF(self);
9416 return self;
9417 }
9418 else
9419 return u;
9420 }
9421
Victor Stinnere6abb482012-05-02 01:15:40 +02009422 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423
Victor Stinnereaab6042011-12-11 22:22:39 +01009424 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009426
9427 /* In case the maximum character changed, we need to
9428 convert the string to the new category. */
9429 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9430 if (v == NULL) {
9431 Py_DECREF(u);
9432 return NULL;
9433 }
9434 if (maxchar_new > maxchar_old) {
9435 /* If the maxchar increased so that the kind changed, not all
9436 characters are representable anymore and we need to fix the
9437 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009438 _PyUnicode_FastCopyCharacters(v, 0,
9439 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009440 maxchar_old = fixfct(v);
9441 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 }
9443 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009444 _PyUnicode_FastCopyCharacters(v, 0,
9445 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009447 Py_DECREF(u);
9448 assert(_PyUnicode_CheckConsistency(v, 1));
9449 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450}
9451
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009452static PyObject *
9453ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009455 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9456 char *resdata, *data = PyUnicode_DATA(self);
9457 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009458
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009459 res = PyUnicode_New(len, 127);
9460 if (res == NULL)
9461 return NULL;
9462 resdata = PyUnicode_DATA(res);
9463 if (lower)
9464 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009466 _Py_bytes_upper(resdata, data, len);
9467 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009468}
9469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009471handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009473 Py_ssize_t j;
9474 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009475 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009476 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009477
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009478 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9479
9480 where ! is a negation and \p{xxx} is a character with property xxx.
9481 */
9482 for (j = i - 1; j >= 0; j--) {
9483 c = PyUnicode_READ(kind, data, j);
9484 if (!_PyUnicode_IsCaseIgnorable(c))
9485 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009487 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9488 if (final_sigma) {
9489 for (j = i + 1; j < length; j++) {
9490 c = PyUnicode_READ(kind, data, j);
9491 if (!_PyUnicode_IsCaseIgnorable(c))
9492 break;
9493 }
9494 final_sigma = j == length || !_PyUnicode_IsCased(c);
9495 }
9496 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497}
9498
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009499static int
9500lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9501 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009503 /* Obscure special case. */
9504 if (c == 0x3A3) {
9505 mapped[0] = handle_capital_sigma(kind, data, length, i);
9506 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009508 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509}
9510
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009511static Py_ssize_t
9512do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009514 Py_ssize_t i, k = 0;
9515 int n_res, j;
9516 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009517
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009518 c = PyUnicode_READ(kind, data, 0);
9519 n_res = _PyUnicode_ToUpperFull(c, mapped);
9520 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009521 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009522 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009523 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009524 for (i = 1; i < length; i++) {
9525 c = PyUnicode_READ(kind, data, i);
9526 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9527 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009528 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009529 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009530 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009531 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009532 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009533}
9534
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009535static Py_ssize_t
9536do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9537 Py_ssize_t i, k = 0;
9538
9539 for (i = 0; i < length; i++) {
9540 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9541 int n_res, j;
9542 if (Py_UNICODE_ISUPPER(c)) {
9543 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9544 }
9545 else if (Py_UNICODE_ISLOWER(c)) {
9546 n_res = _PyUnicode_ToUpperFull(c, mapped);
9547 }
9548 else {
9549 n_res = 1;
9550 mapped[0] = c;
9551 }
9552 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009553 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009554 res[k++] = mapped[j];
9555 }
9556 }
9557 return k;
9558}
9559
9560static Py_ssize_t
9561do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9562 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009564 Py_ssize_t i, k = 0;
9565
9566 for (i = 0; i < length; i++) {
9567 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9568 int n_res, j;
9569 if (lower)
9570 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9571 else
9572 n_res = _PyUnicode_ToUpperFull(c, mapped);
9573 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009574 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009575 res[k++] = mapped[j];
9576 }
9577 }
9578 return k;
9579}
9580
9581static Py_ssize_t
9582do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9583{
9584 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9585}
9586
9587static Py_ssize_t
9588do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9589{
9590 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9591}
9592
Benjamin Petersone51757f2012-01-12 21:10:29 -05009593static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009594do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9595{
9596 Py_ssize_t i, k = 0;
9597
9598 for (i = 0; i < length; i++) {
9599 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9600 Py_UCS4 mapped[3];
9601 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9602 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009603 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009604 res[k++] = mapped[j];
9605 }
9606 }
9607 return k;
9608}
9609
9610static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009611do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9612{
9613 Py_ssize_t i, k = 0;
9614 int previous_is_cased;
9615
9616 previous_is_cased = 0;
9617 for (i = 0; i < length; i++) {
9618 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9619 Py_UCS4 mapped[3];
9620 int n_res, j;
9621
9622 if (previous_is_cased)
9623 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9624 else
9625 n_res = _PyUnicode_ToTitleFull(c, mapped);
9626
9627 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009628 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009629 res[k++] = mapped[j];
9630 }
9631
9632 previous_is_cased = _PyUnicode_IsCased(c);
9633 }
9634 return k;
9635}
9636
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637static PyObject *
9638case_operation(PyObject *self,
9639 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9640{
9641 PyObject *res = NULL;
9642 Py_ssize_t length, newlength = 0;
9643 int kind, outkind;
9644 void *data, *outdata;
9645 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9646
Benjamin Petersoneea48462012-01-16 14:28:50 -05009647 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648
9649 kind = PyUnicode_KIND(self);
9650 data = PyUnicode_DATA(self);
9651 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009652 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009653 PyErr_SetString(PyExc_OverflowError, "string is too long");
9654 return NULL;
9655 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009656 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009657 if (tmp == NULL)
9658 return PyErr_NoMemory();
9659 newlength = perform(kind, data, length, tmp, &maxchar);
9660 res = PyUnicode_New(newlength, maxchar);
9661 if (res == NULL)
9662 goto leave;
9663 tmpend = tmp + newlength;
9664 outdata = PyUnicode_DATA(res);
9665 outkind = PyUnicode_KIND(res);
9666 switch (outkind) {
9667 case PyUnicode_1BYTE_KIND:
9668 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9669 break;
9670 case PyUnicode_2BYTE_KIND:
9671 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9672 break;
9673 case PyUnicode_4BYTE_KIND:
9674 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9675 break;
9676 default:
9677 assert(0);
9678 break;
9679 }
9680 leave:
9681 PyMem_FREE(tmp);
9682 return res;
9683}
9684
Tim Peters8ce9f162004-08-27 01:49:32 +00009685PyObject *
9686PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009687{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009688 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009689 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009690 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009691 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009692 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9693 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009694 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009695 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009696 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009698 int use_memcpy;
9699 unsigned char *res_data = NULL, *sep_data = NULL;
9700 PyObject *last_obj;
9701 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009702
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009703 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009704 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009705 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009706 }
9707
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009708 /* NOTE: the following code can't call back into Python code,
9709 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009710 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009711
Tim Peters05eba1f2004-08-27 21:32:02 +00009712 seqlen = PySequence_Fast_GET_SIZE(fseq);
9713 /* If empty sequence, return u"". */
9714 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009715 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009716 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009717 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009718
Tim Peters05eba1f2004-08-27 21:32:02 +00009719 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009720 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009721 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009722 if (seqlen == 1) {
9723 if (PyUnicode_CheckExact(items[0])) {
9724 res = items[0];
9725 Py_INCREF(res);
9726 Py_DECREF(fseq);
9727 return res;
9728 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009729 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009730 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009731 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009732 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009733 /* Set up sep and seplen */
9734 if (separator == NULL) {
9735 /* fall back to a blank space separator */
9736 sep = PyUnicode_FromOrdinal(' ');
9737 if (!sep)
9738 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009739 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009740 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009741 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009742 else {
9743 if (!PyUnicode_Check(separator)) {
9744 PyErr_Format(PyExc_TypeError,
9745 "separator: expected str instance,"
9746 " %.80s found",
9747 Py_TYPE(separator)->tp_name);
9748 goto onError;
9749 }
9750 if (PyUnicode_READY(separator))
9751 goto onError;
9752 sep = separator;
9753 seplen = PyUnicode_GET_LENGTH(separator);
9754 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9755 /* inc refcount to keep this code path symmetric with the
9756 above case of a blank separator */
9757 Py_INCREF(sep);
9758 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009759 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009760 }
9761
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009762 /* There are at least two things to join, or else we have a subclass
9763 * of str in the sequence.
9764 * Do a pre-pass to figure out the total amount of space we'll
9765 * need (sz), and see whether all argument are strings.
9766 */
9767 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009768#ifdef Py_DEBUG
9769 use_memcpy = 0;
9770#else
9771 use_memcpy = 1;
9772#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009773 for (i = 0; i < seqlen; i++) {
9774 const Py_ssize_t old_sz = sz;
9775 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009776 if (!PyUnicode_Check(item)) {
9777 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009778 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009779 " %.80s found",
9780 i, Py_TYPE(item)->tp_name);
9781 goto onError;
9782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 if (PyUnicode_READY(item) == -1)
9784 goto onError;
9785 sz += PyUnicode_GET_LENGTH(item);
9786 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009787 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009788 if (i != 0)
9789 sz += seplen;
9790 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9791 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009792 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009793 goto onError;
9794 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009795 if (use_memcpy && last_obj != NULL) {
9796 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9797 use_memcpy = 0;
9798 }
9799 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009800 }
Tim Petersced69f82003-09-16 20:30:58 +00009801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009802 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009803 if (res == NULL)
9804 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009805
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009806 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009807#ifdef Py_DEBUG
9808 use_memcpy = 0;
9809#else
9810 if (use_memcpy) {
9811 res_data = PyUnicode_1BYTE_DATA(res);
9812 kind = PyUnicode_KIND(res);
9813 if (seplen != 0)
9814 sep_data = PyUnicode_1BYTE_DATA(sep);
9815 }
9816#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009817 if (use_memcpy) {
9818 for (i = 0; i < seqlen; ++i) {
9819 Py_ssize_t itemlen;
9820 item = items[i];
9821
9822 /* Copy item, and maybe the separator. */
9823 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009824 Py_MEMCPY(res_data,
9825 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009826 kind * seplen);
9827 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009828 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009829
9830 itemlen = PyUnicode_GET_LENGTH(item);
9831 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009832 Py_MEMCPY(res_data,
9833 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009834 kind * itemlen);
9835 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009836 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009837 }
9838 assert(res_data == PyUnicode_1BYTE_DATA(res)
9839 + kind * PyUnicode_GET_LENGTH(res));
9840 }
9841 else {
9842 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9843 Py_ssize_t itemlen;
9844 item = items[i];
9845
9846 /* Copy item, and maybe the separator. */
9847 if (i && seplen != 0) {
9848 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9849 res_offset += seplen;
9850 }
9851
9852 itemlen = PyUnicode_GET_LENGTH(item);
9853 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009854 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009855 res_offset += itemlen;
9856 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009857 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009858 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009859 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009860
Tim Peters05eba1f2004-08-27 21:32:02 +00009861 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009863 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009865
Benjamin Peterson29060642009-01-31 22:14:21 +00009866 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009867 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009869 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009870 return NULL;
9871}
9872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873#define FILL(kind, data, value, start, length) \
9874 do { \
9875 Py_ssize_t i_ = 0; \
9876 assert(kind != PyUnicode_WCHAR_KIND); \
9877 switch ((kind)) { \
9878 case PyUnicode_1BYTE_KIND: { \
9879 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009880 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 break; \
9882 } \
9883 case PyUnicode_2BYTE_KIND: { \
9884 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9885 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9886 break; \
9887 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009888 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9890 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9891 break; \
9892 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009893 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009894 } \
9895 } while (0)
9896
Victor Stinnerd3f08822012-05-29 12:57:52 +02009897void
9898_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9899 Py_UCS4 fill_char)
9900{
9901 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9902 const void *data = PyUnicode_DATA(unicode);
9903 assert(PyUnicode_IS_READY(unicode));
9904 assert(unicode_modifiable(unicode));
9905 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9906 assert(start >= 0);
9907 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9908 FILL(kind, data, fill_char, start, length);
9909}
9910
Victor Stinner3fe55312012-01-04 00:33:50 +01009911Py_ssize_t
9912PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9913 Py_UCS4 fill_char)
9914{
9915 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009916
9917 if (!PyUnicode_Check(unicode)) {
9918 PyErr_BadInternalCall();
9919 return -1;
9920 }
9921 if (PyUnicode_READY(unicode) == -1)
9922 return -1;
9923 if (unicode_check_modifiable(unicode))
9924 return -1;
9925
Victor Stinnerd3f08822012-05-29 12:57:52 +02009926 if (start < 0) {
9927 PyErr_SetString(PyExc_IndexError, "string index out of range");
9928 return -1;
9929 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009930 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9931 PyErr_SetString(PyExc_ValueError,
9932 "fill character is bigger than "
9933 "the string maximum character");
9934 return -1;
9935 }
9936
9937 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9938 length = Py_MIN(maxlen, length);
9939 if (length <= 0)
9940 return 0;
9941
Victor Stinnerd3f08822012-05-29 12:57:52 +02009942 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009943 return length;
9944}
9945
Victor Stinner9310abb2011-10-05 00:59:23 +02009946static PyObject *
9947pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009948 Py_ssize_t left,
9949 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 PyObject *u;
9953 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009954 int kind;
9955 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956
9957 if (left < 0)
9958 left = 0;
9959 if (right < 0)
9960 right = 0;
9961
Victor Stinnerc4b49542011-12-11 22:44:26 +01009962 if (left == 0 && right == 0)
9963 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9966 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009967 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9968 return NULL;
9969 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009971 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009973 if (!u)
9974 return NULL;
9975
9976 kind = PyUnicode_KIND(u);
9977 data = PyUnicode_DATA(u);
9978 if (left)
9979 FILL(kind, data, fill, 0, left);
9980 if (right)
9981 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009982 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009983 assert(_PyUnicode_CheckConsistency(u, 1));
9984 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985}
9986
Alexander Belopolsky40018472011-02-26 01:02:56 +00009987PyObject *
9988PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009989{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991
9992 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009993 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009994 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009995 if (PyUnicode_READY(string) == -1) {
9996 Py_DECREF(string);
9997 return NULL;
9998 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009999
Benjamin Petersonead6b532011-12-20 17:23:42 -060010000 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010001 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010002 if (PyUnicode_IS_ASCII(string))
10003 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010004 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010005 PyUnicode_GET_LENGTH(string), keepends);
10006 else
10007 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010008 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010009 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 break;
10011 case PyUnicode_2BYTE_KIND:
10012 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010013 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 PyUnicode_GET_LENGTH(string), keepends);
10015 break;
10016 case PyUnicode_4BYTE_KIND:
10017 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010018 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 PyUnicode_GET_LENGTH(string), keepends);
10020 break;
10021 default:
10022 assert(0);
10023 list = 0;
10024 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010025 Py_DECREF(string);
10026 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010027}
10028
Alexander Belopolsky40018472011-02-26 01:02:56 +000010029static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010030split(PyObject *self,
10031 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010032 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010034 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 void *buf1, *buf2;
10036 Py_ssize_t len1, len2;
10037 PyObject* out;
10038
Guido van Rossumd57fd912000-03-10 22:53:23 +000010039 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010040 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 if (PyUnicode_READY(self) == -1)
10043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010046 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010048 if (PyUnicode_IS_ASCII(self))
10049 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010050 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010051 PyUnicode_GET_LENGTH(self), maxcount
10052 );
10053 else
10054 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010055 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010056 PyUnicode_GET_LENGTH(self), maxcount
10057 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 case PyUnicode_2BYTE_KIND:
10059 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010060 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061 PyUnicode_GET_LENGTH(self), maxcount
10062 );
10063 case PyUnicode_4BYTE_KIND:
10064 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010065 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 PyUnicode_GET_LENGTH(self), maxcount
10067 );
10068 default:
10069 assert(0);
10070 return NULL;
10071 }
10072
10073 if (PyUnicode_READY(substring) == -1)
10074 return NULL;
10075
10076 kind1 = PyUnicode_KIND(self);
10077 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 len1 = PyUnicode_GET_LENGTH(self);
10079 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010080 if (kind1 < kind2 || len1 < len2) {
10081 out = PyList_New(1);
10082 if (out == NULL)
10083 return NULL;
10084 Py_INCREF(self);
10085 PyList_SET_ITEM(out, 0, self);
10086 return out;
10087 }
10088 buf1 = PyUnicode_DATA(self);
10089 buf2 = PyUnicode_DATA(substring);
10090 if (kind2 != kind1) {
10091 buf2 = _PyUnicode_AsKind(substring, kind1);
10092 if (!buf2)
10093 return NULL;
10094 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010095
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010096 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010098 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10099 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010100 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010101 else
10102 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010103 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 break;
10105 case PyUnicode_2BYTE_KIND:
10106 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010107 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 break;
10109 case PyUnicode_4BYTE_KIND:
10110 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010111 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 break;
10113 default:
10114 out = NULL;
10115 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010116 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 PyMem_Free(buf2);
10118 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010119}
10120
Alexander Belopolsky40018472011-02-26 01:02:56 +000010121static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010122rsplit(PyObject *self,
10123 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010124 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010125{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010126 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 void *buf1, *buf2;
10128 Py_ssize_t len1, len2;
10129 PyObject* out;
10130
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010131 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010132 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 if (PyUnicode_READY(self) == -1)
10135 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010138 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010140 if (PyUnicode_IS_ASCII(self))
10141 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010143 PyUnicode_GET_LENGTH(self), maxcount
10144 );
10145 else
10146 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010147 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 PyUnicode_GET_LENGTH(self), maxcount
10149 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 case PyUnicode_2BYTE_KIND:
10151 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010152 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 PyUnicode_GET_LENGTH(self), maxcount
10154 );
10155 case PyUnicode_4BYTE_KIND:
10156 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010157 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 PyUnicode_GET_LENGTH(self), maxcount
10159 );
10160 default:
10161 assert(0);
10162 return NULL;
10163 }
10164
10165 if (PyUnicode_READY(substring) == -1)
10166 return NULL;
10167
10168 kind1 = PyUnicode_KIND(self);
10169 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 len1 = PyUnicode_GET_LENGTH(self);
10171 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010172 if (kind1 < kind2 || len1 < len2) {
10173 out = PyList_New(1);
10174 if (out == NULL)
10175 return NULL;
10176 Py_INCREF(self);
10177 PyList_SET_ITEM(out, 0, self);
10178 return out;
10179 }
10180 buf1 = PyUnicode_DATA(self);
10181 buf2 = PyUnicode_DATA(substring);
10182 if (kind2 != kind1) {
10183 buf2 = _PyUnicode_AsKind(substring, kind1);
10184 if (!buf2)
10185 return NULL;
10186 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010188 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010190 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10191 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 else
10194 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 break;
10197 case PyUnicode_2BYTE_KIND:
10198 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010199 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 break;
10201 case PyUnicode_4BYTE_KIND:
10202 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010203 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 break;
10205 default:
10206 out = NULL;
10207 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010208 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 PyMem_Free(buf2);
10210 return out;
10211}
10212
10213static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010214anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10215 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010217 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10220 return asciilib_find(buf1, len1, buf2, len2, offset);
10221 else
10222 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 case PyUnicode_2BYTE_KIND:
10224 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10225 case PyUnicode_4BYTE_KIND:
10226 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10227 }
10228 assert(0);
10229 return -1;
10230}
10231
10232static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10234 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010236 switch (kind) {
10237 case PyUnicode_1BYTE_KIND:
10238 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10239 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10240 else
10241 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10242 case PyUnicode_2BYTE_KIND:
10243 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10244 case PyUnicode_4BYTE_KIND:
10245 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10246 }
10247 assert(0);
10248 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010249}
10250
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010251static void
10252replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10253 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10254{
10255 int kind = PyUnicode_KIND(u);
10256 void *data = PyUnicode_DATA(u);
10257 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10258 if (kind == PyUnicode_1BYTE_KIND) {
10259 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10260 (Py_UCS1 *)data + len,
10261 u1, u2, maxcount);
10262 }
10263 else if (kind == PyUnicode_2BYTE_KIND) {
10264 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10265 (Py_UCS2 *)data + len,
10266 u1, u2, maxcount);
10267 }
10268 else {
10269 assert(kind == PyUnicode_4BYTE_KIND);
10270 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10271 (Py_UCS4 *)data + len,
10272 u1, u2, maxcount);
10273 }
10274}
10275
Alexander Belopolsky40018472011-02-26 01:02:56 +000010276static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277replace(PyObject *self, PyObject *str1,
10278 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 PyObject *u;
10281 char *sbuf = PyUnicode_DATA(self);
10282 char *buf1 = PyUnicode_DATA(str1);
10283 char *buf2 = PyUnicode_DATA(str2);
10284 int srelease = 0, release1 = 0, release2 = 0;
10285 int skind = PyUnicode_KIND(self);
10286 int kind1 = PyUnicode_KIND(str1);
10287 int kind2 = PyUnicode_KIND(str2);
10288 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10289 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10290 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010291 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010292 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293
10294 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010295 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010297 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298
Victor Stinner59de0ee2011-10-07 10:01:28 +020010299 if (str1 == str2)
10300 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301
Victor Stinner49a0a212011-10-12 23:46:10 +020010302 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010303 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10304 if (maxchar < maxchar_str1)
10305 /* substring too wide to be present */
10306 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010307 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10308 /* Replacing str1 with str2 may cause a maxchar reduction in the
10309 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010310 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010311 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010314 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010316 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010318 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010319 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010320 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010321
Victor Stinner69ed0f42013-04-09 21:48:24 +020010322 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010323 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010324 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010325 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010326 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010328 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010330
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010331 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10332 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010333 }
10334 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 int rkind = skind;
10336 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010337 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 if (kind1 < rkind) {
10340 /* widen substring */
10341 buf1 = _PyUnicode_AsKind(str1, rkind);
10342 if (!buf1) goto error;
10343 release1 = 1;
10344 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010345 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010346 if (i < 0)
10347 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 if (rkind > kind2) {
10349 /* widen replacement */
10350 buf2 = _PyUnicode_AsKind(str2, rkind);
10351 if (!buf2) goto error;
10352 release2 = 1;
10353 }
10354 else if (rkind < kind2) {
10355 /* widen self and buf1 */
10356 rkind = kind2;
10357 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010358 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 sbuf = _PyUnicode_AsKind(self, rkind);
10360 if (!sbuf) goto error;
10361 srelease = 1;
10362 buf1 = _PyUnicode_AsKind(str1, rkind);
10363 if (!buf1) goto error;
10364 release1 = 1;
10365 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010366 u = PyUnicode_New(slen, maxchar);
10367 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010369 assert(PyUnicode_KIND(u) == rkind);
10370 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010371
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010372 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010373 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010374 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010378
10379 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010380 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010381 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010382 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010383 if (i == -1)
10384 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010385 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010387 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010389 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010390 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010391 }
10392 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010394 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 int rkind = skind;
10396 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010399 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 buf1 = _PyUnicode_AsKind(str1, rkind);
10401 if (!buf1) goto error;
10402 release1 = 1;
10403 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010404 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010405 if (n == 0)
10406 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010408 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 buf2 = _PyUnicode_AsKind(str2, rkind);
10410 if (!buf2) goto error;
10411 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010414 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 rkind = kind2;
10416 sbuf = _PyUnicode_AsKind(self, rkind);
10417 if (!sbuf) goto error;
10418 srelease = 1;
10419 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010420 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 buf1 = _PyUnicode_AsKind(str1, rkind);
10422 if (!buf1) goto error;
10423 release1 = 1;
10424 }
10425 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10426 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010427 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 PyErr_SetString(PyExc_OverflowError,
10429 "replace string is too long");
10430 goto error;
10431 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010432 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010433 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010434 _Py_INCREF_UNICODE_EMPTY();
10435 if (!unicode_empty)
10436 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010437 u = unicode_empty;
10438 goto done;
10439 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010440 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 PyErr_SetString(PyExc_OverflowError,
10442 "replace string is too long");
10443 goto error;
10444 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010445 u = PyUnicode_New(new_size, maxchar);
10446 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010448 assert(PyUnicode_KIND(u) == rkind);
10449 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 ires = i = 0;
10451 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010452 while (n-- > 0) {
10453 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010454 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010455 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010456 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010457 if (j == -1)
10458 break;
10459 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010460 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010461 memcpy(res + rkind * ires,
10462 sbuf + rkind * i,
10463 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010465 }
10466 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010468 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010470 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010472 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010474 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010477 memcpy(res + rkind * ires,
10478 sbuf + rkind * i,
10479 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010480 }
10481 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010482 /* interleave */
10483 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010484 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010486 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010488 if (--n <= 0)
10489 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010490 memcpy(res + rkind * ires,
10491 sbuf + rkind * i,
10492 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 ires++;
10494 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010495 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010496 memcpy(res + rkind * ires,
10497 sbuf + rkind * i,
10498 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010499 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010500 }
10501
10502 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010503 unicode_adjust_maxchar(&u);
10504 if (u == NULL)
10505 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010507
10508 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (srelease)
10510 PyMem_FREE(sbuf);
10511 if (release1)
10512 PyMem_FREE(buf1);
10513 if (release2)
10514 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010515 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010517
Benjamin Peterson29060642009-01-31 22:14:21 +000010518 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (srelease)
10521 PyMem_FREE(sbuf);
10522 if (release1)
10523 PyMem_FREE(buf1);
10524 if (release2)
10525 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010526 return unicode_result_unchanged(self);
10527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 error:
10529 if (srelease && sbuf)
10530 PyMem_FREE(sbuf);
10531 if (release1 && buf1)
10532 PyMem_FREE(buf1);
10533 if (release2 && buf2)
10534 PyMem_FREE(buf2);
10535 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536}
10537
10538/* --- Unicode Object Methods --------------------------------------------- */
10539
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010540PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010541 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542\n\
10543Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010544characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545
10546static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010547unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010548{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010549 if (PyUnicode_READY(self) == -1)
10550 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010551 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552}
10553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010554PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010555 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010556\n\
10557Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010558have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010559
10560static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010561unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010562{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010563 if (PyUnicode_READY(self) == -1)
10564 return NULL;
10565 if (PyUnicode_GET_LENGTH(self) == 0)
10566 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010567 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010568}
10569
Benjamin Petersond5890c82012-01-14 13:23:30 -050010570PyDoc_STRVAR(casefold__doc__,
10571 "S.casefold() -> str\n\
10572\n\
10573Return a version of S suitable for caseless comparisons.");
10574
10575static PyObject *
10576unicode_casefold(PyObject *self)
10577{
10578 if (PyUnicode_READY(self) == -1)
10579 return NULL;
10580 if (PyUnicode_IS_ASCII(self))
10581 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010582 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010583}
10584
10585
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010586/* Argument converter. Coerces to a single unicode character */
10587
10588static int
10589convert_uc(PyObject *obj, void *addr)
10590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010592 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010593
Benjamin Peterson14339b62009-01-31 16:36:08 +000010594 uniobj = PyUnicode_FromObject(obj);
10595 if (uniobj == NULL) {
10596 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010597 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010598 return 0;
10599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010601 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010602 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010603 Py_DECREF(uniobj);
10604 return 0;
10605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010607 Py_DECREF(uniobj);
10608 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010609}
10610
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010611PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010612 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010614Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010615done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616
10617static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010618unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010620 Py_ssize_t marg, left;
10621 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 Py_UCS4 fillchar = ' ';
10623
Victor Stinnere9a29352011-10-01 02:14:59 +020010624 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626
Benjamin Petersonbac79492012-01-14 13:34:47 -050010627 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628 return NULL;
10629
Victor Stinnerc4b49542011-12-11 22:44:26 +010010630 if (PyUnicode_GET_LENGTH(self) >= width)
10631 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632
Victor Stinnerc4b49542011-12-11 22:44:26 +010010633 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634 left = marg / 2 + (marg & width & 1);
10635
Victor Stinner9310abb2011-10-05 00:59:23 +020010636 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637}
10638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010639/* This function assumes that str1 and str2 are readied by the caller. */
10640
Marc-André Lemburge5034372000-08-08 08:04:29 +000010641static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010642unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010643{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010644#define COMPARE(TYPE1, TYPE2) \
10645 do { \
10646 TYPE1* p1 = (TYPE1 *)data1; \
10647 TYPE2* p2 = (TYPE2 *)data2; \
10648 TYPE1* end = p1 + len; \
10649 Py_UCS4 c1, c2; \
10650 for (; p1 != end; p1++, p2++) { \
10651 c1 = *p1; \
10652 c2 = *p2; \
10653 if (c1 != c2) \
10654 return (c1 < c2) ? -1 : 1; \
10655 } \
10656 } \
10657 while (0)
10658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 int kind1, kind2;
10660 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010661 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010662
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 kind1 = PyUnicode_KIND(str1);
10664 kind2 = PyUnicode_KIND(str2);
10665 data1 = PyUnicode_DATA(str1);
10666 data2 = PyUnicode_DATA(str2);
10667 len1 = PyUnicode_GET_LENGTH(str1);
10668 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010669 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010670
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010671 switch(kind1) {
10672 case PyUnicode_1BYTE_KIND:
10673 {
10674 switch(kind2) {
10675 case PyUnicode_1BYTE_KIND:
10676 {
10677 int cmp = memcmp(data1, data2, len);
10678 /* normalize result of memcmp() into the range [-1; 1] */
10679 if (cmp < 0)
10680 return -1;
10681 if (cmp > 0)
10682 return 1;
10683 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010684 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010685 case PyUnicode_2BYTE_KIND:
10686 COMPARE(Py_UCS1, Py_UCS2);
10687 break;
10688 case PyUnicode_4BYTE_KIND:
10689 COMPARE(Py_UCS1, Py_UCS4);
10690 break;
10691 default:
10692 assert(0);
10693 }
10694 break;
10695 }
10696 case PyUnicode_2BYTE_KIND:
10697 {
10698 switch(kind2) {
10699 case PyUnicode_1BYTE_KIND:
10700 COMPARE(Py_UCS2, Py_UCS1);
10701 break;
10702 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010703 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010704 COMPARE(Py_UCS2, Py_UCS2);
10705 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010706 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010707 case PyUnicode_4BYTE_KIND:
10708 COMPARE(Py_UCS2, Py_UCS4);
10709 break;
10710 default:
10711 assert(0);
10712 }
10713 break;
10714 }
10715 case PyUnicode_4BYTE_KIND:
10716 {
10717 switch(kind2) {
10718 case PyUnicode_1BYTE_KIND:
10719 COMPARE(Py_UCS4, Py_UCS1);
10720 break;
10721 case PyUnicode_2BYTE_KIND:
10722 COMPARE(Py_UCS4, Py_UCS2);
10723 break;
10724 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010725 {
10726#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10727 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10728 /* normalize result of wmemcmp() into the range [-1; 1] */
10729 if (cmp < 0)
10730 return -1;
10731 if (cmp > 0)
10732 return 1;
10733#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010734 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010735#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010736 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010737 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010738 default:
10739 assert(0);
10740 }
10741 break;
10742 }
10743 default:
10744 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010745 }
10746
Victor Stinner770e19e2012-10-04 22:59:45 +020010747 if (len1 == len2)
10748 return 0;
10749 if (len1 < len2)
10750 return -1;
10751 else
10752 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010753
10754#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010755}
10756
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010757Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010758unicode_compare_eq(PyObject *str1, PyObject *str2)
10759{
10760 int kind;
10761 void *data1, *data2;
10762 Py_ssize_t len;
10763 int cmp;
10764
Victor Stinnere5567ad2012-10-23 02:48:49 +020010765 len = PyUnicode_GET_LENGTH(str1);
10766 if (PyUnicode_GET_LENGTH(str2) != len)
10767 return 0;
10768 kind = PyUnicode_KIND(str1);
10769 if (PyUnicode_KIND(str2) != kind)
10770 return 0;
10771 data1 = PyUnicode_DATA(str1);
10772 data2 = PyUnicode_DATA(str2);
10773
10774 cmp = memcmp(data1, data2, len * kind);
10775 return (cmp == 0);
10776}
10777
10778
Alexander Belopolsky40018472011-02-26 01:02:56 +000010779int
10780PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10783 if (PyUnicode_READY(left) == -1 ||
10784 PyUnicode_READY(right) == -1)
10785 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010786
10787 /* a string is equal to itself */
10788 if (left == right)
10789 return 0;
10790
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010791 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010793 PyErr_Format(PyExc_TypeError,
10794 "Can't compare %.100s and %.100s",
10795 left->ob_type->tp_name,
10796 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797 return -1;
10798}
10799
Martin v. Löwis5b222132007-06-10 09:51:05 +000010800int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010801_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10802{
10803 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10804 if (right_str == NULL)
10805 return -1;
10806 return PyUnicode_Compare(left, right_str);
10807}
10808
10809int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010810PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10811{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 Py_ssize_t i;
10813 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010814 Py_UCS4 chr;
10815
Victor Stinner910337b2011-10-03 03:20:16 +020010816 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 if (PyUnicode_READY(uni) == -1)
10818 return -1;
10819 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010820 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010821 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010822 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010823 size_t len, len2 = strlen(str);
10824 int cmp;
10825
10826 len = Py_MIN(len1, len2);
10827 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010828 if (cmp != 0) {
10829 if (cmp < 0)
10830 return -1;
10831 else
10832 return 1;
10833 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010834 if (len1 > len2)
10835 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010836 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010837 return -1; /* str is longer */
10838 return 0;
10839 }
10840 else {
10841 void *data = PyUnicode_DATA(uni);
10842 /* Compare Unicode string and source character set string */
10843 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010844 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010845 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10846 /* This check keeps Python strings that end in '\0' from comparing equal
10847 to C strings identical up to that point. */
10848 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10849 return 1; /* uni is longer */
10850 if (str[i])
10851 return -1; /* str is longer */
10852 return 0;
10853 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010854}
10855
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010856
Benjamin Peterson29060642009-01-31 22:14:21 +000010857#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010858 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010859
Alexander Belopolsky40018472011-02-26 01:02:56 +000010860PyObject *
10861PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010862{
10863 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010864 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010865
Victor Stinnere5567ad2012-10-23 02:48:49 +020010866 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10867 Py_RETURN_NOTIMPLEMENTED;
10868
10869 if (PyUnicode_READY(left) == -1 ||
10870 PyUnicode_READY(right) == -1)
10871 return NULL;
10872
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010873 if (left == right) {
10874 switch (op) {
10875 case Py_EQ:
10876 case Py_LE:
10877 case Py_GE:
10878 /* a string is equal to itself */
10879 v = Py_True;
10880 break;
10881 case Py_NE:
10882 case Py_LT:
10883 case Py_GT:
10884 v = Py_False;
10885 break;
10886 default:
10887 PyErr_BadArgument();
10888 return NULL;
10889 }
10890 }
10891 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010892 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010893 result ^= (op == Py_NE);
10894 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010895 }
10896 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010897 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010898
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010899 /* Convert the return value to a Boolean */
10900 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010901 case Py_LE:
10902 v = TEST_COND(result <= 0);
10903 break;
10904 case Py_GE:
10905 v = TEST_COND(result >= 0);
10906 break;
10907 case Py_LT:
10908 v = TEST_COND(result == -1);
10909 break;
10910 case Py_GT:
10911 v = TEST_COND(result == 1);
10912 break;
10913 default:
10914 PyErr_BadArgument();
10915 return NULL;
10916 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010917 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010918 Py_INCREF(v);
10919 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010920}
10921
Alexander Belopolsky40018472011-02-26 01:02:56 +000010922int
10923PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010924{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010925 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010926 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 void *buf1, *buf2;
10928 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010929 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010930
10931 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010932 sub = PyUnicode_FromObject(element);
10933 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010934 PyErr_Format(PyExc_TypeError,
10935 "'in <string>' requires string as left operand, not %s",
10936 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010937 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010938 }
10939
Thomas Wouters477c8d52006-05-27 19:21:47 +000010940 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010941 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010942 Py_DECREF(sub);
10943 return -1;
10944 }
10945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946 kind1 = PyUnicode_KIND(str);
10947 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010948 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010950 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010951 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 }
10953 len1 = PyUnicode_GET_LENGTH(str);
10954 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010955 if (len1 < len2) {
10956 Py_DECREF(sub);
10957 Py_DECREF(str);
10958 return 0;
10959 }
10960 buf1 = PyUnicode_DATA(str);
10961 buf2 = PyUnicode_DATA(sub);
10962 if (len2 == 1) {
10963 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10964 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
10965 Py_DECREF(sub);
10966 Py_DECREF(str);
10967 return result;
10968 }
10969 if (kind2 != kind1) {
10970 buf2 = _PyUnicode_AsKind(sub, kind1);
10971 if (!buf2) {
10972 Py_DECREF(sub);
10973 Py_DECREF(str);
10974 return -1;
10975 }
10976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010977
Victor Stinner77282cb2013-04-14 19:22:47 +020010978 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010979 case PyUnicode_1BYTE_KIND:
10980 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10981 break;
10982 case PyUnicode_2BYTE_KIND:
10983 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10984 break;
10985 case PyUnicode_4BYTE_KIND:
10986 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10987 break;
10988 default:
10989 result = -1;
10990 assert(0);
10991 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010992
10993 Py_DECREF(str);
10994 Py_DECREF(sub);
10995
Victor Stinner77282cb2013-04-14 19:22:47 +020010996 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 PyMem_Free(buf2);
10998
Guido van Rossum403d68b2000-03-13 15:55:09 +000010999 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011000}
11001
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002/* Concat to string or Unicode object giving a new Unicode object. */
11003
Alexander Belopolsky40018472011-02-26 01:02:56 +000011004PyObject *
11005PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011008 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011009 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010
11011 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011012 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011014 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011017 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018
11019 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011020 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011021 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011024 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027 }
11028
Victor Stinner488fa492011-12-12 00:01:39 +010011029 u_len = PyUnicode_GET_LENGTH(u);
11030 v_len = PyUnicode_GET_LENGTH(v);
11031 if (u_len > PY_SSIZE_T_MAX - v_len) {
11032 PyErr_SetString(PyExc_OverflowError,
11033 "strings are too large to concat");
11034 goto onError;
11035 }
11036 new_len = u_len + v_len;
11037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011038 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011039 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011040 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011041
Guido van Rossumd57fd912000-03-10 22:53:23 +000011042 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011043 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011045 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011046 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11047 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011048 Py_DECREF(u);
11049 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011050 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011051 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
Benjamin Peterson29060642009-01-31 22:14:21 +000011053 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054 Py_XDECREF(u);
11055 Py_XDECREF(v);
11056 return NULL;
11057}
11058
Walter Dörwald1ab83302007-05-18 17:15:44 +000011059void
Victor Stinner23e56682011-10-03 03:54:37 +020011060PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011061{
Victor Stinner23e56682011-10-03 03:54:37 +020011062 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011063 Py_UCS4 maxchar, maxchar2;
11064 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011065
11066 if (p_left == NULL) {
11067 if (!PyErr_Occurred())
11068 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011069 return;
11070 }
Victor Stinner23e56682011-10-03 03:54:37 +020011071 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011072 if (right == NULL || left == NULL
11073 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011074 if (!PyErr_Occurred())
11075 PyErr_BadInternalCall();
11076 goto error;
11077 }
11078
Benjamin Petersonbac79492012-01-14 13:34:47 -050011079 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011080 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011081 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011082 goto error;
11083
Victor Stinner488fa492011-12-12 00:01:39 +010011084 /* Shortcuts */
11085 if (left == unicode_empty) {
11086 Py_DECREF(left);
11087 Py_INCREF(right);
11088 *p_left = right;
11089 return;
11090 }
11091 if (right == unicode_empty)
11092 return;
11093
11094 left_len = PyUnicode_GET_LENGTH(left);
11095 right_len = PyUnicode_GET_LENGTH(right);
11096 if (left_len > PY_SSIZE_T_MAX - right_len) {
11097 PyErr_SetString(PyExc_OverflowError,
11098 "strings are too large to concat");
11099 goto error;
11100 }
11101 new_len = left_len + right_len;
11102
11103 if (unicode_modifiable(left)
11104 && PyUnicode_CheckExact(right)
11105 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011106 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11107 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011108 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011109 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011110 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11111 {
11112 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011113 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011114 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011115
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011116 /* copy 'right' into the newly allocated area of 'left' */
11117 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011118 }
Victor Stinner488fa492011-12-12 00:01:39 +010011119 else {
11120 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11121 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011122 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011123
Victor Stinner488fa492011-12-12 00:01:39 +010011124 /* Concat the two Unicode strings */
11125 res = PyUnicode_New(new_len, maxchar);
11126 if (res == NULL)
11127 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011128 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11129 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011130 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011131 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011132 }
11133 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011134 return;
11135
11136error:
Victor Stinner488fa492011-12-12 00:01:39 +010011137 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011138}
11139
11140void
11141PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11142{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011143 PyUnicode_Append(pleft, right);
11144 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011145}
11146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011147PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011148 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011150Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011151string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011152interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153
11154static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011155unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011157 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011158 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011159 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011161 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 void *buf1, *buf2;
11163 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164
Jesus Ceaac451502011-04-20 17:09:23 +020011165 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11166 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011167 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 kind1 = PyUnicode_KIND(self);
11170 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011171 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011172 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011173 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011175 len1 = PyUnicode_GET_LENGTH(self);
11176 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011177 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011178 if (end - start < len2) {
11179 Py_DECREF(substring);
11180 return PyLong_FromLong(0);
11181 }
11182 buf1 = PyUnicode_DATA(self);
11183 buf2 = PyUnicode_DATA(substring);
11184 if (kind2 != kind1) {
11185 buf2 = _PyUnicode_AsKind(substring, kind1);
11186 if (!buf2) {
11187 Py_DECREF(substring);
11188 return NULL;
11189 }
11190 }
11191 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 case PyUnicode_1BYTE_KIND:
11193 iresult = ucs1lib_count(
11194 ((Py_UCS1*)buf1) + start, end - start,
11195 buf2, len2, PY_SSIZE_T_MAX
11196 );
11197 break;
11198 case PyUnicode_2BYTE_KIND:
11199 iresult = ucs2lib_count(
11200 ((Py_UCS2*)buf1) + start, end - start,
11201 buf2, len2, PY_SSIZE_T_MAX
11202 );
11203 break;
11204 case PyUnicode_4BYTE_KIND:
11205 iresult = ucs4lib_count(
11206 ((Py_UCS4*)buf1) + start, end - start,
11207 buf2, len2, PY_SSIZE_T_MAX
11208 );
11209 break;
11210 default:
11211 assert(0); iresult = 0;
11212 }
11213
11214 result = PyLong_FromSsize_t(iresult);
11215
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011216 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
11219 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011220
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221 return result;
11222}
11223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011224PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011225 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011227Encode S using the codec registered for encoding. Default encoding\n\
11228is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011229handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011230a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11231'xmlcharrefreplace' as well as any other name registered with\n\
11232codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233
11234static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011235unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011237 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 char *encoding = NULL;
11239 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011240
Benjamin Peterson308d6372009-09-18 21:42:35 +000011241 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11242 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011244 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011245}
11246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011247PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011248 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249\n\
11250Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011251If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252
11253static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011254unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011256 Py_ssize_t i, j, line_pos, src_len, incr;
11257 Py_UCS4 ch;
11258 PyObject *u;
11259 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011260 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011262 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011263 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
Ezio Melotti745d54d2013-11-16 19:10:57 +020011265 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11266 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268
Antoine Pitrou22425222011-10-04 19:10:51 +020011269 if (PyUnicode_READY(self) == -1)
11270 return NULL;
11271
Thomas Wouters7e474022000-07-16 12:04:32 +000011272 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011273 src_len = PyUnicode_GET_LENGTH(self);
11274 i = j = line_pos = 0;
11275 kind = PyUnicode_KIND(self);
11276 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011277 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 for (; i < src_len; i++) {
11279 ch = PyUnicode_READ(kind, src_data, i);
11280 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011281 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011283 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011285 goto overflow;
11286 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011287 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011288 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011289 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011291 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011292 goto overflow;
11293 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011295 if (ch == '\n' || ch == '\r')
11296 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011298 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011299 if (!found)
11300 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011301
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011303 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304 if (!u)
11305 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011306 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307
Antoine Pitroue71d5742011-10-04 15:55:09 +020011308 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309
Antoine Pitroue71d5742011-10-04 15:55:09 +020011310 for (; i < src_len; i++) {
11311 ch = PyUnicode_READ(kind, src_data, i);
11312 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011313 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011314 incr = tabsize - (line_pos % tabsize);
11315 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011316 FILL(kind, dest_data, ' ', j, incr);
11317 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011318 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011319 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011320 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011321 line_pos++;
11322 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011323 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011324 if (ch == '\n' || ch == '\r')
11325 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011327 }
11328 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011329 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011330
Antoine Pitroue71d5742011-10-04 15:55:09 +020011331 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011332 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11333 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334}
11335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011336PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011337 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338\n\
11339Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011340such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341arguments start and end are interpreted as in slice notation.\n\
11342\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011343Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344
11345static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011348 /* initialize variables to prevent gcc warning */
11349 PyObject *substring = NULL;
11350 Py_ssize_t start = 0;
11351 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011352 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
Jesus Ceaac451502011-04-20 17:09:23 +020011354 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11355 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357
Christian Heimesd47802e2013-06-29 21:33:36 +020011358 if (PyUnicode_READY(self) == -1) {
11359 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011361 }
11362 if (PyUnicode_READY(substring) == -1) {
11363 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011365 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366
Victor Stinner7931d9a2011-11-04 00:22:48 +010011367 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368
11369 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 if (result == -2)
11372 return NULL;
11373
Christian Heimes217cfd12007-12-02 14:31:20 +000011374 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375}
11376
11377static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011378unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011380 void *data;
11381 enum PyUnicode_Kind kind;
11382 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011383
11384 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11385 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011387 }
11388 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11389 PyErr_SetString(PyExc_IndexError, "string index out of range");
11390 return NULL;
11391 }
11392 kind = PyUnicode_KIND(self);
11393 data = PyUnicode_DATA(self);
11394 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011395 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396}
11397
Guido van Rossumc2504932007-09-18 19:42:40 +000011398/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011399 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011400static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011401unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402{
Guido van Rossumc2504932007-09-18 19:42:40 +000011403 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011404 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011405
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011406#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011407 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011408#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 if (_PyUnicode_HASH(self) != -1)
11410 return _PyUnicode_HASH(self);
11411 if (PyUnicode_READY(self) == -1)
11412 return -1;
11413 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011414 /*
11415 We make the hash of the empty string be 0, rather than using
11416 (prefix ^ suffix), since this slightly obfuscates the hash secret
11417 */
11418 if (len == 0) {
11419 _PyUnicode_HASH(self) = 0;
11420 return 0;
11421 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011422 x = _Py_HashBytes(PyUnicode_DATA(self),
11423 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011425 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426}
11427
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011428PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011429 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011431Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432
11433static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011436 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011437 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011438 PyObject *substring = NULL;
11439 Py_ssize_t start = 0;
11440 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441
Jesus Ceaac451502011-04-20 17:09:23 +020011442 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11443 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445
Christian Heimesd47a0452013-06-29 21:21:37 +020011446 if (PyUnicode_READY(self) == -1) {
11447 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011449 }
11450 if (PyUnicode_READY(substring) == -1) {
11451 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011453 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454
Victor Stinner7931d9a2011-11-04 00:22:48 +010011455 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456
11457 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (result == -2)
11460 return NULL;
11461
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 if (result < 0) {
11463 PyErr_SetString(PyExc_ValueError, "substring not found");
11464 return NULL;
11465 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011466
Christian Heimes217cfd12007-12-02 14:31:20 +000011467 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468}
11469
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011470PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011473Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011474at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
11476static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011477unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 Py_ssize_t i, length;
11480 int kind;
11481 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 int cased;
11483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 if (PyUnicode_READY(self) == -1)
11485 return NULL;
11486 length = PyUnicode_GET_LENGTH(self);
11487 kind = PyUnicode_KIND(self);
11488 data = PyUnicode_DATA(self);
11489
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 if (length == 1)
11492 return PyBool_FromLong(
11493 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011495 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011498
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 for (i = 0; i < length; i++) {
11501 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011502
Benjamin Peterson29060642009-01-31 22:14:21 +000011503 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11504 return PyBool_FromLong(0);
11505 else if (!cased && Py_UNICODE_ISLOWER(ch))
11506 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011508 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509}
11510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011511PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011514Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011515at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516
11517static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011518unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 Py_ssize_t i, length;
11521 int kind;
11522 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523 int cased;
11524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 if (PyUnicode_READY(self) == -1)
11526 return NULL;
11527 length = PyUnicode_GET_LENGTH(self);
11528 kind = PyUnicode_KIND(self);
11529 data = PyUnicode_DATA(self);
11530
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 if (length == 1)
11533 return PyBool_FromLong(
11534 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011536 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011538 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011539
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 for (i = 0; i < length; i++) {
11542 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011543
Benjamin Peterson29060642009-01-31 22:14:21 +000011544 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11545 return PyBool_FromLong(0);
11546 else if (!cased && Py_UNICODE_ISUPPER(ch))
11547 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011549 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550}
11551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011552PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011553 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011555Return True if S is a titlecased string and there is at least one\n\
11556character in S, i.e. upper- and titlecase characters may only\n\
11557follow uncased characters and lowercase characters only cased ones.\n\
11558Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559
11560static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011561unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011563 Py_ssize_t i, length;
11564 int kind;
11565 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566 int cased, previous_is_cased;
11567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 if (PyUnicode_READY(self) == -1)
11569 return NULL;
11570 length = PyUnicode_GET_LENGTH(self);
11571 kind = PyUnicode_KIND(self);
11572 data = PyUnicode_DATA(self);
11573
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (length == 1) {
11576 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11577 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11578 (Py_UNICODE_ISUPPER(ch) != 0));
11579 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011581 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011582 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011584
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585 cased = 0;
11586 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011587 for (i = 0; i < length; i++) {
11588 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011589
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11591 if (previous_is_cased)
11592 return PyBool_FromLong(0);
11593 previous_is_cased = 1;
11594 cased = 1;
11595 }
11596 else if (Py_UNICODE_ISLOWER(ch)) {
11597 if (!previous_is_cased)
11598 return PyBool_FromLong(0);
11599 previous_is_cased = 1;
11600 cased = 1;
11601 }
11602 else
11603 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011605 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606}
11607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011608PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011611Return True if all characters in S are whitespace\n\
11612and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
11614static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011615unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 Py_ssize_t i, length;
11618 int kind;
11619 void *data;
11620
11621 if (PyUnicode_READY(self) == -1)
11622 return NULL;
11623 length = PyUnicode_GET_LENGTH(self);
11624 kind = PyUnicode_KIND(self);
11625 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 if (length == 1)
11629 return PyBool_FromLong(
11630 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011632 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 for (i = 0; i < length; i++) {
11637 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011638 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011641 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642}
11643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011644PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011645 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011646\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011647Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011648and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649
11650static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011651unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 Py_ssize_t i, length;
11654 int kind;
11655 void *data;
11656
11657 if (PyUnicode_READY(self) == -1)
11658 return NULL;
11659 length = PyUnicode_GET_LENGTH(self);
11660 kind = PyUnicode_KIND(self);
11661 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011662
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011663 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011664 if (length == 1)
11665 return PyBool_FromLong(
11666 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011667
11668 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011670 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 for (i = 0; i < length; i++) {
11673 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011674 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011675 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011676 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011677}
11678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011679PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011680 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011681\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011682Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011683and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011684
11685static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011686unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011687{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 int kind;
11689 void *data;
11690 Py_ssize_t len, i;
11691
11692 if (PyUnicode_READY(self) == -1)
11693 return NULL;
11694
11695 kind = PyUnicode_KIND(self);
11696 data = PyUnicode_DATA(self);
11697 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011698
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011699 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 if (len == 1) {
11701 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11702 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11703 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011704
11705 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011707 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 for (i = 0; i < len; i++) {
11710 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011711 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011712 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011713 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011714 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011715}
11716
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011717PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011718 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011720Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011721False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722
11723static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011724unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 Py_ssize_t i, length;
11727 int kind;
11728 void *data;
11729
11730 if (PyUnicode_READY(self) == -1)
11731 return NULL;
11732 length = PyUnicode_GET_LENGTH(self);
11733 kind = PyUnicode_KIND(self);
11734 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737 if (length == 1)
11738 return PyBool_FromLong(
11739 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011741 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 for (i = 0; i < length; i++) {
11746 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011749 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750}
11751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011752PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011753 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011755Return True if all characters in S are digits\n\
11756and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757
11758static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011759unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761 Py_ssize_t i, length;
11762 int kind;
11763 void *data;
11764
11765 if (PyUnicode_READY(self) == -1)
11766 return NULL;
11767 length = PyUnicode_GET_LENGTH(self);
11768 kind = PyUnicode_KIND(self);
11769 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 if (length == 1) {
11773 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11774 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11775 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011777 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 for (i = 0; i < length; i++) {
11782 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011785 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786}
11787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011788PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011791Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011792False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793
11794static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011795unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797 Py_ssize_t i, length;
11798 int kind;
11799 void *data;
11800
11801 if (PyUnicode_READY(self) == -1)
11802 return NULL;
11803 length = PyUnicode_GET_LENGTH(self);
11804 kind = PyUnicode_KIND(self);
11805 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 if (length == 1)
11809 return PyBool_FromLong(
11810 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011812 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011814 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 for (i = 0; i < length; i++) {
11817 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011818 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011820 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821}
11822
Martin v. Löwis47383402007-08-15 07:32:56 +000011823int
11824PyUnicode_IsIdentifier(PyObject *self)
11825{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 int kind;
11827 void *data;
11828 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011829 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011831 if (PyUnicode_READY(self) == -1) {
11832 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 }
11835
11836 /* Special case for empty strings */
11837 if (PyUnicode_GET_LENGTH(self) == 0)
11838 return 0;
11839 kind = PyUnicode_KIND(self);
11840 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011841
11842 /* PEP 3131 says that the first character must be in
11843 XID_Start and subsequent characters in XID_Continue,
11844 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011845 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011846 letters, digits, underscore). However, given the current
11847 definition of XID_Start and XID_Continue, it is sufficient
11848 to check just for these, except that _ must be allowed
11849 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011851 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011852 return 0;
11853
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011854 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011855 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011856 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011857 return 1;
11858}
11859
11860PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011861 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011862\n\
11863Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011864to the language definition.\n\
11865\n\
11866Use keyword.iskeyword() to test for reserved identifiers\n\
11867such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011868
11869static PyObject*
11870unicode_isidentifier(PyObject *self)
11871{
11872 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11873}
11874
Georg Brandl559e5d72008-06-11 18:37:52 +000011875PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011876 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011877\n\
11878Return True if all characters in S are considered\n\
11879printable in repr() or S is empty, False otherwise.");
11880
11881static PyObject*
11882unicode_isprintable(PyObject *self)
11883{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 Py_ssize_t i, length;
11885 int kind;
11886 void *data;
11887
11888 if (PyUnicode_READY(self) == -1)
11889 return NULL;
11890 length = PyUnicode_GET_LENGTH(self);
11891 kind = PyUnicode_KIND(self);
11892 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011893
11894 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 if (length == 1)
11896 return PyBool_FromLong(
11897 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 for (i = 0; i < length; i++) {
11900 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011901 Py_RETURN_FALSE;
11902 }
11903 }
11904 Py_RETURN_TRUE;
11905}
11906
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011907PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011908 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909\n\
11910Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011911iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912
11913static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011914unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011916 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917}
11918
Martin v. Löwis18e16552006-02-15 17:27:45 +000011919static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011920unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 if (PyUnicode_READY(self) == -1)
11923 return -1;
11924 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011925}
11926
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011927PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011928 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011930Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011931done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932
11933static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011934unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011936 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 Py_UCS4 fillchar = ' ';
11938
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011939 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940 return NULL;
11941
Benjamin Petersonbac79492012-01-14 13:34:47 -050011942 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011943 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944
Victor Stinnerc4b49542011-12-11 22:44:26 +010011945 if (PyUnicode_GET_LENGTH(self) >= width)
11946 return unicode_result_unchanged(self);
11947
11948 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949}
11950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011951PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011952 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011954Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955
11956static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011957unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011959 if (PyUnicode_READY(self) == -1)
11960 return NULL;
11961 if (PyUnicode_IS_ASCII(self))
11962 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011963 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964}
11965
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011966#define LEFTSTRIP 0
11967#define RIGHTSTRIP 1
11968#define BOTHSTRIP 2
11969
11970/* Arrays indexed by above */
11971static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11972
11973#define STRIPNAME(i) (stripformat[i]+3)
11974
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011975/* externally visible for str.strip(unicode) */
11976PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011977_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 void *data;
11980 int kind;
11981 Py_ssize_t i, j, len;
11982 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011983 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11986 return NULL;
11987
11988 kind = PyUnicode_KIND(self);
11989 data = PyUnicode_DATA(self);
11990 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011991 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11993 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011994 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011995
Benjamin Peterson14339b62009-01-31 16:36:08 +000011996 i = 0;
11997 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011998 while (i < len) {
11999 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12000 if (!BLOOM(sepmask, ch))
12001 break;
12002 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12003 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 i++;
12005 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012006 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012007
Benjamin Peterson14339b62009-01-31 16:36:08 +000012008 j = len;
12009 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012010 j--;
12011 while (j >= i) {
12012 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12013 if (!BLOOM(sepmask, ch))
12014 break;
12015 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12016 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012017 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012018 }
12019
Benjamin Peterson29060642009-01-31 22:14:21 +000012020 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012021 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012022
Victor Stinner7931d9a2011-11-04 00:22:48 +010012023 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024}
12025
12026PyObject*
12027PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12028{
12029 unsigned char *data;
12030 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012031 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032
Victor Stinnerde636f32011-10-01 03:55:54 +020012033 if (PyUnicode_READY(self) == -1)
12034 return NULL;
12035
Victor Stinner684d5fd2012-05-03 02:32:34 +020012036 length = PyUnicode_GET_LENGTH(self);
12037 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012038
Victor Stinner684d5fd2012-05-03 02:32:34 +020012039 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012040 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041
Victor Stinnerde636f32011-10-01 03:55:54 +020012042 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012043 PyErr_SetString(PyExc_IndexError, "string index out of range");
12044 return NULL;
12045 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012046 if (start >= length || end < start)
12047 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012048
Victor Stinner684d5fd2012-05-03 02:32:34 +020012049 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012050 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012051 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012052 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012053 }
12054 else {
12055 kind = PyUnicode_KIND(self);
12056 data = PyUnicode_1BYTE_DATA(self);
12057 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012058 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012059 length);
12060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062
12063static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012064do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 Py_ssize_t len, i, j;
12067
12068 if (PyUnicode_READY(self) == -1)
12069 return NULL;
12070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012071 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012072
Victor Stinnercc7af722013-04-09 22:39:24 +020012073 if (PyUnicode_IS_ASCII(self)) {
12074 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12075
12076 i = 0;
12077 if (striptype != RIGHTSTRIP) {
12078 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012079 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012080 if (!_Py_ascii_whitespace[ch])
12081 break;
12082 i++;
12083 }
12084 }
12085
12086 j = len;
12087 if (striptype != LEFTSTRIP) {
12088 j--;
12089 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012090 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012091 if (!_Py_ascii_whitespace[ch])
12092 break;
12093 j--;
12094 }
12095 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012096 }
12097 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012098 else {
12099 int kind = PyUnicode_KIND(self);
12100 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012101
Victor Stinnercc7af722013-04-09 22:39:24 +020012102 i = 0;
12103 if (striptype != RIGHTSTRIP) {
12104 while (i < len) {
12105 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12106 if (!Py_UNICODE_ISSPACE(ch))
12107 break;
12108 i++;
12109 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012110 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012111
12112 j = len;
12113 if (striptype != LEFTSTRIP) {
12114 j--;
12115 while (j >= i) {
12116 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12117 if (!Py_UNICODE_ISSPACE(ch))
12118 break;
12119 j--;
12120 }
12121 j++;
12122 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012123 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012124
Victor Stinner7931d9a2011-11-04 00:22:48 +010012125 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126}
12127
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012128
12129static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012130do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012132 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133
Serhiy Storchakac6792272013-10-19 21:03:34 +030012134 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136
Benjamin Peterson14339b62009-01-31 16:36:08 +000012137 if (sep != NULL && sep != Py_None) {
12138 if (PyUnicode_Check(sep))
12139 return _PyUnicode_XStrip(self, striptype, sep);
12140 else {
12141 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012142 "%s arg must be None or str",
12143 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012144 return NULL;
12145 }
12146 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012147
Benjamin Peterson14339b62009-01-31 16:36:08 +000012148 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012149}
12150
12151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012152PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012154\n\
12155Return a copy of the string S with leading and trailing\n\
12156whitespace 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_strip(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, BOTHSTRIP); /* Common case */
12164 else
12165 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166}
12167
12168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012169PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012170 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012171\n\
12172Return a copy of the string S with leading 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_lstrip(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, LEFTSTRIP); /* Common case */
12180 else
12181 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012182}
12183
12184
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012185PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012186 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012187\n\
12188Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012189If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012190
12191static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012192unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012193{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012194 if (PyTuple_GET_SIZE(args) == 0)
12195 return do_strip(self, RIGHTSTRIP); /* Common case */
12196 else
12197 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012198}
12199
12200
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012202unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012204 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206
Serhiy Storchaka05997252013-01-26 12:14:02 +020012207 if (len < 1)
12208 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
Victor Stinnerc4b49542011-12-11 22:44:26 +010012210 /* no repeat, return original string */
12211 if (len == 1)
12212 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012213
Benjamin Petersonbac79492012-01-14 13:34:47 -050012214 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215 return NULL;
12216
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012217 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012218 PyErr_SetString(PyExc_OverflowError,
12219 "repeated string is too long");
12220 return NULL;
12221 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012223
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012224 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225 if (!u)
12226 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012227 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229 if (PyUnicode_GET_LENGTH(str) == 1) {
12230 const int kind = PyUnicode_KIND(str);
12231 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012232 if (kind == PyUnicode_1BYTE_KIND) {
12233 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012234 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012235 }
12236 else if (kind == PyUnicode_2BYTE_KIND) {
12237 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012238 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012239 ucs2[n] = fill_char;
12240 } else {
12241 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12242 assert(kind == PyUnicode_4BYTE_KIND);
12243 for (n = 0; n < len; ++n)
12244 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012246 }
12247 else {
12248 /* number of characters copied this far */
12249 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012250 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251 char *to = (char *) PyUnicode_DATA(u);
12252 Py_MEMCPY(to, PyUnicode_DATA(str),
12253 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255 n = (done <= nchars-done) ? done : nchars-done;
12256 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012257 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259 }
12260
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012261 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012262 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263}
12264
Alexander Belopolsky40018472011-02-26 01:02:56 +000012265PyObject *
12266PyUnicode_Replace(PyObject *obj,
12267 PyObject *subobj,
12268 PyObject *replobj,
12269 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270{
12271 PyObject *self;
12272 PyObject *str1;
12273 PyObject *str2;
12274 PyObject *result;
12275
12276 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012277 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012278 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012280 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012281 Py_DECREF(self);
12282 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283 }
12284 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012285 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012286 Py_DECREF(self);
12287 Py_DECREF(str1);
12288 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012290 if (PyUnicode_READY(self) == -1 ||
12291 PyUnicode_READY(str1) == -1 ||
12292 PyUnicode_READY(str2) == -1)
12293 result = NULL;
12294 else
12295 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296 Py_DECREF(self);
12297 Py_DECREF(str1);
12298 Py_DECREF(str2);
12299 return result;
12300}
12301
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012302PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012303 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012304\n\
12305Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012306old replaced by new. If the optional argument count is\n\
12307given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308
12309static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012311{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 PyObject *str1;
12313 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012314 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315 PyObject *result;
12316
Martin v. Löwis18e16552006-02-15 17:27:45 +000012317 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012319 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012320 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012322 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 return NULL;
12324 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012325 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012326 Py_DECREF(str1);
12327 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012328 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012329 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12330 result = NULL;
12331 else
12332 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333
12334 Py_DECREF(str1);
12335 Py_DECREF(str2);
12336 return result;
12337}
12338
Alexander Belopolsky40018472011-02-26 01:02:56 +000012339static PyObject *
12340unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012342 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 Py_ssize_t isize;
12344 Py_ssize_t osize, squote, dquote, i, o;
12345 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012346 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012350 return NULL;
12351
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 isize = PyUnicode_GET_LENGTH(unicode);
12353 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012354
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 /* Compute length of output, quote characters, and
12356 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012357 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 max = 127;
12359 squote = dquote = 0;
12360 ikind = PyUnicode_KIND(unicode);
12361 for (i = 0; i < isize; i++) {
12362 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012363 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012365 case '\'': squote++; break;
12366 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012368 incr = 2;
12369 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 default:
12371 /* Fast-path ASCII */
12372 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012373 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012375 ;
12376 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012379 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012381 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012383 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012385 if (osize > PY_SSIZE_T_MAX - incr) {
12386 PyErr_SetString(PyExc_OverflowError,
12387 "string is too long to generate repr");
12388 return NULL;
12389 }
12390 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 }
12392
12393 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012394 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012396 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 if (dquote)
12398 /* Both squote and dquote present. Use squote,
12399 and escape them */
12400 osize += squote;
12401 else
12402 quote = '"';
12403 }
Victor Stinner55c08782013-04-14 18:45:39 +020012404 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405
12406 repr = PyUnicode_New(osize, max);
12407 if (repr == NULL)
12408 return NULL;
12409 okind = PyUnicode_KIND(repr);
12410 odata = PyUnicode_DATA(repr);
12411
12412 PyUnicode_WRITE(okind, odata, 0, quote);
12413 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012414 if (unchanged) {
12415 _PyUnicode_FastCopyCharacters(repr, 1,
12416 unicode, 0,
12417 isize);
12418 }
12419 else {
12420 for (i = 0, o = 1; i < isize; i++) {
12421 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422
Victor Stinner55c08782013-04-14 18:45:39 +020012423 /* Escape quotes and backslashes */
12424 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012425 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012426 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012427 continue;
12428 }
12429
12430 /* Map special whitespace to '\t', \n', '\r' */
12431 if (ch == '\t') {
12432 PyUnicode_WRITE(okind, odata, o++, '\\');
12433 PyUnicode_WRITE(okind, odata, o++, 't');
12434 }
12435 else if (ch == '\n') {
12436 PyUnicode_WRITE(okind, odata, o++, '\\');
12437 PyUnicode_WRITE(okind, odata, o++, 'n');
12438 }
12439 else if (ch == '\r') {
12440 PyUnicode_WRITE(okind, odata, o++, '\\');
12441 PyUnicode_WRITE(okind, odata, o++, 'r');
12442 }
12443
12444 /* Map non-printable US ASCII to '\xhh' */
12445 else if (ch < ' ' || ch == 0x7F) {
12446 PyUnicode_WRITE(okind, odata, o++, '\\');
12447 PyUnicode_WRITE(okind, odata, o++, 'x');
12448 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12449 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12450 }
12451
12452 /* Copy ASCII characters as-is */
12453 else if (ch < 0x7F) {
12454 PyUnicode_WRITE(okind, odata, o++, ch);
12455 }
12456
12457 /* Non-ASCII characters */
12458 else {
12459 /* Map Unicode whitespace and control characters
12460 (categories Z* and C* except ASCII space)
12461 */
12462 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12463 PyUnicode_WRITE(okind, odata, o++, '\\');
12464 /* Map 8-bit characters to '\xhh' */
12465 if (ch <= 0xff) {
12466 PyUnicode_WRITE(okind, odata, o++, 'x');
12467 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12468 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12469 }
12470 /* Map 16-bit characters to '\uxxxx' */
12471 else if (ch <= 0xffff) {
12472 PyUnicode_WRITE(okind, odata, o++, 'u');
12473 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12474 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12475 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12476 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12477 }
12478 /* Map 21-bit characters to '\U00xxxxxx' */
12479 else {
12480 PyUnicode_WRITE(okind, odata, o++, 'U');
12481 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12482 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12483 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12484 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12485 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12486 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12487 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12488 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12489 }
12490 }
12491 /* Copy characters as-is */
12492 else {
12493 PyUnicode_WRITE(okind, odata, o++, ch);
12494 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012495 }
12496 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012497 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012499 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012500 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501}
12502
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012503PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012504 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505\n\
12506Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012507such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508arguments start and end are interpreted as in slice notation.\n\
12509\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012510Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511
12512static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012515 /* initialize variables to prevent gcc warning */
12516 PyObject *substring = NULL;
12517 Py_ssize_t start = 0;
12518 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520
Jesus Ceaac451502011-04-20 17:09:23 +020012521 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12522 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012523 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524
Christian Heimesea71a522013-06-29 21:17:34 +020012525 if (PyUnicode_READY(self) == -1) {
12526 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012527 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012528 }
12529 if (PyUnicode_READY(substring) == -1) {
12530 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012531 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533
Victor Stinner7931d9a2011-11-04 00:22:48 +010012534 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535
12536 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 if (result == -2)
12539 return NULL;
12540
Christian Heimes217cfd12007-12-02 14:31:20 +000012541 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542}
12543
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012544PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012545 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012547Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012548
12549static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012552 /* initialize variables to prevent gcc warning */
12553 PyObject *substring = NULL;
12554 Py_ssize_t start = 0;
12555 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557
Jesus Ceaac451502011-04-20 17:09:23 +020012558 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12559 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012560 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561
Christian Heimesea71a522013-06-29 21:17:34 +020012562 if (PyUnicode_READY(self) == -1) {
12563 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012565 }
12566 if (PyUnicode_READY(substring) == -1) {
12567 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570
Victor Stinner7931d9a2011-11-04 00:22:48 +010012571 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012572
12573 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 if (result == -2)
12576 return NULL;
12577
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578 if (result < 0) {
12579 PyErr_SetString(PyExc_ValueError, "substring not found");
12580 return NULL;
12581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582
Christian Heimes217cfd12007-12-02 14:31:20 +000012583 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584}
12585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012586PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012587 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012589Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012590done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591
12592static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012593unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012595 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012596 Py_UCS4 fillchar = ' ';
12597
Victor Stinnere9a29352011-10-01 02:14:59 +020012598 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012600
Benjamin Petersonbac79492012-01-14 13:34:47 -050012601 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602 return NULL;
12603
Victor Stinnerc4b49542011-12-11 22:44:26 +010012604 if (PyUnicode_GET_LENGTH(self) >= width)
12605 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606
Victor Stinnerc4b49542011-12-11 22:44:26 +010012607 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608}
12609
Alexander Belopolsky40018472011-02-26 01:02:56 +000012610PyObject *
12611PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612{
12613 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012614
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615 s = PyUnicode_FromObject(s);
12616 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012617 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012618 if (sep != NULL) {
12619 sep = PyUnicode_FromObject(sep);
12620 if (sep == NULL) {
12621 Py_DECREF(s);
12622 return NULL;
12623 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624 }
12625
Victor Stinner9310abb2011-10-05 00:59:23 +020012626 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627
12628 Py_DECREF(s);
12629 Py_XDECREF(sep);
12630 return result;
12631}
12632
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012633PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012634 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635\n\
12636Return a list of the words in S, using sep as the\n\
12637delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012638splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012639whitespace string is a separator and empty strings are\n\
12640removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641
12642static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012643unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012645 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012647 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012649 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12650 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651 return NULL;
12652
12653 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012654 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012656 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012658 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659}
12660
Thomas Wouters477c8d52006-05-27 19:21:47 +000012661PyObject *
12662PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12663{
12664 PyObject* str_obj;
12665 PyObject* sep_obj;
12666 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012667 int kind1, kind2;
12668 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012670
12671 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012672 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012673 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012674 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012675 if (!sep_obj) {
12676 Py_DECREF(str_obj);
12677 return NULL;
12678 }
12679 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12680 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012681 Py_DECREF(str_obj);
12682 return NULL;
12683 }
12684
Victor Stinner14f8f022011-10-05 20:58:25 +020012685 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 len1 = PyUnicode_GET_LENGTH(str_obj);
12688 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012689 if (kind1 < kind2 || len1 < len2) {
12690 _Py_INCREF_UNICODE_EMPTY();
12691 if (!unicode_empty)
12692 out = NULL;
12693 else {
12694 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12695 Py_DECREF(unicode_empty);
12696 }
12697 Py_DECREF(sep_obj);
12698 Py_DECREF(str_obj);
12699 return out;
12700 }
12701 buf1 = PyUnicode_DATA(str_obj);
12702 buf2 = PyUnicode_DATA(sep_obj);
12703 if (kind2 != kind1) {
12704 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12705 if (!buf2)
12706 goto onError;
12707 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012708
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012709 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012711 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12712 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12713 else
12714 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 break;
12716 case PyUnicode_2BYTE_KIND:
12717 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12718 break;
12719 case PyUnicode_4BYTE_KIND:
12720 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12721 break;
12722 default:
12723 assert(0);
12724 out = 0;
12725 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012726
12727 Py_DECREF(sep_obj);
12728 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012729 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012730 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012731
12732 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012733 onError:
12734 Py_DECREF(sep_obj);
12735 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012736 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012737 PyMem_Free(buf2);
12738 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012739}
12740
12741
12742PyObject *
12743PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12744{
12745 PyObject* str_obj;
12746 PyObject* sep_obj;
12747 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012748 int kind1, kind2;
12749 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012751
12752 str_obj = PyUnicode_FromObject(str_in);
12753 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012754 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012755 sep_obj = PyUnicode_FromObject(sep_in);
12756 if (!sep_obj) {
12757 Py_DECREF(str_obj);
12758 return NULL;
12759 }
12760
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012761 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 len1 = PyUnicode_GET_LENGTH(str_obj);
12764 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012765 if (kind1 < kind2 || len1 < len2) {
12766 _Py_INCREF_UNICODE_EMPTY();
12767 if (!unicode_empty)
12768 out = NULL;
12769 else {
12770 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12771 Py_DECREF(unicode_empty);
12772 }
12773 Py_DECREF(sep_obj);
12774 Py_DECREF(str_obj);
12775 return out;
12776 }
12777 buf1 = PyUnicode_DATA(str_obj);
12778 buf2 = PyUnicode_DATA(sep_obj);
12779 if (kind2 != kind1) {
12780 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12781 if (!buf2)
12782 goto onError;
12783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012785 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012786 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012787 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12788 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12789 else
12790 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791 break;
12792 case PyUnicode_2BYTE_KIND:
12793 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12794 break;
12795 case PyUnicode_4BYTE_KIND:
12796 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12797 break;
12798 default:
12799 assert(0);
12800 out = 0;
12801 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802
12803 Py_DECREF(sep_obj);
12804 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012805 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807
12808 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 onError:
12810 Py_DECREF(sep_obj);
12811 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012812 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 PyMem_Free(buf2);
12814 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815}
12816
12817PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012818 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012819\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012820Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012821the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012822found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012823
12824static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012825unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012826{
Victor Stinner9310abb2011-10-05 00:59:23 +020012827 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012828}
12829
12830PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012831 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012833Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012834the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012835separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836
12837static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012838unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012839{
Victor Stinner9310abb2011-10-05 00:59:23 +020012840 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012841}
12842
Alexander Belopolsky40018472011-02-26 01:02:56 +000012843PyObject *
12844PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012845{
12846 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012847
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012848 s = PyUnicode_FromObject(s);
12849 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012850 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012851 if (sep != NULL) {
12852 sep = PyUnicode_FromObject(sep);
12853 if (sep == NULL) {
12854 Py_DECREF(s);
12855 return NULL;
12856 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012857 }
12858
Victor Stinner9310abb2011-10-05 00:59:23 +020012859 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012860
12861 Py_DECREF(s);
12862 Py_XDECREF(sep);
12863 return result;
12864}
12865
12866PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012867 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012868\n\
12869Return a list of the words in S, using sep as the\n\
12870delimiter string, starting at the end of the string and\n\
12871working to the front. If maxsplit is given, at most maxsplit\n\
12872splits are done. If sep is not specified, any whitespace string\n\
12873is a separator.");
12874
12875static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012876unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012877{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012878 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012879 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012880 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012881
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012882 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12883 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012884 return NULL;
12885
12886 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012887 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012888 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012889 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012890 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012891 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012892}
12893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012894PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012895 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896\n\
12897Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012898Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012899is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900
12901static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012902unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012904 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012905 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012907 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12908 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012909 return NULL;
12910
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012911 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012912}
12913
12914static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012915PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012916{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012917 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918}
12919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012920PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012921 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012922\n\
12923Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012924and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012925
12926static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012927unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012928{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012929 if (PyUnicode_READY(self) == -1)
12930 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012931 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932}
12933
Larry Hastings61272b72014-01-07 12:41:53 -080012934/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012935
Larry Hastings31826802013-10-19 00:09:25 -070012936@staticmethod
12937str.maketrans as unicode_maketrans
12938
12939 x: object
12940
12941 y: unicode=NULL
12942
12943 z: unicode=NULL
12944
12945 /
12946
12947Return a translation table usable for str.translate().
12948
12949If there is only one argument, it must be a dictionary mapping Unicode
12950ordinals (integers) or characters to Unicode ordinals, strings or None.
12951Character keys will be then converted to ordinals.
12952If there are two arguments, they must be strings of equal length, and
12953in the resulting dictionary, each character in x will be mapped to the
12954character at the same position in y. If there is a third argument, it
12955must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012956[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012957
12958PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012959"maketrans(x, y=None, z=None, /)\n"
12960"--\n"
12961"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012962"Return a translation table usable for str.translate().\n"
12963"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012964"If there is only one argument, it must be a dictionary mapping Unicode\n"
12965"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12966"Character keys will be then converted to ordinals.\n"
12967"If there are two arguments, they must be strings of equal length, and\n"
12968"in the resulting dictionary, each character in x will be mapped to the\n"
12969"character at the same position in y. If there is a third argument, it\n"
12970"must be a string, whose characters will be mapped to None in the result.");
12971
12972#define UNICODE_MAKETRANS_METHODDEF \
12973 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12974
12975static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012976unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012977
12978static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012979unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012980{
Larry Hastings31826802013-10-19 00:09:25 -070012981 PyObject *return_value = NULL;
12982 PyObject *x;
12983 PyObject *y = NULL;
12984 PyObject *z = NULL;
12985
12986 if (!PyArg_ParseTuple(args,
12987 "O|UU:maketrans",
12988 &x, &y, &z))
12989 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012990 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012991
12992exit:
12993 return return_value;
12994}
12995
12996static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012997unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012998/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012999{
Georg Brandlceee0772007-11-27 23:48:05 +000013000 PyObject *new = NULL, *key, *value;
13001 Py_ssize_t i = 0;
13002 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013003
Georg Brandlceee0772007-11-27 23:48:05 +000013004 new = PyDict_New();
13005 if (!new)
13006 return NULL;
13007 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 int x_kind, y_kind, z_kind;
13009 void *x_data, *y_data, *z_data;
13010
Georg Brandlceee0772007-11-27 23:48:05 +000013011 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013012 if (!PyUnicode_Check(x)) {
13013 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13014 "be a string if there is a second argument");
13015 goto err;
13016 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013018 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13019 "arguments must have equal length");
13020 goto err;
13021 }
13022 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 x_kind = PyUnicode_KIND(x);
13024 y_kind = PyUnicode_KIND(y);
13025 x_data = PyUnicode_DATA(x);
13026 y_data = PyUnicode_DATA(y);
13027 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13028 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013029 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013030 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013031 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013032 if (!value) {
13033 Py_DECREF(key);
13034 goto err;
13035 }
Georg Brandlceee0772007-11-27 23:48:05 +000013036 res = PyDict_SetItem(new, key, value);
13037 Py_DECREF(key);
13038 Py_DECREF(value);
13039 if (res < 0)
13040 goto err;
13041 }
13042 /* create entries for deleting chars in z */
13043 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013044 z_kind = PyUnicode_KIND(z);
13045 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013046 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013047 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013048 if (!key)
13049 goto err;
13050 res = PyDict_SetItem(new, key, Py_None);
13051 Py_DECREF(key);
13052 if (res < 0)
13053 goto err;
13054 }
13055 }
13056 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013057 int kind;
13058 void *data;
13059
Georg Brandlceee0772007-11-27 23:48:05 +000013060 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013061 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013062 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13063 "to maketrans it must be a dict");
13064 goto err;
13065 }
13066 /* copy entries into the new dict, converting string keys to int keys */
13067 while (PyDict_Next(x, &i, &key, &value)) {
13068 if (PyUnicode_Check(key)) {
13069 /* convert string keys to integer keys */
13070 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013071 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013072 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13073 "table must be of length 1");
13074 goto err;
13075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013076 kind = PyUnicode_KIND(key);
13077 data = PyUnicode_DATA(key);
13078 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013079 if (!newkey)
13080 goto err;
13081 res = PyDict_SetItem(new, newkey, value);
13082 Py_DECREF(newkey);
13083 if (res < 0)
13084 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013085 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013086 /* just keep integer keys */
13087 if (PyDict_SetItem(new, key, value) < 0)
13088 goto err;
13089 } else {
13090 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13091 "be strings or integers");
13092 goto err;
13093 }
13094 }
13095 }
13096 return new;
13097 err:
13098 Py_DECREF(new);
13099 return NULL;
13100}
13101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013102PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013103 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104\n\
13105Return a copy of the string S, where all characters have been mapped\n\
13106through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013107Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013108Unmapped characters are left untouched. Characters mapped to None\n\
13109are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110
13111static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013112unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013114 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115}
13116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013117PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013118 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013120Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121
13122static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013123unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013125 if (PyUnicode_READY(self) == -1)
13126 return NULL;
13127 if (PyUnicode_IS_ASCII(self))
13128 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013129 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130}
13131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013132PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013133 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013134\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013135Pad a numeric string S with zeros on the left, to fill a field\n\
13136of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013137
13138static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013139unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013141 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013142 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013143 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 int kind;
13145 void *data;
13146 Py_UCS4 chr;
13147
Martin v. Löwis18e16552006-02-15 17:27:45 +000013148 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149 return NULL;
13150
Benjamin Petersonbac79492012-01-14 13:34:47 -050013151 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013152 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013153
Victor Stinnerc4b49542011-12-11 22:44:26 +010013154 if (PyUnicode_GET_LENGTH(self) >= width)
13155 return unicode_result_unchanged(self);
13156
13157 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158
13159 u = pad(self, fill, 0, '0');
13160
Walter Dörwald068325e2002-04-15 13:36:47 +000013161 if (u == NULL)
13162 return NULL;
13163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013164 kind = PyUnicode_KIND(u);
13165 data = PyUnicode_DATA(u);
13166 chr = PyUnicode_READ(kind, data, fill);
13167
13168 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013169 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013170 PyUnicode_WRITE(kind, data, 0, chr);
13171 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172 }
13173
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013174 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013175 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177
13178#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013179static PyObject *
13180unicode__decimal2ascii(PyObject *self)
13181{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013182 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013183}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184#endif
13185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013186PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013189Return True if S starts with the specified prefix, False otherwise.\n\
13190With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191With optional end, stop comparing S at that position.\n\
13192prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193
13194static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013195unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013196 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013198 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013199 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013200 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013201 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013202 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203
Jesus Ceaac451502011-04-20 17:09:23 +020013204 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013205 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013206 if (PyTuple_Check(subobj)) {
13207 Py_ssize_t i;
13208 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013209 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013210 if (substring == NULL)
13211 return NULL;
13212 result = tailmatch(self, substring, start, end, -1);
13213 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013214 if (result == -1)
13215 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013216 if (result) {
13217 Py_RETURN_TRUE;
13218 }
13219 }
13220 /* nothing matched */
13221 Py_RETURN_FALSE;
13222 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013223 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013224 if (substring == NULL) {
13225 if (PyErr_ExceptionMatches(PyExc_TypeError))
13226 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13227 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013229 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013230 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013232 if (result == -1)
13233 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013234 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235}
13236
13237
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013238PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013241Return True if S ends with the specified suffix, False otherwise.\n\
13242With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013243With optional end, stop comparing S at that position.\n\
13244suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245
13246static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013247unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013250 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013251 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013252 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013253 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013254 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255
Jesus Ceaac451502011-04-20 17:09:23 +020013256 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013257 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013258 if (PyTuple_Check(subobj)) {
13259 Py_ssize_t i;
13260 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013261 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013263 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013265 result = tailmatch(self, substring, start, end, +1);
13266 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013267 if (result == -1)
13268 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013269 if (result) {
13270 Py_RETURN_TRUE;
13271 }
13272 }
13273 Py_RETURN_FALSE;
13274 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013275 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013276 if (substring == NULL) {
13277 if (PyErr_ExceptionMatches(PyExc_TypeError))
13278 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13279 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013280 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013281 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013282 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013283 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013284 if (result == -1)
13285 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013286 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287}
13288
Victor Stinner202fdca2012-05-07 12:47:02 +020013289Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013290_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013291{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013292 if (!writer->readonly)
13293 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13294 else {
13295 /* Copy-on-write mode: set buffer size to 0 so
13296 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13297 * next write. */
13298 writer->size = 0;
13299 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013300 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13301 writer->data = PyUnicode_DATA(writer->buffer);
13302 writer->kind = PyUnicode_KIND(writer->buffer);
13303}
13304
Victor Stinnerd3f08822012-05-29 12:57:52 +020013305void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013306_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013307{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013308 memset(writer, 0, sizeof(*writer));
13309#ifdef Py_DEBUG
13310 writer->kind = 5; /* invalid kind */
13311#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013312 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013313}
13314
Victor Stinnerd3f08822012-05-29 12:57:52 +020013315int
13316_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13317 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013318{
Victor Stinner6989ba02013-11-18 21:08:39 +010013319#ifdef MS_WINDOWS
13320 /* On Windows, overallocate by 50% is the best factor */
13321# define OVERALLOCATE_FACTOR 2
13322#else
13323 /* On Linux, overallocate by 25% is the best factor */
13324# define OVERALLOCATE_FACTOR 4
13325#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013326 Py_ssize_t newlen;
13327 PyObject *newbuffer;
13328
Victor Stinnerd3f08822012-05-29 12:57:52 +020013329 assert(length > 0);
13330
Victor Stinner202fdca2012-05-07 12:47:02 +020013331 if (length > PY_SSIZE_T_MAX - writer->pos) {
13332 PyErr_NoMemory();
13333 return -1;
13334 }
13335 newlen = writer->pos + length;
13336
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013337 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013338
Victor Stinnerd3f08822012-05-29 12:57:52 +020013339 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013340 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013341 if (writer->overallocate
13342 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13343 /* overallocate to limit the number of realloc() */
13344 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013345 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013346 if (newlen < writer->min_length)
13347 newlen = writer->min_length;
13348
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349 writer->buffer = PyUnicode_New(newlen, maxchar);
13350 if (writer->buffer == NULL)
13351 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013352 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013353 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013354 if (writer->overallocate
13355 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13356 /* overallocate to limit the number of realloc() */
13357 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013358 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013359 if (newlen < writer->min_length)
13360 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013361
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013362 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013363 /* resize + widen */
13364 newbuffer = PyUnicode_New(newlen, maxchar);
13365 if (newbuffer == NULL)
13366 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013367 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13368 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013369 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013370 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013371 }
13372 else {
13373 newbuffer = resize_compact(writer->buffer, newlen);
13374 if (newbuffer == NULL)
13375 return -1;
13376 }
13377 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013378 }
13379 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013380 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013381 newbuffer = PyUnicode_New(writer->size, maxchar);
13382 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013383 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013384 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13385 writer->buffer, 0, writer->pos);
13386 Py_DECREF(writer->buffer);
13387 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013388 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013389 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013390 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013391
13392#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013393}
13394
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013395Py_LOCAL_INLINE(int)
13396_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013397{
13398 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13399 return -1;
13400 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13401 writer->pos++;
13402 return 0;
13403}
13404
13405int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013406_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13407{
13408 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13409}
13410
13411int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013412_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13413{
13414 Py_UCS4 maxchar;
13415 Py_ssize_t len;
13416
13417 if (PyUnicode_READY(str) == -1)
13418 return -1;
13419 len = PyUnicode_GET_LENGTH(str);
13420 if (len == 0)
13421 return 0;
13422 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13423 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013424 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013425 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013426 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013427 Py_INCREF(str);
13428 writer->buffer = str;
13429 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013430 writer->pos += len;
13431 return 0;
13432 }
13433 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13434 return -1;
13435 }
13436 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13437 str, 0, len);
13438 writer->pos += len;
13439 return 0;
13440}
13441
Victor Stinnere215d962012-10-06 23:03:36 +020013442int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013443_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13444 Py_ssize_t start, Py_ssize_t end)
13445{
13446 Py_UCS4 maxchar;
13447 Py_ssize_t len;
13448
13449 if (PyUnicode_READY(str) == -1)
13450 return -1;
13451
13452 assert(0 <= start);
13453 assert(end <= PyUnicode_GET_LENGTH(str));
13454 assert(start <= end);
13455
13456 if (end == 0)
13457 return 0;
13458
13459 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13460 return _PyUnicodeWriter_WriteStr(writer, str);
13461
13462 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13463 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13464 else
13465 maxchar = writer->maxchar;
13466 len = end - start;
13467
13468 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13469 return -1;
13470
13471 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13472 str, start, len);
13473 writer->pos += len;
13474 return 0;
13475}
13476
13477int
Victor Stinner4a587072013-11-19 12:54:53 +010013478_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13479 const char *ascii, Py_ssize_t len)
13480{
13481 if (len == -1)
13482 len = strlen(ascii);
13483
13484 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13485
13486 if (writer->buffer == NULL && !writer->overallocate) {
13487 PyObject *str;
13488
13489 str = _PyUnicode_FromASCII(ascii, len);
13490 if (str == NULL)
13491 return -1;
13492
13493 writer->readonly = 1;
13494 writer->buffer = str;
13495 _PyUnicodeWriter_Update(writer);
13496 writer->pos += len;
13497 return 0;
13498 }
13499
13500 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13501 return -1;
13502
13503 switch (writer->kind)
13504 {
13505 case PyUnicode_1BYTE_KIND:
13506 {
13507 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13508 Py_UCS1 *data = writer->data;
13509
13510 Py_MEMCPY(data + writer->pos, str, len);
13511 break;
13512 }
13513 case PyUnicode_2BYTE_KIND:
13514 {
13515 _PyUnicode_CONVERT_BYTES(
13516 Py_UCS1, Py_UCS2,
13517 ascii, ascii + len,
13518 (Py_UCS2 *)writer->data + writer->pos);
13519 break;
13520 }
13521 case PyUnicode_4BYTE_KIND:
13522 {
13523 _PyUnicode_CONVERT_BYTES(
13524 Py_UCS1, Py_UCS4,
13525 ascii, ascii + len,
13526 (Py_UCS4 *)writer->data + writer->pos);
13527 break;
13528 }
13529 default:
13530 assert(0);
13531 }
13532
13533 writer->pos += len;
13534 return 0;
13535}
13536
13537int
13538_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13539 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013540{
13541 Py_UCS4 maxchar;
13542
13543 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13544 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13545 return -1;
13546 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13547 writer->pos += len;
13548 return 0;
13549}
13550
Victor Stinnerd3f08822012-05-29 12:57:52 +020013551PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013552_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013553{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013554 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013555 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013556 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013557 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013559 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013560 str = writer->buffer;
13561 writer->buffer = NULL;
13562 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13563 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013564 }
13565 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13566 PyObject *newbuffer;
13567 newbuffer = resize_compact(writer->buffer, writer->pos);
13568 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013569 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013570 return NULL;
13571 }
13572 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013573 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013574 str = writer->buffer;
13575 writer->buffer = NULL;
13576 assert(_PyUnicode_CheckConsistency(str, 1));
13577 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013578}
13579
Victor Stinnerd3f08822012-05-29 12:57:52 +020013580void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013581_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013582{
13583 Py_CLEAR(writer->buffer);
13584}
13585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013586#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013587
13588PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013590\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013591Return a formatted version of S, using substitutions from args and kwargs.\n\
13592The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013593
Eric Smith27bbca62010-11-04 17:06:58 +000013594PyDoc_STRVAR(format_map__doc__,
13595 "S.format_map(mapping) -> str\n\
13596\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013597Return a formatted version of S, using substitutions from mapping.\n\
13598The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013599
Eric Smith4a7d76d2008-05-30 18:10:19 +000013600static PyObject *
13601unicode__format__(PyObject* self, PyObject* args)
13602{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013603 PyObject *format_spec;
13604 _PyUnicodeWriter writer;
13605 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013606
13607 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13608 return NULL;
13609
Victor Stinnerd3f08822012-05-29 12:57:52 +020013610 if (PyUnicode_READY(self) == -1)
13611 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013612 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013613 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13614 self, format_spec, 0,
13615 PyUnicode_GET_LENGTH(format_spec));
13616 if (ret == -1) {
13617 _PyUnicodeWriter_Dealloc(&writer);
13618 return NULL;
13619 }
13620 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013621}
13622
Eric Smith8c663262007-08-25 02:26:07 +000013623PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013625\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013626Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013627
13628static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013629unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013631 Py_ssize_t size;
13632
13633 /* If it's a compact object, account for base structure +
13634 character data. */
13635 if (PyUnicode_IS_COMPACT_ASCII(v))
13636 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13637 else if (PyUnicode_IS_COMPACT(v))
13638 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013639 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013640 else {
13641 /* If it is a two-block object, account for base object, and
13642 for character block if present. */
13643 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013644 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013645 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013646 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013647 }
13648 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013649 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013650 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013651 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013652 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013653 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013654
13655 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013656}
13657
13658PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013659 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013660
13661static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013662unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013663{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013664 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013665 if (!copy)
13666 return NULL;
13667 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013668}
13669
Guido van Rossumd57fd912000-03-10 22:53:23 +000013670static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013671 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013672 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013673 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13674 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013675 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13676 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013677 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013678 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13679 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13680 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013681 {"expandtabs", (PyCFunction) unicode_expandtabs,
13682 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013683 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013684 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013685 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13686 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13687 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013688 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013689 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13690 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13691 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013692 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013693 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013694 {"splitlines", (PyCFunction) unicode_splitlines,
13695 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013696 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013697 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13698 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13699 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13700 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13701 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13702 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13703 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13704 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13705 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13706 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13707 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13708 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13709 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13710 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013711 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013712 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013713 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013714 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013715 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013716 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013717 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013718 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013719#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013720 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013721 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013722#endif
13723
Benjamin Peterson14339b62009-01-31 16:36:08 +000013724 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013725 {NULL, NULL}
13726};
13727
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013728static PyObject *
13729unicode_mod(PyObject *v, PyObject *w)
13730{
Brian Curtindfc80e32011-08-10 20:28:54 -050013731 if (!PyUnicode_Check(v))
13732 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013734}
13735
13736static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013737 0, /*nb_add*/
13738 0, /*nb_subtract*/
13739 0, /*nb_multiply*/
13740 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013741};
13742
Guido van Rossumd57fd912000-03-10 22:53:23 +000013743static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013744 (lenfunc) unicode_length, /* sq_length */
13745 PyUnicode_Concat, /* sq_concat */
13746 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13747 (ssizeargfunc) unicode_getitem, /* sq_item */
13748 0, /* sq_slice */
13749 0, /* sq_ass_item */
13750 0, /* sq_ass_slice */
13751 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013752};
13753
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013754static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013755unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013757 if (PyUnicode_READY(self) == -1)
13758 return NULL;
13759
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013760 if (PyIndex_Check(item)) {
13761 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013762 if (i == -1 && PyErr_Occurred())
13763 return NULL;
13764 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013765 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013766 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013767 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013768 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013769 PyObject *result;
13770 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013771 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013772 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013776 return NULL;
13777 }
13778
13779 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013780 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013781 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013782 slicelength == PyUnicode_GET_LENGTH(self)) {
13783 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013784 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013785 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013786 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013787 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013788 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013789 src_kind = PyUnicode_KIND(self);
13790 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013791 if (!PyUnicode_IS_ASCII(self)) {
13792 kind_limit = kind_maxchar_limit(src_kind);
13793 max_char = 0;
13794 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13795 ch = PyUnicode_READ(src_kind, src_data, cur);
13796 if (ch > max_char) {
13797 max_char = ch;
13798 if (max_char >= kind_limit)
13799 break;
13800 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013801 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013802 }
Victor Stinner55c99112011-10-13 01:17:06 +020013803 else
13804 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013805 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013806 if (result == NULL)
13807 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013808 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013809 dest_data = PyUnicode_DATA(result);
13810
13811 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013812 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13813 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013814 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013815 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013816 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013817 } else {
13818 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13819 return NULL;
13820 }
13821}
13822
13823static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013824 (lenfunc)unicode_length, /* mp_length */
13825 (binaryfunc)unicode_subscript, /* mp_subscript */
13826 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013827};
13828
Guido van Rossumd57fd912000-03-10 22:53:23 +000013829
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830/* Helpers for PyUnicode_Format() */
13831
Victor Stinnera47082312012-10-04 02:19:54 +020013832struct unicode_formatter_t {
13833 PyObject *args;
13834 int args_owned;
13835 Py_ssize_t arglen, argidx;
13836 PyObject *dict;
13837
13838 enum PyUnicode_Kind fmtkind;
13839 Py_ssize_t fmtcnt, fmtpos;
13840 void *fmtdata;
13841 PyObject *fmtstr;
13842
13843 _PyUnicodeWriter writer;
13844};
13845
13846struct unicode_format_arg_t {
13847 Py_UCS4 ch;
13848 int flags;
13849 Py_ssize_t width;
13850 int prec;
13851 int sign;
13852};
13853
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013855unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013856{
Victor Stinnera47082312012-10-04 02:19:54 +020013857 Py_ssize_t argidx = ctx->argidx;
13858
13859 if (argidx < ctx->arglen) {
13860 ctx->argidx++;
13861 if (ctx->arglen < 0)
13862 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013863 else
Victor Stinnera47082312012-10-04 02:19:54 +020013864 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013865 }
13866 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868 return NULL;
13869}
13870
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013871/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013872
Victor Stinnera47082312012-10-04 02:19:54 +020013873/* Format a float into the writer if the writer is not NULL, or into *p_output
13874 otherwise.
13875
13876 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013877static int
Victor Stinnera47082312012-10-04 02:19:54 +020013878formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13879 PyObject **p_output,
13880 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013882 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013883 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013884 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013885 int prec;
13886 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013887
Guido van Rossumd57fd912000-03-10 22:53:23 +000013888 x = PyFloat_AsDouble(v);
13889 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013890 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013891
Victor Stinnera47082312012-10-04 02:19:54 +020013892 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013893 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013894 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013895
Victor Stinnera47082312012-10-04 02:19:54 +020013896 if (arg->flags & F_ALT)
13897 dtoa_flags = Py_DTSF_ALT;
13898 else
13899 dtoa_flags = 0;
13900 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013901 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013902 return -1;
13903 len = strlen(p);
13904 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013905 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013906 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013907 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013908 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013909 }
13910 else
13911 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013912 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013913 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013914}
13915
Victor Stinnerd0880d52012-04-27 23:40:13 +020013916/* formatlong() emulates the format codes d, u, o, x and X, and
13917 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13918 * Python's regular ints.
13919 * Return value: a new PyUnicodeObject*, or NULL if error.
13920 * The output string is of the form
13921 * "-"? ("0x" | "0X")? digit+
13922 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13923 * set in flags. The case of hex digits will be correct,
13924 * There will be at least prec digits, zero-filled on the left if
13925 * necessary to get that many.
13926 * val object to be converted
13927 * flags bitmask of format flags; only F_ALT is looked at
13928 * prec minimum number of digits; 0-fill on left if needed
13929 * type a character in [duoxX]; u acts the same as d
13930 *
13931 * CAUTION: o, x and X conversions on regular ints can never
13932 * produce a '-' sign, but can for Python's unbounded ints.
13933 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013934PyObject *
13935_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013936{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013937 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013938 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013939 Py_ssize_t i;
13940 int sign; /* 1 if '-', else 0 */
13941 int len; /* number of characters */
13942 Py_ssize_t llen;
13943 int numdigits; /* len == numnondigits + numdigits */
13944 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013945
Victor Stinnerd0880d52012-04-27 23:40:13 +020013946 /* Avoid exceeding SSIZE_T_MAX */
13947 if (prec > INT_MAX-3) {
13948 PyErr_SetString(PyExc_OverflowError,
13949 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013950 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013951 }
13952
13953 assert(PyLong_Check(val));
13954
13955 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013956 default:
13957 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013958 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013959 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013960 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013961 /* int and int subclasses should print numerically when a numeric */
13962 /* format code is used (see issue18780) */
13963 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013964 break;
13965 case 'o':
13966 numnondigits = 2;
13967 result = PyNumber_ToBase(val, 8);
13968 break;
13969 case 'x':
13970 case 'X':
13971 numnondigits = 2;
13972 result = PyNumber_ToBase(val, 16);
13973 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013974 }
13975 if (!result)
13976 return NULL;
13977
13978 assert(unicode_modifiable(result));
13979 assert(PyUnicode_IS_READY(result));
13980 assert(PyUnicode_IS_ASCII(result));
13981
13982 /* To modify the string in-place, there can only be one reference. */
13983 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013984 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013985 PyErr_BadInternalCall();
13986 return NULL;
13987 }
13988 buf = PyUnicode_DATA(result);
13989 llen = PyUnicode_GET_LENGTH(result);
13990 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013991 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013992 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013993 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013994 return NULL;
13995 }
13996 len = (int)llen;
13997 sign = buf[0] == '-';
13998 numnondigits += sign;
13999 numdigits = len - numnondigits;
14000 assert(numdigits > 0);
14001
14002 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014003 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014004 (type == 'o' || type == 'x' || type == 'X'))) {
14005 assert(buf[sign] == '0');
14006 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14007 buf[sign+1] == 'o');
14008 numnondigits -= 2;
14009 buf += 2;
14010 len -= 2;
14011 if (sign)
14012 buf[0] = '-';
14013 assert(len == numnondigits + numdigits);
14014 assert(numdigits > 0);
14015 }
14016
14017 /* Fill with leading zeroes to meet minimum width. */
14018 if (prec > numdigits) {
14019 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14020 numnondigits + prec);
14021 char *b1;
14022 if (!r1) {
14023 Py_DECREF(result);
14024 return NULL;
14025 }
14026 b1 = PyBytes_AS_STRING(r1);
14027 for (i = 0; i < numnondigits; ++i)
14028 *b1++ = *buf++;
14029 for (i = 0; i < prec - numdigits; i++)
14030 *b1++ = '0';
14031 for (i = 0; i < numdigits; i++)
14032 *b1++ = *buf++;
14033 *b1 = '\0';
14034 Py_DECREF(result);
14035 result = r1;
14036 buf = PyBytes_AS_STRING(result);
14037 len = numnondigits + prec;
14038 }
14039
14040 /* Fix up case for hex conversions. */
14041 if (type == 'X') {
14042 /* Need to convert all lower case letters to upper case.
14043 and need to convert 0x to 0X (and -0x to -0X). */
14044 for (i = 0; i < len; i++)
14045 if (buf[i] >= 'a' && buf[i] <= 'x')
14046 buf[i] -= 'a'-'A';
14047 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014048 if (!PyUnicode_Check(result)
14049 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014050 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014051 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014052 Py_DECREF(result);
14053 result = unicode;
14054 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014055 else if (len != PyUnicode_GET_LENGTH(result)) {
14056 if (PyUnicode_Resize(&result, len) < 0)
14057 Py_CLEAR(result);
14058 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014059 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014060}
14061
Ethan Furmandf3ed242014-01-05 06:50:30 -080014062/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014063 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014064 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014065 * -1 and raise an exception on error */
14066static int
Victor Stinnera47082312012-10-04 02:19:54 +020014067mainformatlong(PyObject *v,
14068 struct unicode_format_arg_t *arg,
14069 PyObject **p_output,
14070 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014071{
14072 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014073 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014074
14075 if (!PyNumber_Check(v))
14076 goto wrongtype;
14077
Ethan Furman9ab74802014-03-21 06:38:46 -070014078 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014079 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014080 if (type == 'o' || type == 'x' || type == 'X') {
14081 iobj = PyNumber_Index(v);
14082 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014083 if (PyErr_ExceptionMatches(PyExc_TypeError))
14084 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014085 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014086 }
14087 }
14088 else {
14089 iobj = PyNumber_Long(v);
14090 if (iobj == NULL ) {
14091 if (PyErr_ExceptionMatches(PyExc_TypeError))
14092 goto wrongtype;
14093 return -1;
14094 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 }
14096 assert(PyLong_Check(iobj));
14097 }
14098 else {
14099 iobj = v;
14100 Py_INCREF(iobj);
14101 }
14102
14103 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014104 && arg->width == -1 && arg->prec == -1
14105 && !(arg->flags & (F_SIGN | F_BLANK))
14106 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014107 {
14108 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014109 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014110 int base;
14111
Victor Stinnera47082312012-10-04 02:19:54 +020014112 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014113 {
14114 default:
14115 assert(0 && "'type' not in [diuoxX]");
14116 case 'd':
14117 case 'i':
14118 case 'u':
14119 base = 10;
14120 break;
14121 case 'o':
14122 base = 8;
14123 break;
14124 case 'x':
14125 case 'X':
14126 base = 16;
14127 break;
14128 }
14129
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014130 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14131 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014132 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014133 }
14134 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014135 return 1;
14136 }
14137
Ethan Furmanb95b5612015-01-23 20:05:18 -080014138 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014139 Py_DECREF(iobj);
14140 if (res == NULL)
14141 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014142 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014143 return 0;
14144
14145wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014146 switch(type)
14147 {
14148 case 'o':
14149 case 'x':
14150 case 'X':
14151 PyErr_Format(PyExc_TypeError,
14152 "%%%c format: an integer is required, "
14153 "not %.200s",
14154 type, Py_TYPE(v)->tp_name);
14155 break;
14156 default:
14157 PyErr_Format(PyExc_TypeError,
14158 "%%%c format: a number is required, "
14159 "not %.200s",
14160 type, Py_TYPE(v)->tp_name);
14161 break;
14162 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014163 return -1;
14164}
14165
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014166static Py_UCS4
14167formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014168{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014169 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014170 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014171 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014172 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014173 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014174 goto onError;
14175 }
14176 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014177 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014178 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014179 /* make sure number is a type of integer */
14180 if (!PyLong_Check(v)) {
14181 iobj = PyNumber_Index(v);
14182 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014183 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014184 }
14185 v = iobj;
14186 Py_DECREF(iobj);
14187 }
14188 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014189 x = PyLong_AsLong(v);
14190 if (x == -1 && PyErr_Occurred())
14191 goto onError;
14192
Victor Stinner8faf8212011-12-08 22:14:11 +010014193 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014194 PyErr_SetString(PyExc_OverflowError,
14195 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014196 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014197 }
14198
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014199 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014200 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014201
Benjamin Peterson29060642009-01-31 22:14:21 +000014202 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014203 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014204 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014205 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014206}
14207
Victor Stinnera47082312012-10-04 02:19:54 +020014208/* Parse options of an argument: flags, width, precision.
14209 Handle also "%(name)" syntax.
14210
14211 Return 0 if the argument has been formatted into arg->str.
14212 Return 1 if the argument has been written into ctx->writer,
14213 Raise an exception and return -1 on error. */
14214static int
14215unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14216 struct unicode_format_arg_t *arg)
14217{
14218#define FORMAT_READ(ctx) \
14219 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14220
14221 PyObject *v;
14222
Victor Stinnera47082312012-10-04 02:19:54 +020014223 if (arg->ch == '(') {
14224 /* Get argument value from a dictionary. Example: "%(name)s". */
14225 Py_ssize_t keystart;
14226 Py_ssize_t keylen;
14227 PyObject *key;
14228 int pcount = 1;
14229
14230 if (ctx->dict == NULL) {
14231 PyErr_SetString(PyExc_TypeError,
14232 "format requires a mapping");
14233 return -1;
14234 }
14235 ++ctx->fmtpos;
14236 --ctx->fmtcnt;
14237 keystart = ctx->fmtpos;
14238 /* Skip over balanced parentheses */
14239 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14240 arg->ch = FORMAT_READ(ctx);
14241 if (arg->ch == ')')
14242 --pcount;
14243 else if (arg->ch == '(')
14244 ++pcount;
14245 ctx->fmtpos++;
14246 }
14247 keylen = ctx->fmtpos - keystart - 1;
14248 if (ctx->fmtcnt < 0 || pcount > 0) {
14249 PyErr_SetString(PyExc_ValueError,
14250 "incomplete format key");
14251 return -1;
14252 }
14253 key = PyUnicode_Substring(ctx->fmtstr,
14254 keystart, keystart + keylen);
14255 if (key == NULL)
14256 return -1;
14257 if (ctx->args_owned) {
14258 Py_DECREF(ctx->args);
14259 ctx->args_owned = 0;
14260 }
14261 ctx->args = PyObject_GetItem(ctx->dict, key);
14262 Py_DECREF(key);
14263 if (ctx->args == NULL)
14264 return -1;
14265 ctx->args_owned = 1;
14266 ctx->arglen = -1;
14267 ctx->argidx = -2;
14268 }
14269
14270 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014271 while (--ctx->fmtcnt >= 0) {
14272 arg->ch = FORMAT_READ(ctx);
14273 ctx->fmtpos++;
14274 switch (arg->ch) {
14275 case '-': arg->flags |= F_LJUST; continue;
14276 case '+': arg->flags |= F_SIGN; continue;
14277 case ' ': arg->flags |= F_BLANK; continue;
14278 case '#': arg->flags |= F_ALT; continue;
14279 case '0': arg->flags |= F_ZERO; continue;
14280 }
14281 break;
14282 }
14283
14284 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014285 if (arg->ch == '*') {
14286 v = unicode_format_getnextarg(ctx);
14287 if (v == NULL)
14288 return -1;
14289 if (!PyLong_Check(v)) {
14290 PyErr_SetString(PyExc_TypeError,
14291 "* wants int");
14292 return -1;
14293 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014294 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014295 if (arg->width == -1 && PyErr_Occurred())
14296 return -1;
14297 if (arg->width < 0) {
14298 arg->flags |= F_LJUST;
14299 arg->width = -arg->width;
14300 }
14301 if (--ctx->fmtcnt >= 0) {
14302 arg->ch = FORMAT_READ(ctx);
14303 ctx->fmtpos++;
14304 }
14305 }
14306 else if (arg->ch >= '0' && arg->ch <= '9') {
14307 arg->width = arg->ch - '0';
14308 while (--ctx->fmtcnt >= 0) {
14309 arg->ch = FORMAT_READ(ctx);
14310 ctx->fmtpos++;
14311 if (arg->ch < '0' || arg->ch > '9')
14312 break;
14313 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14314 mixing signed and unsigned comparison. Since arg->ch is between
14315 '0' and '9', casting to int is safe. */
14316 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14317 PyErr_SetString(PyExc_ValueError,
14318 "width too big");
14319 return -1;
14320 }
14321 arg->width = arg->width*10 + (arg->ch - '0');
14322 }
14323 }
14324
14325 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014326 if (arg->ch == '.') {
14327 arg->prec = 0;
14328 if (--ctx->fmtcnt >= 0) {
14329 arg->ch = FORMAT_READ(ctx);
14330 ctx->fmtpos++;
14331 }
14332 if (arg->ch == '*') {
14333 v = unicode_format_getnextarg(ctx);
14334 if (v == NULL)
14335 return -1;
14336 if (!PyLong_Check(v)) {
14337 PyErr_SetString(PyExc_TypeError,
14338 "* wants int");
14339 return -1;
14340 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014341 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014342 if (arg->prec == -1 && PyErr_Occurred())
14343 return -1;
14344 if (arg->prec < 0)
14345 arg->prec = 0;
14346 if (--ctx->fmtcnt >= 0) {
14347 arg->ch = FORMAT_READ(ctx);
14348 ctx->fmtpos++;
14349 }
14350 }
14351 else if (arg->ch >= '0' && arg->ch <= '9') {
14352 arg->prec = arg->ch - '0';
14353 while (--ctx->fmtcnt >= 0) {
14354 arg->ch = FORMAT_READ(ctx);
14355 ctx->fmtpos++;
14356 if (arg->ch < '0' || arg->ch > '9')
14357 break;
14358 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14359 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014360 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014361 return -1;
14362 }
14363 arg->prec = arg->prec*10 + (arg->ch - '0');
14364 }
14365 }
14366 }
14367
14368 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14369 if (ctx->fmtcnt >= 0) {
14370 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14371 if (--ctx->fmtcnt >= 0) {
14372 arg->ch = FORMAT_READ(ctx);
14373 ctx->fmtpos++;
14374 }
14375 }
14376 }
14377 if (ctx->fmtcnt < 0) {
14378 PyErr_SetString(PyExc_ValueError,
14379 "incomplete format");
14380 return -1;
14381 }
14382 return 0;
14383
14384#undef FORMAT_READ
14385}
14386
14387/* Format one argument. Supported conversion specifiers:
14388
14389 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014390 - "i", "d", "u": int or float
14391 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014392 - "e", "E", "f", "F", "g", "G": float
14393 - "c": int or str (1 character)
14394
Victor Stinner8dbd4212012-12-04 09:30:24 +010014395 When possible, the output is written directly into the Unicode writer
14396 (ctx->writer). A string is created when padding is required.
14397
Victor Stinnera47082312012-10-04 02:19:54 +020014398 Return 0 if the argument has been formatted into *p_str,
14399 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014400 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014401static int
14402unicode_format_arg_format(struct unicode_formatter_t *ctx,
14403 struct unicode_format_arg_t *arg,
14404 PyObject **p_str)
14405{
14406 PyObject *v;
14407 _PyUnicodeWriter *writer = &ctx->writer;
14408
14409 if (ctx->fmtcnt == 0)
14410 ctx->writer.overallocate = 0;
14411
14412 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014413 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014414 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014415 return 1;
14416 }
14417
14418 v = unicode_format_getnextarg(ctx);
14419 if (v == NULL)
14420 return -1;
14421
Victor Stinnera47082312012-10-04 02:19:54 +020014422
14423 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014424 case 's':
14425 case 'r':
14426 case 'a':
14427 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14428 /* Fast path */
14429 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14430 return -1;
14431 return 1;
14432 }
14433
14434 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14435 *p_str = v;
14436 Py_INCREF(*p_str);
14437 }
14438 else {
14439 if (arg->ch == 's')
14440 *p_str = PyObject_Str(v);
14441 else if (arg->ch == 'r')
14442 *p_str = PyObject_Repr(v);
14443 else
14444 *p_str = PyObject_ASCII(v);
14445 }
14446 break;
14447
14448 case 'i':
14449 case 'd':
14450 case 'u':
14451 case 'o':
14452 case 'x':
14453 case 'X':
14454 {
14455 int ret = mainformatlong(v, arg, p_str, writer);
14456 if (ret != 0)
14457 return ret;
14458 arg->sign = 1;
14459 break;
14460 }
14461
14462 case 'e':
14463 case 'E':
14464 case 'f':
14465 case 'F':
14466 case 'g':
14467 case 'G':
14468 if (arg->width == -1 && arg->prec == -1
14469 && !(arg->flags & (F_SIGN | F_BLANK)))
14470 {
14471 /* Fast path */
14472 if (formatfloat(v, arg, NULL, writer) == -1)
14473 return -1;
14474 return 1;
14475 }
14476
14477 arg->sign = 1;
14478 if (formatfloat(v, arg, p_str, NULL) == -1)
14479 return -1;
14480 break;
14481
14482 case 'c':
14483 {
14484 Py_UCS4 ch = formatchar(v);
14485 if (ch == (Py_UCS4) -1)
14486 return -1;
14487 if (arg->width == -1 && arg->prec == -1) {
14488 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014489 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014490 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014491 return 1;
14492 }
14493 *p_str = PyUnicode_FromOrdinal(ch);
14494 break;
14495 }
14496
14497 default:
14498 PyErr_Format(PyExc_ValueError,
14499 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014500 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014501 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14502 (int)arg->ch,
14503 ctx->fmtpos - 1);
14504 return -1;
14505 }
14506 if (*p_str == NULL)
14507 return -1;
14508 assert (PyUnicode_Check(*p_str));
14509 return 0;
14510}
14511
14512static int
14513unicode_format_arg_output(struct unicode_formatter_t *ctx,
14514 struct unicode_format_arg_t *arg,
14515 PyObject *str)
14516{
14517 Py_ssize_t len;
14518 enum PyUnicode_Kind kind;
14519 void *pbuf;
14520 Py_ssize_t pindex;
14521 Py_UCS4 signchar;
14522 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014523 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014524 Py_ssize_t sublen;
14525 _PyUnicodeWriter *writer = &ctx->writer;
14526 Py_UCS4 fill;
14527
14528 fill = ' ';
14529 if (arg->sign && arg->flags & F_ZERO)
14530 fill = '0';
14531
14532 if (PyUnicode_READY(str) == -1)
14533 return -1;
14534
14535 len = PyUnicode_GET_LENGTH(str);
14536 if ((arg->width == -1 || arg->width <= len)
14537 && (arg->prec == -1 || arg->prec >= len)
14538 && !(arg->flags & (F_SIGN | F_BLANK)))
14539 {
14540 /* Fast path */
14541 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14542 return -1;
14543 return 0;
14544 }
14545
14546 /* Truncate the string for "s", "r" and "a" formats
14547 if the precision is set */
14548 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14549 if (arg->prec >= 0 && len > arg->prec)
14550 len = arg->prec;
14551 }
14552
14553 /* Adjust sign and width */
14554 kind = PyUnicode_KIND(str);
14555 pbuf = PyUnicode_DATA(str);
14556 pindex = 0;
14557 signchar = '\0';
14558 if (arg->sign) {
14559 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14560 if (ch == '-' || ch == '+') {
14561 signchar = ch;
14562 len--;
14563 pindex++;
14564 }
14565 else if (arg->flags & F_SIGN)
14566 signchar = '+';
14567 else if (arg->flags & F_BLANK)
14568 signchar = ' ';
14569 else
14570 arg->sign = 0;
14571 }
14572 if (arg->width < len)
14573 arg->width = len;
14574
14575 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014576 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014577 if (!(arg->flags & F_LJUST)) {
14578 if (arg->sign) {
14579 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014580 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014581 }
14582 else {
14583 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014584 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014585 }
14586 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014587 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14588 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014589 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014590 }
14591
Victor Stinnera47082312012-10-04 02:19:54 +020014592 buflen = arg->width;
14593 if (arg->sign && len == arg->width)
14594 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014595 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014596 return -1;
14597
14598 /* Write the sign if needed */
14599 if (arg->sign) {
14600 if (fill != ' ') {
14601 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14602 writer->pos += 1;
14603 }
14604 if (arg->width > len)
14605 arg->width--;
14606 }
14607
14608 /* Write the numeric prefix for "x", "X" and "o" formats
14609 if the alternate form is used.
14610 For example, write "0x" for the "%#x" format. */
14611 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14612 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14613 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14614 if (fill != ' ') {
14615 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14616 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14617 writer->pos += 2;
14618 pindex += 2;
14619 }
14620 arg->width -= 2;
14621 if (arg->width < 0)
14622 arg->width = 0;
14623 len -= 2;
14624 }
14625
14626 /* Pad left with the fill character if needed */
14627 if (arg->width > len && !(arg->flags & F_LJUST)) {
14628 sublen = arg->width - len;
14629 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14630 writer->pos += sublen;
14631 arg->width = len;
14632 }
14633
14634 /* If padding with spaces: write sign if needed and/or numeric prefix if
14635 the alternate form is used */
14636 if (fill == ' ') {
14637 if (arg->sign) {
14638 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14639 writer->pos += 1;
14640 }
14641 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14642 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14643 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14644 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14645 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14646 writer->pos += 2;
14647 pindex += 2;
14648 }
14649 }
14650
14651 /* Write characters */
14652 if (len) {
14653 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14654 str, pindex, len);
14655 writer->pos += len;
14656 }
14657
14658 /* Pad right with the fill character if needed */
14659 if (arg->width > len) {
14660 sublen = arg->width - len;
14661 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14662 writer->pos += sublen;
14663 }
14664 return 0;
14665}
14666
14667/* Helper of PyUnicode_Format(): format one arg.
14668 Return 0 on success, raise an exception and return -1 on error. */
14669static int
14670unicode_format_arg(struct unicode_formatter_t *ctx)
14671{
14672 struct unicode_format_arg_t arg;
14673 PyObject *str;
14674 int ret;
14675
Victor Stinner8dbd4212012-12-04 09:30:24 +010014676 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14677 arg.flags = 0;
14678 arg.width = -1;
14679 arg.prec = -1;
14680 arg.sign = 0;
14681 str = NULL;
14682
Victor Stinnera47082312012-10-04 02:19:54 +020014683 ret = unicode_format_arg_parse(ctx, &arg);
14684 if (ret == -1)
14685 return -1;
14686
14687 ret = unicode_format_arg_format(ctx, &arg, &str);
14688 if (ret == -1)
14689 return -1;
14690
14691 if (ret != 1) {
14692 ret = unicode_format_arg_output(ctx, &arg, str);
14693 Py_DECREF(str);
14694 if (ret == -1)
14695 return -1;
14696 }
14697
14698 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14699 PyErr_SetString(PyExc_TypeError,
14700 "not all arguments converted during string formatting");
14701 return -1;
14702 }
14703 return 0;
14704}
14705
Alexander Belopolsky40018472011-02-26 01:02:56 +000014706PyObject *
14707PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014708{
Victor Stinnera47082312012-10-04 02:19:54 +020014709 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014710
Guido van Rossumd57fd912000-03-10 22:53:23 +000014711 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014712 PyErr_BadInternalCall();
14713 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014714 }
Victor Stinnera47082312012-10-04 02:19:54 +020014715
14716 ctx.fmtstr = PyUnicode_FromObject(format);
14717 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014718 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014719 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14720 Py_DECREF(ctx.fmtstr);
14721 return NULL;
14722 }
14723 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14724 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14725 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14726 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014727
Victor Stinner8f674cc2013-04-17 23:02:17 +020014728 _PyUnicodeWriter_Init(&ctx.writer);
14729 ctx.writer.min_length = ctx.fmtcnt + 100;
14730 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014731
Guido van Rossumd57fd912000-03-10 22:53:23 +000014732 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014733 ctx.arglen = PyTuple_Size(args);
14734 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014735 }
14736 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014737 ctx.arglen = -1;
14738 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014739 }
Victor Stinnera47082312012-10-04 02:19:54 +020014740 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014741 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014742 ctx.dict = args;
14743 else
14744 ctx.dict = NULL;
14745 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014746
Victor Stinnera47082312012-10-04 02:19:54 +020014747 while (--ctx.fmtcnt >= 0) {
14748 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014749 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014750
14751 nonfmtpos = ctx.fmtpos++;
14752 while (ctx.fmtcnt >= 0 &&
14753 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14754 ctx.fmtpos++;
14755 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014756 }
Victor Stinnera47082312012-10-04 02:19:54 +020014757 if (ctx.fmtcnt < 0) {
14758 ctx.fmtpos--;
14759 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014760 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014761
Victor Stinnercfc4c132013-04-03 01:48:39 +020014762 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14763 nonfmtpos, ctx.fmtpos) < 0)
14764 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014765 }
14766 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014767 ctx.fmtpos++;
14768 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014769 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014770 }
14771 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014772
Victor Stinnera47082312012-10-04 02:19:54 +020014773 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014774 PyErr_SetString(PyExc_TypeError,
14775 "not all arguments converted during string formatting");
14776 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014777 }
14778
Victor Stinnera47082312012-10-04 02:19:54 +020014779 if (ctx.args_owned) {
14780 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014781 }
Victor Stinnera47082312012-10-04 02:19:54 +020014782 Py_DECREF(ctx.fmtstr);
14783 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014784
Benjamin Peterson29060642009-01-31 22:14:21 +000014785 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014786 Py_DECREF(ctx.fmtstr);
14787 _PyUnicodeWriter_Dealloc(&ctx.writer);
14788 if (ctx.args_owned) {
14789 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014790 }
14791 return NULL;
14792}
14793
Jeremy Hylton938ace62002-07-17 16:30:39 +000014794static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014795unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14796
Tim Peters6d6c1a32001-08-02 04:15:00 +000014797static PyObject *
14798unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14799{
Benjamin Peterson29060642009-01-31 22:14:21 +000014800 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014801 static char *kwlist[] = {"object", "encoding", "errors", 0};
14802 char *encoding = NULL;
14803 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014804
Benjamin Peterson14339b62009-01-31 16:36:08 +000014805 if (type != &PyUnicode_Type)
14806 return unicode_subtype_new(type, args, kwds);
14807 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014808 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014809 return NULL;
14810 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014811 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014812 if (encoding == NULL && errors == NULL)
14813 return PyObject_Str(x);
14814 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014815 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014816}
14817
Guido van Rossume023fe02001-08-30 03:12:59 +000014818static PyObject *
14819unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14820{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014821 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014822 Py_ssize_t length, char_size;
14823 int share_wstr, share_utf8;
14824 unsigned int kind;
14825 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014826
Benjamin Peterson14339b62009-01-31 16:36:08 +000014827 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014828
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014829 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014830 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014831 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014832 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014833 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014834 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014835 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014836 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014837
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014838 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014839 if (self == NULL) {
14840 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014841 return NULL;
14842 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014843 kind = PyUnicode_KIND(unicode);
14844 length = PyUnicode_GET_LENGTH(unicode);
14845
14846 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014847#ifdef Py_DEBUG
14848 _PyUnicode_HASH(self) = -1;
14849#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014850 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014851#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014852 _PyUnicode_STATE(self).interned = 0;
14853 _PyUnicode_STATE(self).kind = kind;
14854 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014855 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014856 _PyUnicode_STATE(self).ready = 1;
14857 _PyUnicode_WSTR(self) = NULL;
14858 _PyUnicode_UTF8_LENGTH(self) = 0;
14859 _PyUnicode_UTF8(self) = NULL;
14860 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014861 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014862
14863 share_utf8 = 0;
14864 share_wstr = 0;
14865 if (kind == PyUnicode_1BYTE_KIND) {
14866 char_size = 1;
14867 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14868 share_utf8 = 1;
14869 }
14870 else if (kind == PyUnicode_2BYTE_KIND) {
14871 char_size = 2;
14872 if (sizeof(wchar_t) == 2)
14873 share_wstr = 1;
14874 }
14875 else {
14876 assert(kind == PyUnicode_4BYTE_KIND);
14877 char_size = 4;
14878 if (sizeof(wchar_t) == 4)
14879 share_wstr = 1;
14880 }
14881
14882 /* Ensure we won't overflow the length. */
14883 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14884 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014885 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014886 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014887 data = PyObject_MALLOC((length + 1) * char_size);
14888 if (data == NULL) {
14889 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014890 goto onError;
14891 }
14892
Victor Stinnerc3c74152011-10-02 20:39:55 +020014893 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014894 if (share_utf8) {
14895 _PyUnicode_UTF8_LENGTH(self) = length;
14896 _PyUnicode_UTF8(self) = data;
14897 }
14898 if (share_wstr) {
14899 _PyUnicode_WSTR_LENGTH(self) = length;
14900 _PyUnicode_WSTR(self) = (wchar_t *)data;
14901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014902
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014903 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014904 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014905 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014906#ifdef Py_DEBUG
14907 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14908#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014909 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014910 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014911
14912onError:
14913 Py_DECREF(unicode);
14914 Py_DECREF(self);
14915 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014916}
14917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014918PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014919"str(object='') -> str\n\
14920str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014921\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014922Create a new string object from the given object. If encoding or\n\
14923errors is specified, then the object must expose a data buffer\n\
14924that will be decoded using the given encoding and error handler.\n\
14925Otherwise, returns the result of object.__str__() (if defined)\n\
14926or repr(object).\n\
14927encoding defaults to sys.getdefaultencoding().\n\
14928errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014929
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014930static PyObject *unicode_iter(PyObject *seq);
14931
Guido van Rossumd57fd912000-03-10 22:53:23 +000014932PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014933 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014934 "str", /* tp_name */
14935 sizeof(PyUnicodeObject), /* tp_size */
14936 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014937 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014938 (destructor)unicode_dealloc, /* tp_dealloc */
14939 0, /* tp_print */
14940 0, /* tp_getattr */
14941 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014942 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014943 unicode_repr, /* tp_repr */
14944 &unicode_as_number, /* tp_as_number */
14945 &unicode_as_sequence, /* tp_as_sequence */
14946 &unicode_as_mapping, /* tp_as_mapping */
14947 (hashfunc) unicode_hash, /* tp_hash*/
14948 0, /* tp_call*/
14949 (reprfunc) unicode_str, /* tp_str */
14950 PyObject_GenericGetAttr, /* tp_getattro */
14951 0, /* tp_setattro */
14952 0, /* tp_as_buffer */
14953 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014954 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014955 unicode_doc, /* tp_doc */
14956 0, /* tp_traverse */
14957 0, /* tp_clear */
14958 PyUnicode_RichCompare, /* tp_richcompare */
14959 0, /* tp_weaklistoffset */
14960 unicode_iter, /* tp_iter */
14961 0, /* tp_iternext */
14962 unicode_methods, /* tp_methods */
14963 0, /* tp_members */
14964 0, /* tp_getset */
14965 &PyBaseObject_Type, /* tp_base */
14966 0, /* tp_dict */
14967 0, /* tp_descr_get */
14968 0, /* tp_descr_set */
14969 0, /* tp_dictoffset */
14970 0, /* tp_init */
14971 0, /* tp_alloc */
14972 unicode_new, /* tp_new */
14973 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014974};
14975
14976/* Initialize the Unicode implementation */
14977
Victor Stinner3a50e702011-10-18 21:21:00 +020014978int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014979{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014980 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014981 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014982 0x000A, /* LINE FEED */
14983 0x000D, /* CARRIAGE RETURN */
14984 0x001C, /* FILE SEPARATOR */
14985 0x001D, /* GROUP SEPARATOR */
14986 0x001E, /* RECORD SEPARATOR */
14987 0x0085, /* NEXT LINE */
14988 0x2028, /* LINE SEPARATOR */
14989 0x2029, /* PARAGRAPH SEPARATOR */
14990 };
14991
Fred Drakee4315f52000-05-09 19:53:39 +000014992 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014993 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014994 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014995 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014996 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014997
Guido van Rossumcacfc072002-05-24 19:01:59 +000014998 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014999 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015000
15001 /* initialize the linebreak bloom filter */
15002 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015003 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015004 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015005
Christian Heimes26532f72013-07-20 14:57:16 +020015006 if (PyType_Ready(&EncodingMapType) < 0)
15007 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015008
Benjamin Petersonc4311282012-10-30 23:21:10 -040015009 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15010 Py_FatalError("Can't initialize field name iterator type");
15011
15012 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15013 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015014
Victor Stinner3a50e702011-10-18 21:21:00 +020015015 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015016}
15017
15018/* Finalize the Unicode implementation */
15019
Christian Heimesa156e092008-02-16 07:38:31 +000015020int
15021PyUnicode_ClearFreeList(void)
15022{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015023 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015024}
15025
Guido van Rossumd57fd912000-03-10 22:53:23 +000015026void
Thomas Wouters78890102000-07-22 19:25:51 +000015027_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015028{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015029 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015030
Serhiy Storchaka05997252013-01-26 12:14:02 +020015031 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015032
Serhiy Storchaka05997252013-01-26 12:14:02 +020015033 for (i = 0; i < 256; i++)
15034 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015035 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015036 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015037}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015038
Walter Dörwald16807132007-05-25 13:52:07 +000015039void
15040PyUnicode_InternInPlace(PyObject **p)
15041{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015042 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015043 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015044#ifdef Py_DEBUG
15045 assert(s != NULL);
15046 assert(_PyUnicode_CHECK(s));
15047#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015048 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015049 return;
15050#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015051 /* If it's a subclass, we don't really know what putting
15052 it in the interned dict might do. */
15053 if (!PyUnicode_CheckExact(s))
15054 return;
15055 if (PyUnicode_CHECK_INTERNED(s))
15056 return;
15057 if (interned == NULL) {
15058 interned = PyDict_New();
15059 if (interned == NULL) {
15060 PyErr_Clear(); /* Don't leave an exception */
15061 return;
15062 }
15063 }
15064 /* It might be that the GetItem call fails even
15065 though the key is present in the dictionary,
15066 namely when this happens during a stack overflow. */
15067 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015068 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015069 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015070
Victor Stinnerf0335102013-04-14 19:13:03 +020015071 if (t) {
15072 Py_INCREF(t);
15073 Py_DECREF(*p);
15074 *p = t;
15075 return;
15076 }
Walter Dörwald16807132007-05-25 13:52:07 +000015077
Benjamin Peterson14339b62009-01-31 16:36:08 +000015078 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015079 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015080 PyErr_Clear();
15081 PyThreadState_GET()->recursion_critical = 0;
15082 return;
15083 }
15084 PyThreadState_GET()->recursion_critical = 0;
15085 /* The two references in interned are not counted by refcnt.
15086 The deallocator will take care of this */
15087 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015088 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015089}
15090
15091void
15092PyUnicode_InternImmortal(PyObject **p)
15093{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 PyUnicode_InternInPlace(p);
15095 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015096 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015097 Py_INCREF(*p);
15098 }
Walter Dörwald16807132007-05-25 13:52:07 +000015099}
15100
15101PyObject *
15102PyUnicode_InternFromString(const char *cp)
15103{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015104 PyObject *s = PyUnicode_FromString(cp);
15105 if (s == NULL)
15106 return NULL;
15107 PyUnicode_InternInPlace(&s);
15108 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015109}
15110
Alexander Belopolsky40018472011-02-26 01:02:56 +000015111void
15112_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015113{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015114 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015115 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015116 Py_ssize_t i, n;
15117 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015118
Benjamin Peterson14339b62009-01-31 16:36:08 +000015119 if (interned == NULL || !PyDict_Check(interned))
15120 return;
15121 keys = PyDict_Keys(interned);
15122 if (keys == NULL || !PyList_Check(keys)) {
15123 PyErr_Clear();
15124 return;
15125 }
Walter Dörwald16807132007-05-25 13:52:07 +000015126
Benjamin Peterson14339b62009-01-31 16:36:08 +000015127 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15128 detector, interned unicode strings are not forcibly deallocated;
15129 rather, we give them their stolen references back, and then clear
15130 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015131
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 n = PyList_GET_SIZE(keys);
15133 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015134 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015135 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015136 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015137 if (PyUnicode_READY(s) == -1) {
15138 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015139 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015140 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015141 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015142 case SSTATE_NOT_INTERNED:
15143 /* XXX Shouldn't happen */
15144 break;
15145 case SSTATE_INTERNED_IMMORTAL:
15146 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015147 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 break;
15149 case SSTATE_INTERNED_MORTAL:
15150 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015151 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015152 break;
15153 default:
15154 Py_FatalError("Inconsistent interned string state.");
15155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015156 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015157 }
15158 fprintf(stderr, "total size of all interned strings: "
15159 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15160 "mortal/immortal\n", mortal_size, immortal_size);
15161 Py_DECREF(keys);
15162 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015163 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015164}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015165
15166
15167/********************* Unicode Iterator **************************/
15168
15169typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 PyObject_HEAD
15171 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015172 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015173} unicodeiterobject;
15174
15175static void
15176unicodeiter_dealloc(unicodeiterobject *it)
15177{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 _PyObject_GC_UNTRACK(it);
15179 Py_XDECREF(it->it_seq);
15180 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015181}
15182
15183static int
15184unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15185{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015186 Py_VISIT(it->it_seq);
15187 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015188}
15189
15190static PyObject *
15191unicodeiter_next(unicodeiterobject *it)
15192{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015193 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015194
Benjamin Peterson14339b62009-01-31 16:36:08 +000015195 assert(it != NULL);
15196 seq = it->it_seq;
15197 if (seq == NULL)
15198 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015199 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015201 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15202 int kind = PyUnicode_KIND(seq);
15203 void *data = PyUnicode_DATA(seq);
15204 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15205 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015206 if (item != NULL)
15207 ++it->it_index;
15208 return item;
15209 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015210
Benjamin Peterson14339b62009-01-31 16:36:08 +000015211 Py_DECREF(seq);
15212 it->it_seq = NULL;
15213 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015214}
15215
15216static PyObject *
15217unicodeiter_len(unicodeiterobject *it)
15218{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015219 Py_ssize_t len = 0;
15220 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015221 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015222 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015223}
15224
15225PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15226
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015227static PyObject *
15228unicodeiter_reduce(unicodeiterobject *it)
15229{
15230 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015231 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015232 it->it_seq, it->it_index);
15233 } else {
15234 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15235 if (u == NULL)
15236 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015237 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015238 }
15239}
15240
15241PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15242
15243static PyObject *
15244unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15245{
15246 Py_ssize_t index = PyLong_AsSsize_t(state);
15247 if (index == -1 && PyErr_Occurred())
15248 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015249 if (it->it_seq != NULL) {
15250 if (index < 0)
15251 index = 0;
15252 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15253 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15254 it->it_index = index;
15255 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015256 Py_RETURN_NONE;
15257}
15258
15259PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15260
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015261static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015262 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015263 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015264 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15265 reduce_doc},
15266 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15267 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015269};
15270
15271PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015272 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15273 "str_iterator", /* tp_name */
15274 sizeof(unicodeiterobject), /* tp_basicsize */
15275 0, /* tp_itemsize */
15276 /* methods */
15277 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15278 0, /* tp_print */
15279 0, /* tp_getattr */
15280 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015281 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015282 0, /* tp_repr */
15283 0, /* tp_as_number */
15284 0, /* tp_as_sequence */
15285 0, /* tp_as_mapping */
15286 0, /* tp_hash */
15287 0, /* tp_call */
15288 0, /* tp_str */
15289 PyObject_GenericGetAttr, /* tp_getattro */
15290 0, /* tp_setattro */
15291 0, /* tp_as_buffer */
15292 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15293 0, /* tp_doc */
15294 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15295 0, /* tp_clear */
15296 0, /* tp_richcompare */
15297 0, /* tp_weaklistoffset */
15298 PyObject_SelfIter, /* tp_iter */
15299 (iternextfunc)unicodeiter_next, /* tp_iternext */
15300 unicodeiter_methods, /* tp_methods */
15301 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015302};
15303
15304static PyObject *
15305unicode_iter(PyObject *seq)
15306{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015307 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015308
Benjamin Peterson14339b62009-01-31 16:36:08 +000015309 if (!PyUnicode_Check(seq)) {
15310 PyErr_BadInternalCall();
15311 return NULL;
15312 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015313 if (PyUnicode_READY(seq) == -1)
15314 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015315 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15316 if (it == NULL)
15317 return NULL;
15318 it->it_index = 0;
15319 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015320 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015321 _PyObject_GC_TRACK(it);
15322 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015323}
15324
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015325
15326size_t
15327Py_UNICODE_strlen(const Py_UNICODE *u)
15328{
15329 int res = 0;
15330 while(*u++)
15331 res++;
15332 return res;
15333}
15334
15335Py_UNICODE*
15336Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15337{
15338 Py_UNICODE *u = s1;
15339 while ((*u++ = *s2++));
15340 return s1;
15341}
15342
15343Py_UNICODE*
15344Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15345{
15346 Py_UNICODE *u = s1;
15347 while ((*u++ = *s2++))
15348 if (n-- == 0)
15349 break;
15350 return s1;
15351}
15352
15353Py_UNICODE*
15354Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15355{
15356 Py_UNICODE *u1 = s1;
15357 u1 += Py_UNICODE_strlen(u1);
15358 Py_UNICODE_strcpy(u1, s2);
15359 return s1;
15360}
15361
15362int
15363Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15364{
15365 while (*s1 && *s2 && *s1 == *s2)
15366 s1++, s2++;
15367 if (*s1 && *s2)
15368 return (*s1 < *s2) ? -1 : +1;
15369 if (*s1)
15370 return 1;
15371 if (*s2)
15372 return -1;
15373 return 0;
15374}
15375
15376int
15377Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15378{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015379 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015380 for (; n != 0; n--) {
15381 u1 = *s1;
15382 u2 = *s2;
15383 if (u1 != u2)
15384 return (u1 < u2) ? -1 : +1;
15385 if (u1 == '\0')
15386 return 0;
15387 s1++;
15388 s2++;
15389 }
15390 return 0;
15391}
15392
15393Py_UNICODE*
15394Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15395{
15396 const Py_UNICODE *p;
15397 for (p = s; *p; p++)
15398 if (*p == c)
15399 return (Py_UNICODE*)p;
15400 return NULL;
15401}
15402
15403Py_UNICODE*
15404Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15405{
15406 const Py_UNICODE *p;
15407 p = s + Py_UNICODE_strlen(s);
15408 while (p != s) {
15409 p--;
15410 if (*p == c)
15411 return (Py_UNICODE*)p;
15412 }
15413 return NULL;
15414}
Victor Stinner331ea922010-08-10 16:37:20 +000015415
Victor Stinner71133ff2010-09-01 23:43:53 +000015416Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015417PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015418{
Victor Stinner577db2c2011-10-11 22:12:48 +020015419 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015420 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015422 if (!PyUnicode_Check(unicode)) {
15423 PyErr_BadArgument();
15424 return NULL;
15425 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015426 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015427 if (u == NULL)
15428 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015429 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015430 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015431 PyErr_NoMemory();
15432 return NULL;
15433 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015434 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015435 size *= sizeof(Py_UNICODE);
15436 copy = PyMem_Malloc(size);
15437 if (copy == NULL) {
15438 PyErr_NoMemory();
15439 return NULL;
15440 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015441 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015442 return copy;
15443}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015444
Georg Brandl66c221e2010-10-14 07:04:07 +000015445/* A _string module, to export formatter_parser and formatter_field_name_split
15446 to the string.Formatter class implemented in Python. */
15447
15448static PyMethodDef _string_methods[] = {
15449 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15450 METH_O, PyDoc_STR("split the argument as a field name")},
15451 {"formatter_parser", (PyCFunction) formatter_parser,
15452 METH_O, PyDoc_STR("parse the argument as a format string")},
15453 {NULL, NULL}
15454};
15455
15456static struct PyModuleDef _string_module = {
15457 PyModuleDef_HEAD_INIT,
15458 "_string",
15459 PyDoc_STR("string helper module"),
15460 0,
15461 _string_methods,
15462 NULL,
15463 NULL,
15464 NULL,
15465 NULL
15466};
15467
15468PyMODINIT_FUNC
15469PyInit__string(void)
15470{
15471 return PyModule_Create(&_string_module);
15472}
15473
15474
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015475#ifdef __cplusplus
15476}
15477#endif