blob: eae4bc5bff6fb304c315fd9f2eda17bfb85a4cc9 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Larry Hastings61272b72014-01-07 12:41:53 -080050/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080051class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080052[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080053/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080054
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055/* --- Globals ------------------------------------------------------------
56
Serhiy Storchaka05997252013-01-26 12:14:02 +020057NOTE: In the interpreter's initialization phase, some globals are currently
58 initialized dynamically as needed. In the process Unicode objects may
59 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000060
61*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64#ifdef __cplusplus
65extern "C" {
66#endif
67
Victor Stinner8faf8212011-12-08 22:14:11 +010068/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
69#define MAX_UNICODE 0x10ffff
70
Victor Stinner910337b2011-10-03 03:20:16 +020071#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020072# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020073#else
74# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
75#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020076
Victor Stinnere90fe6a2011-10-01 16:48:13 +020077#define _PyUnicode_UTF8(op) \
78 (((PyCompactUnicodeObject*)(op))->utf8)
79#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020080 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 assert(PyUnicode_IS_READY(op)), \
82 PyUnicode_IS_COMPACT_ASCII(op) ? \
83 ((char*)((PyASCIIObject*)(op) + 1)) : \
84 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020085#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020086 (((PyCompactUnicodeObject*)(op))->utf8_length)
87#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020088 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 assert(PyUnicode_IS_READY(op)), \
90 PyUnicode_IS_COMPACT_ASCII(op) ? \
91 ((PyASCIIObject*)(op))->length : \
92 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020093#define _PyUnicode_WSTR(op) \
94 (((PyASCIIObject*)(op))->wstr)
95#define _PyUnicode_WSTR_LENGTH(op) \
96 (((PyCompactUnicodeObject*)(op))->wstr_length)
97#define _PyUnicode_LENGTH(op) \
98 (((PyASCIIObject *)(op))->length)
99#define _PyUnicode_STATE(op) \
100 (((PyASCIIObject *)(op))->state)
101#define _PyUnicode_HASH(op) \
102 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200103#define _PyUnicode_KIND(op) \
104 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200105 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_GET_LENGTH(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_DATA_ANY(op) \
110 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200130 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200131 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200132 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
133
Victor Stinner03490912011-10-03 23:45:12 +0200134/* true if the Unicode object has an allocated wstr memory block
135 (not shared with other data) */
136#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200137 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100148 to_type *_to = (to_type *)(to); \
149 const from_type *_iter = (from_type *)(begin); \
150 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200153 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Walter Dörwald16807132007-05-25 13:52:07 +0000165/* This dictionary holds all interned unicode strings. Note that references
166 to strings in this dictionary are *not* counted in the string's ob_refcnt.
167 When the interned string reaches a refcnt of 0 the string deallocation
168 function will delete the reference from this dictionary.
169
170 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000171 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000172*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200173static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000174
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000175/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200176static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200177
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179 do { \
180 if (unicode_empty != NULL) \
181 Py_INCREF(unicode_empty); \
182 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183 unicode_empty = PyUnicode_New(0, 0); \
184 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200185 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
187 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191#define _Py_RETURN_UNICODE_EMPTY() \
192 do { \
193 _Py_INCREF_UNICODE_EMPTY(); \
194 return unicode_empty; \
195 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200197/* Forward declaration */
198Py_LOCAL_INLINE(int)
199_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
200
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200206static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100242static int unicode_modifiable(PyObject *unicode);
243
Victor Stinnerfe226c02011-10-03 03:52:20 +0200244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100246_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200247static PyObject *
248_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
249static PyObject *
250_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
251
252static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100255 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
257
Alexander Belopolsky40018472011-02-26 01:02:56 +0000258static void
259raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300260 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100261 PyObject *unicode,
262 Py_ssize_t startpos, Py_ssize_t endpos,
263 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Same for linebreaks */
266static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000268/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* 0x000B, * LINE TABULATION */
270/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x001C, * FILE SEPARATOR */
275/* 0x001D, * GROUP SEPARATOR */
276/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 1, 1, 1, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000282
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000291};
292
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300293/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
294 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000296PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000298#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 /* This is actually an illegal character, so it should
302 not be passed to unichr. */
303 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000304#endif
305}
306
Victor Stinner910337b2011-10-03 03:20:16 +0200307#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200308int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100309_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200310{
311 PyASCIIObject *ascii;
312 unsigned int kind;
313
314 assert(PyUnicode_Check(op));
315
316 ascii = (PyASCIIObject *)op;
317 kind = ascii->state.kind;
318
Victor Stinnera3b334d2011-10-03 13:53:37 +0200319 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200325 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200326
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 if (ascii->state.compact == 1) {
328 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(kind == PyUnicode_1BYTE_KIND
330 || kind == PyUnicode_2BYTE_KIND
331 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200333 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100335 }
336 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
338
339 data = unicode->data.any;
340 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->length == 0);
342 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100346 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200347 assert(ascii->wstr != NULL);
348 assert(data == NULL);
349 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200391 void *data;
392 Py_UCS4 ch;
393
394 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 for (i=0; i < ascii->length; i++)
396 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 if (ch > maxchar)
399 maxchar = ch;
400 }
401 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100402 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 255);
405 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 else
407 assert(maxchar < 128);
408 }
Victor Stinner77faf692011-11-20 18:56:05 +0100409 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 assert(maxchar <= 0xFFFF);
412 }
413 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200414 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100415 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100416 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200417 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200418 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100423static PyObject*
424unicode_result_wchar(PyObject *unicode)
425{
426#ifndef Py_DEBUG
427 Py_ssize_t len;
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 len = _PyUnicode_WSTR_LENGTH(unicode);
430 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200432 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 }
434
435 if (len == 1) {
436 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100437 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
439 Py_DECREF(unicode);
440 return latin1_char;
441 }
442 }
443
444 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200445 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 return NULL;
447 }
448#else
Victor Stinneraa771272012-10-04 02:32:58 +0200449 assert(Py_REFCNT(unicode) == 1);
450
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100451 /* don't make the result ready in debug mode to ensure that the caller
452 makes the string ready before using it */
453 assert(_PyUnicode_CheckConsistency(unicode, 1));
454#endif
455 return unicode;
456}
457
458static PyObject*
459unicode_result_ready(PyObject *unicode)
460{
461 Py_ssize_t length;
462
463 length = PyUnicode_GET_LENGTH(unicode);
464 if (length == 0) {
465 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200467 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 }
469 return unicode_empty;
470 }
471
472 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200473 void *data = PyUnicode_DATA(unicode);
474 int kind = PyUnicode_KIND(unicode);
475 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 if (ch < 256) {
477 PyObject *latin1_char = unicode_latin1[ch];
478 if (latin1_char != NULL) {
479 if (unicode != latin1_char) {
480 Py_INCREF(latin1_char);
481 Py_DECREF(unicode);
482 }
483 return latin1_char;
484 }
485 else {
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 Py_INCREF(unicode);
488 unicode_latin1[ch] = unicode;
489 return unicode;
490 }
491 }
492 }
493
494 assert(_PyUnicode_CheckConsistency(unicode, 1));
495 return unicode;
496}
497
498static PyObject*
499unicode_result(PyObject *unicode)
500{
501 assert(_PyUnicode_CHECK(unicode));
502 if (PyUnicode_IS_READY(unicode))
503 return unicode_result_ready(unicode);
504 else
505 return unicode_result_wchar(unicode);
506}
507
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508static PyObject*
509unicode_result_unchanged(PyObject *unicode)
510{
511 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500512 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100513 return NULL;
514 Py_INCREF(unicode);
515 return unicode;
516 }
517 else
518 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100519 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100520}
521
Victor Stinner3a50e702011-10-18 21:21:00 +0200522#ifdef HAVE_MBCS
523static OSVERSIONINFOEX winver;
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526/* --- Bloom Filters ----------------------------------------------------- */
527
528/* stuff to implement simple "bloom filters" for Unicode characters.
529 to keep things simple, we use a single bitmask, using the least 5
530 bits from each unicode characters as the bit index. */
531
532/* the linebreak mask is set up by Unicode_Init below */
533
Antoine Pitrouf068f942010-01-13 14:19:12 +0000534#if LONG_BIT >= 128
535#define BLOOM_WIDTH 128
536#elif LONG_BIT >= 64
537#define BLOOM_WIDTH 64
538#elif LONG_BIT >= 32
539#define BLOOM_WIDTH 32
540#else
541#error "LONG_BIT is smaller than 32"
542#endif
543
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544#define BLOOM_MASK unsigned long
545
Serhiy Storchaka05997252013-01-26 12:14:02 +0200546static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Antoine Pitrouf068f942010-01-13 14:19:12 +0000548#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Benjamin Peterson29060642009-01-31 22:14:21 +0000550#define BLOOM_LINEBREAK(ch) \
551 ((ch) < 128U ? ascii_linebreak[(ch)] : \
552 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
Alexander Belopolsky40018472011-02-26 01:02:56 +0000554Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556{
Victor Stinnera85af502013-04-09 21:53:54 +0200557#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
558 do { \
559 TYPE *data = (TYPE *)PTR; \
560 TYPE *end = data + LEN; \
561 Py_UCS4 ch; \
562 for (; data != end; data++) { \
563 ch = *data; \
564 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
565 } \
566 break; \
567 } while (0)
568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 /* calculate simple bloom-style bitmask for a given unicode string */
570
Antoine Pitrouf068f942010-01-13 14:19:12 +0000571 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200574 switch (kind) {
575 case PyUnicode_1BYTE_KIND:
576 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
577 break;
578 case PyUnicode_2BYTE_KIND:
579 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
580 break;
581 case PyUnicode_4BYTE_KIND:
582 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
583 break;
584 default:
585 assert(0);
586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200588
589#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590}
591
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200592/* Compilation of templated routines */
593
594#include "stringlib/asciilib.h"
595#include "stringlib/fastsearch.h"
596#include "stringlib/partition.h"
597#include "stringlib/split.h"
598#include "stringlib/count.h"
599#include "stringlib/find.h"
600#include "stringlib/find_max_char.h"
601#include "stringlib/localeutil.h"
602#include "stringlib/undef.h"
603
604#include "stringlib/ucs1lib.h"
605#include "stringlib/fastsearch.h"
606#include "stringlib/partition.h"
607#include "stringlib/split.h"
608#include "stringlib/count.h"
609#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300610#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200611#include "stringlib/find_max_char.h"
612#include "stringlib/localeutil.h"
613#include "stringlib/undef.h"
614
615#include "stringlib/ucs2lib.h"
616#include "stringlib/fastsearch.h"
617#include "stringlib/partition.h"
618#include "stringlib/split.h"
619#include "stringlib/count.h"
620#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300621#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200622#include "stringlib/find_max_char.h"
623#include "stringlib/localeutil.h"
624#include "stringlib/undef.h"
625
626#include "stringlib/ucs4lib.h"
627#include "stringlib/fastsearch.h"
628#include "stringlib/partition.h"
629#include "stringlib/split.h"
630#include "stringlib/count.h"
631#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300632#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200633#include "stringlib/find_max_char.h"
634#include "stringlib/localeutil.h"
635#include "stringlib/undef.h"
636
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637#include "stringlib/unicodedefs.h"
638#include "stringlib/fastsearch.h"
639#include "stringlib/count.h"
640#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100641#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* --- Unicode Object ----------------------------------------------------- */
644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200646fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
649 Py_ssize_t size, Py_UCS4 ch,
650 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200652 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
653
654 switch (kind) {
655 case PyUnicode_1BYTE_KIND:
656 {
657 Py_UCS1 ch1 = (Py_UCS1) ch;
658 if (ch1 == ch)
659 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
660 else
661 return -1;
662 }
663 case PyUnicode_2BYTE_KIND:
664 {
665 Py_UCS2 ch2 = (Py_UCS2) ch;
666 if (ch2 == ch)
667 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
668 else
669 return -1;
670 }
671 case PyUnicode_4BYTE_KIND:
672 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
673 default:
674 assert(0);
675 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677}
678
Victor Stinnerafffce42012-10-03 23:03:17 +0200679#ifdef Py_DEBUG
680/* Fill the data of an Unicode string with invalid characters to detect bugs
681 earlier.
682
683 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
684 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
685 invalid character in Unicode 6.0. */
686static void
687unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
688{
689 int kind = PyUnicode_KIND(unicode);
690 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
691 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
692 if (length <= old_length)
693 return;
694 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
695}
696#endif
697
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698static PyObject*
699resize_compact(PyObject *unicode, Py_ssize_t length)
700{
701 Py_ssize_t char_size;
702 Py_ssize_t struct_size;
703 Py_ssize_t new_size;
704 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100705 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200706#ifdef Py_DEBUG
707 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
708#endif
709
Victor Stinner79891572012-05-03 13:43:07 +0200710 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100712 assert(PyUnicode_IS_COMPACT(unicode));
713
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200714 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100715 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 struct_size = sizeof(PyASCIIObject);
717 else
718 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200719 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
722 PyErr_NoMemory();
723 return NULL;
724 }
725 new_size = (struct_size + (length + 1) * char_size);
726
Victor Stinner84def372011-12-11 20:04:56 +0100727 _Py_DEC_REFTOTAL;
728 _Py_ForgetReference(unicode);
729
730 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
731 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100732 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733 PyErr_NoMemory();
734 return NULL;
735 }
Victor Stinner84def372011-12-11 20:04:56 +0100736 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100738
Victor Stinnerfe226c02011-10-03 03:52:20 +0200739 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200740 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100742 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200743 _PyUnicode_WSTR_LENGTH(unicode) = length;
744 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100745 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
746 PyObject_DEL(_PyUnicode_WSTR(unicode));
747 _PyUnicode_WSTR(unicode) = NULL;
748 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200749#ifdef Py_DEBUG
750 unicode_fill_invalid(unicode, old_length);
751#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200752 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
753 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200754 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200755 return unicode;
756}
757
Alexander Belopolsky40018472011-02-26 01:02:56 +0000758static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200759resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000760{
Victor Stinner95663112011-10-04 01:03:50 +0200761 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100762 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000765
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 if (PyUnicode_IS_READY(unicode)) {
767 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200768 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200770#ifdef Py_DEBUG
771 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
772#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773
774 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200775 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200776 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
777 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200778
779 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
780 PyErr_NoMemory();
781 return -1;
782 }
783 new_size = (length + 1) * char_size;
784
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
786 {
787 PyObject_DEL(_PyUnicode_UTF8(unicode));
788 _PyUnicode_UTF8(unicode) = NULL;
789 _PyUnicode_UTF8_LENGTH(unicode) = 0;
790 }
791
Victor Stinnerfe226c02011-10-03 03:52:20 +0200792 data = (PyObject *)PyObject_REALLOC(data, new_size);
793 if (data == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200798 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200799 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 _PyUnicode_WSTR_LENGTH(unicode) = length;
801 }
802 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200803 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200804 _PyUnicode_UTF8_LENGTH(unicode) = length;
805 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806 _PyUnicode_LENGTH(unicode) = length;
807 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200808#ifdef Py_DEBUG
809 unicode_fill_invalid(unicode, old_length);
810#endif
Victor Stinner95663112011-10-04 01:03:50 +0200811 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200812 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200814 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200815 }
Victor Stinner95663112011-10-04 01:03:50 +0200816 assert(_PyUnicode_WSTR(unicode) != NULL);
817
818 /* check for integer overflow */
819 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
820 PyErr_NoMemory();
821 return -1;
822 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100823 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200824 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100825 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200826 if (!wstr) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 _PyUnicode_WSTR(unicode) = wstr;
831 _PyUnicode_WSTR(unicode)[length] = 0;
832 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200833 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000834 return 0;
835}
836
Victor Stinnerfe226c02011-10-03 03:52:20 +0200837static PyObject*
838resize_copy(PyObject *unicode, Py_ssize_t length)
839{
840 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100841 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100843
Benjamin Petersonbac79492012-01-14 13:34:47 -0500844 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100845 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200846
847 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
848 if (copy == NULL)
849 return NULL;
850
851 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200852 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200853 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200854 }
855 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200856 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100857
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200858 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200859 if (w == NULL)
860 return NULL;
861 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
862 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200863 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
864 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200865 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200866 }
867}
868
Guido van Rossumd57fd912000-03-10 22:53:23 +0000869/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000870 Ux0000 terminated; some code (e.g. new_identifier)
871 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000872
873 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000874 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875
876*/
877
Alexander Belopolsky40018472011-02-26 01:02:56 +0000878static PyUnicodeObject *
879_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200881 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200882 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885 if (length == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888 }
889
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000890 /* Ensure we won't overflow the size. */
891 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
892 return (PyUnicodeObject *)PyErr_NoMemory();
893 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894 if (length < 0) {
895 PyErr_SetString(PyExc_SystemError,
896 "Negative size passed to _PyUnicode_New");
897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000898 }
899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
901 if (unicode == NULL)
902 return NULL;
903 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100904
905 _PyUnicode_WSTR_LENGTH(unicode) = length;
906 _PyUnicode_HASH(unicode) = -1;
907 _PyUnicode_STATE(unicode).interned = 0;
908 _PyUnicode_STATE(unicode).kind = 0;
909 _PyUnicode_STATE(unicode).compact = 0;
910 _PyUnicode_STATE(unicode).ready = 0;
911 _PyUnicode_STATE(unicode).ascii = 0;
912 _PyUnicode_DATA_ANY(unicode) = NULL;
913 _PyUnicode_LENGTH(unicode) = 0;
914 _PyUnicode_UTF8(unicode) = NULL;
915 _PyUnicode_UTF8_LENGTH(unicode) = 0;
916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
918 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100919 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000920 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100921 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000922 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
Jeremy Hyltond8082792003-09-16 19:41:39 +0000924 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000925 * the caller fails before initializing str -- unicode_resize()
926 * reads str[0], and the Keep-Alive optimization can keep memory
927 * allocated for str alive across a call to unicode_dealloc(unicode).
928 * We don't want unicode_resize to read uninitialized memory in
929 * that case.
930 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 _PyUnicode_WSTR(unicode)[0] = 0;
932 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100933
Victor Stinner7931d9a2011-11-04 00:22:48 +0100934 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000935 return unicode;
936}
937
Victor Stinnerf42dc442011-10-02 23:33:16 +0200938static const char*
939unicode_kind_name(PyObject *unicode)
940{
Victor Stinner42dfd712011-10-03 14:41:45 +0200941 /* don't check consistency: unicode_kind_name() is called from
942 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 if (!PyUnicode_IS_COMPACT(unicode))
944 {
945 if (!PyUnicode_IS_READY(unicode))
946 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600947 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 {
949 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200951 return "legacy ascii";
952 else
953 return "legacy latin1";
954 case PyUnicode_2BYTE_KIND:
955 return "legacy UCS2";
956 case PyUnicode_4BYTE_KIND:
957 return "legacy UCS4";
958 default:
959 return "<legacy invalid kind>";
960 }
961 }
962 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600963 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200965 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200966 return "ascii";
967 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200972 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200973 default:
974 return "<invalid compact kind>";
975 }
976}
977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979/* Functions wrapping macros for use in debugger */
980char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200981 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982}
983
984void *_PyUnicode_compact_data(void *unicode) {
985 return _PyUnicode_COMPACT_DATA(unicode);
986}
987void *_PyUnicode_data(void *unicode){
988 printf("obj %p\n", unicode);
989 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
990 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
991 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
992 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
993 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
994 return PyUnicode_DATA(unicode);
995}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200996
997void
998_PyUnicode_Dump(PyObject *op)
999{
1000 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1002 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1003 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001004
Victor Stinnera849a4b2011-10-03 12:12:11 +02001005 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 {
1007 if (ascii->state.ascii)
1008 data = (ascii + 1);
1009 else
1010 data = (compact + 1);
1011 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001012 else
1013 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +02001014 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
1015
Victor Stinnera849a4b2011-10-03 12:12:11 +02001016 if (ascii->wstr == data)
1017 printf("shared ");
1018 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001019
Victor Stinnera3b334d2011-10-03 13:53:37 +02001020 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +02001021 printf(" (%zu), ", compact->wstr_length);
1022 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1023 printf("shared ");
1024 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001025 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001026 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001027}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001028#endif
1029
1030PyObject *
1031PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1032{
1033 PyObject *obj;
1034 PyCompactUnicodeObject *unicode;
1035 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001036 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001037 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001038 Py_ssize_t char_size;
1039 Py_ssize_t struct_size;
1040
1041 /* Optimization for empty strings */
1042 if (size == 0 && unicode_empty != NULL) {
1043 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001044 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001045 }
1046
Victor Stinner9e9d6892011-10-04 01:02:02 +02001047 is_ascii = 0;
1048 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001049 struct_size = sizeof(PyCompactUnicodeObject);
1050 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001051 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 char_size = 1;
1053 is_ascii = 1;
1054 struct_size = sizeof(PyASCIIObject);
1055 }
1056 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001057 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 char_size = 1;
1059 }
1060 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001061 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062 char_size = 2;
1063 if (sizeof(wchar_t) == 2)
1064 is_sharing = 1;
1065 }
1066 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001067 if (maxchar > MAX_UNICODE) {
1068 PyErr_SetString(PyExc_SystemError,
1069 "invalid maximum character passed to PyUnicode_New");
1070 return NULL;
1071 }
Victor Stinner8f825062012-04-27 13:55:39 +02001072 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073 char_size = 4;
1074 if (sizeof(wchar_t) == 4)
1075 is_sharing = 1;
1076 }
1077
1078 /* Ensure we won't overflow the size. */
1079 if (size < 0) {
1080 PyErr_SetString(PyExc_SystemError,
1081 "Negative size passed to PyUnicode_New");
1082 return NULL;
1083 }
1084 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1085 return PyErr_NoMemory();
1086
1087 /* Duplicated allocation code from _PyObject_New() instead of a call to
1088 * PyObject_New() so we are able to allocate space for the object and
1089 * it's data buffer.
1090 */
1091 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1092 if (obj == NULL)
1093 return PyErr_NoMemory();
1094 obj = PyObject_INIT(obj, &PyUnicode_Type);
1095 if (obj == NULL)
1096 return NULL;
1097
1098 unicode = (PyCompactUnicodeObject *)obj;
1099 if (is_ascii)
1100 data = ((PyASCIIObject*)obj) + 1;
1101 else
1102 data = unicode + 1;
1103 _PyUnicode_LENGTH(unicode) = size;
1104 _PyUnicode_HASH(unicode) = -1;
1105 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001106 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107 _PyUnicode_STATE(unicode).compact = 1;
1108 _PyUnicode_STATE(unicode).ready = 1;
1109 _PyUnicode_STATE(unicode).ascii = is_ascii;
1110 if (is_ascii) {
1111 ((char*)data)[size] = 0;
1112 _PyUnicode_WSTR(unicode) = NULL;
1113 }
Victor Stinner8f825062012-04-27 13:55:39 +02001114 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001115 ((char*)data)[size] = 0;
1116 _PyUnicode_WSTR(unicode) = NULL;
1117 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001119 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001121 else {
1122 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001123 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001124 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001126 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001127 ((Py_UCS4*)data)[size] = 0;
1128 if (is_sharing) {
1129 _PyUnicode_WSTR_LENGTH(unicode) = size;
1130 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1131 }
1132 else {
1133 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1134 _PyUnicode_WSTR(unicode) = NULL;
1135 }
1136 }
Victor Stinner8f825062012-04-27 13:55:39 +02001137#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001138 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001139#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001140 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001141 return obj;
1142}
1143
1144#if SIZEOF_WCHAR_T == 2
1145/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1146 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001147 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148
1149 This function assumes that unicode can hold one more code point than wstr
1150 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001151static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001153 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001154{
1155 const wchar_t *iter;
1156 Py_UCS4 *ucs4_out;
1157
Victor Stinner910337b2011-10-03 03:20:16 +02001158 assert(unicode != NULL);
1159 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001160 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1161 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1162
1163 for (iter = begin; iter < end; ) {
1164 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1165 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001166 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1167 && (iter+1) < end
1168 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169 {
Victor Stinner551ac952011-11-29 22:58:13 +01001170 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001171 iter += 2;
1172 }
1173 else {
1174 *ucs4_out++ = *iter;
1175 iter++;
1176 }
1177 }
1178 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1179 _PyUnicode_GET_LENGTH(unicode)));
1180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001181}
1182#endif
1183
Victor Stinnercd9950f2011-10-02 00:34:53 +02001184static int
Victor Stinner488fa492011-12-12 00:01:39 +01001185unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001186{
Victor Stinner488fa492011-12-12 00:01:39 +01001187 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001188 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001189 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001190 return -1;
1191 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001192 return 0;
1193}
1194
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001195static int
1196_copy_characters(PyObject *to, Py_ssize_t to_start,
1197 PyObject *from, Py_ssize_t from_start,
1198 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001199{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001200 unsigned int from_kind, to_kind;
1201 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001202
Victor Stinneree4544c2012-05-09 22:24:08 +02001203 assert(0 <= how_many);
1204 assert(0 <= from_start);
1205 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001206 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001207 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001208 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209
Victor Stinnerd3f08822012-05-29 12:57:52 +02001210 assert(PyUnicode_Check(to));
1211 assert(PyUnicode_IS_READY(to));
1212 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1213
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001214 if (how_many == 0)
1215 return 0;
1216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221
Victor Stinnerf1852262012-06-16 16:38:26 +02001222#ifdef Py_DEBUG
1223 if (!check_maxchar
1224 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1225 {
1226 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1227 Py_UCS4 ch;
1228 Py_ssize_t i;
1229 for (i=0; i < how_many; i++) {
1230 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1231 assert(ch <= to_maxchar);
1232 }
1233 }
1234#endif
1235
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001236 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001237 if (check_maxchar
1238 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1239 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001240 /* Writing Latin-1 characters into an ASCII string requires to
1241 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001242 Py_UCS4 max_char;
1243 max_char = ucs1lib_find_max_char(from_data,
1244 (Py_UCS1*)from_data + how_many);
1245 if (max_char >= 128)
1246 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001247 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001248 Py_MEMCPY((char*)to_data + to_kind * to_start,
1249 (char*)from_data + from_kind * from_start,
1250 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001252 else if (from_kind == PyUnicode_1BYTE_KIND
1253 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001254 {
1255 _PyUnicode_CONVERT_BYTES(
1256 Py_UCS1, Py_UCS2,
1257 PyUnicode_1BYTE_DATA(from) + from_start,
1258 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1259 PyUnicode_2BYTE_DATA(to) + to_start
1260 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001261 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001262 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001263 && to_kind == PyUnicode_4BYTE_KIND)
1264 {
1265 _PyUnicode_CONVERT_BYTES(
1266 Py_UCS1, Py_UCS4,
1267 PyUnicode_1BYTE_DATA(from) + from_start,
1268 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1269 PyUnicode_4BYTE_DATA(to) + to_start
1270 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001271 }
1272 else if (from_kind == PyUnicode_2BYTE_KIND
1273 && to_kind == PyUnicode_4BYTE_KIND)
1274 {
1275 _PyUnicode_CONVERT_BYTES(
1276 Py_UCS2, Py_UCS4,
1277 PyUnicode_2BYTE_DATA(from) + from_start,
1278 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1279 PyUnicode_4BYTE_DATA(to) + to_start
1280 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001281 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001282 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001283 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1284
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001285 if (!check_maxchar) {
1286 if (from_kind == PyUnicode_2BYTE_KIND
1287 && to_kind == PyUnicode_1BYTE_KIND)
1288 {
1289 _PyUnicode_CONVERT_BYTES(
1290 Py_UCS2, Py_UCS1,
1291 PyUnicode_2BYTE_DATA(from) + from_start,
1292 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1293 PyUnicode_1BYTE_DATA(to) + to_start
1294 );
1295 }
1296 else if (from_kind == PyUnicode_4BYTE_KIND
1297 && to_kind == PyUnicode_1BYTE_KIND)
1298 {
1299 _PyUnicode_CONVERT_BYTES(
1300 Py_UCS4, Py_UCS1,
1301 PyUnicode_4BYTE_DATA(from) + from_start,
1302 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1303 PyUnicode_1BYTE_DATA(to) + to_start
1304 );
1305 }
1306 else if (from_kind == PyUnicode_4BYTE_KIND
1307 && to_kind == PyUnicode_2BYTE_KIND)
1308 {
1309 _PyUnicode_CONVERT_BYTES(
1310 Py_UCS4, Py_UCS2,
1311 PyUnicode_4BYTE_DATA(from) + from_start,
1312 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1313 PyUnicode_2BYTE_DATA(to) + to_start
1314 );
1315 }
1316 else {
1317 assert(0);
1318 return -1;
1319 }
1320 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001321 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001322 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001323 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 Py_ssize_t i;
1325
Victor Stinnera0702ab2011-09-29 14:14:38 +02001326 for (i=0; i < how_many; i++) {
1327 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001328 if (ch > to_maxchar)
1329 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001330 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1331 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001332 }
1333 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001334 return 0;
1335}
1336
Victor Stinnerd3f08822012-05-29 12:57:52 +02001337void
1338_PyUnicode_FastCopyCharacters(
1339 PyObject *to, Py_ssize_t to_start,
1340 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001341{
1342 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1343}
1344
1345Py_ssize_t
1346PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1347 PyObject *from, Py_ssize_t from_start,
1348 Py_ssize_t how_many)
1349{
1350 int err;
1351
1352 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1353 PyErr_BadInternalCall();
1354 return -1;
1355 }
1356
Benjamin Petersonbac79492012-01-14 13:34:47 -05001357 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001358 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001359 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001360 return -1;
1361
Victor Stinnerd3f08822012-05-29 12:57:52 +02001362 if (from_start < 0) {
1363 PyErr_SetString(PyExc_IndexError, "string index out of range");
1364 return -1;
1365 }
1366 if (to_start < 0) {
1367 PyErr_SetString(PyExc_IndexError, "string index out of range");
1368 return -1;
1369 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001370 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1371 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1372 PyErr_Format(PyExc_SystemError,
1373 "Cannot write %zi characters at %zi "
1374 "in a string of %zi characters",
1375 how_many, to_start, PyUnicode_GET_LENGTH(to));
1376 return -1;
1377 }
1378
1379 if (how_many == 0)
1380 return 0;
1381
Victor Stinner488fa492011-12-12 00:01:39 +01001382 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001383 return -1;
1384
1385 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1386 if (err) {
1387 PyErr_Format(PyExc_SystemError,
1388 "Cannot copy %s characters "
1389 "into a string of %s characters",
1390 unicode_kind_name(from),
1391 unicode_kind_name(to));
1392 return -1;
1393 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001394 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395}
1396
Victor Stinner17222162011-09-28 22:15:37 +02001397/* Find the maximum code point and count the number of surrogate pairs so a
1398 correct string length can be computed before converting a string to UCS4.
1399 This function counts single surrogates as a character and not as a pair.
1400
1401 Return 0 on success, or -1 on error. */
1402static int
1403find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1404 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405{
1406 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001407 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408
Victor Stinnerc53be962011-10-02 21:33:54 +02001409 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410 *num_surrogates = 0;
1411 *maxchar = 0;
1412
1413 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001415 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1416 && (iter+1) < end
1417 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1418 {
1419 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1420 ++(*num_surrogates);
1421 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001422 }
1423 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001425 {
1426 ch = *iter;
1427 iter++;
1428 }
1429 if (ch > *maxchar) {
1430 *maxchar = ch;
1431 if (*maxchar > MAX_UNICODE) {
1432 PyErr_Format(PyExc_ValueError,
1433 "character U+%x is not in range [U+0000; U+10ffff]",
1434 ch);
1435 return -1;
1436 }
1437 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 }
1439 return 0;
1440}
1441
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001442int
1443_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001444{
1445 wchar_t *end;
1446 Py_UCS4 maxchar = 0;
1447 Py_ssize_t num_surrogates;
1448#if SIZEOF_WCHAR_T == 2
1449 Py_ssize_t length_wo_surrogates;
1450#endif
1451
Georg Brandl7597add2011-10-05 16:36:47 +02001452 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001453 strings were created using _PyObject_New() and where no canonical
1454 representation (the str field) has been set yet aka strings
1455 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001456 assert(_PyUnicode_CHECK(unicode));
1457 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001459 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001460 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001461 /* Actually, it should neither be interned nor be anything else: */
1462 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001465 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001466 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468
1469 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001470 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1471 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 PyErr_NoMemory();
1473 return -1;
1474 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001475 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001476 _PyUnicode_WSTR(unicode), end,
1477 PyUnicode_1BYTE_DATA(unicode));
1478 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1479 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1480 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1481 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001482 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001483 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001484 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001485 }
1486 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001487 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001488 _PyUnicode_UTF8(unicode) = NULL;
1489 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 }
1491 PyObject_FREE(_PyUnicode_WSTR(unicode));
1492 _PyUnicode_WSTR(unicode) = NULL;
1493 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1494 }
1495 /* In this case we might have to convert down from 4-byte native
1496 wchar_t to 2-byte unicode. */
1497 else if (maxchar < 65536) {
1498 assert(num_surrogates == 0 &&
1499 "FindMaxCharAndNumSurrogatePairs() messed up");
1500
Victor Stinner506f5922011-09-28 22:34:18 +02001501#if SIZEOF_WCHAR_T == 2
1502 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001503 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001504 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1505 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1506 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001507 _PyUnicode_UTF8(unicode) = NULL;
1508 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001509#else
1510 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001511 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001512 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001513 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001514 PyErr_NoMemory();
1515 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001516 }
Victor Stinner506f5922011-09-28 22:34:18 +02001517 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1518 _PyUnicode_WSTR(unicode), end,
1519 PyUnicode_2BYTE_DATA(unicode));
1520 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1521 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1522 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001523 _PyUnicode_UTF8(unicode) = NULL;
1524 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001525 PyObject_FREE(_PyUnicode_WSTR(unicode));
1526 _PyUnicode_WSTR(unicode) = NULL;
1527 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1528#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001529 }
1530 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1531 else {
1532#if SIZEOF_WCHAR_T == 2
1533 /* in case the native representation is 2-bytes, we need to allocate a
1534 new normalized 4-byte version. */
1535 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001536 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1537 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001538 PyErr_NoMemory();
1539 return -1;
1540 }
1541 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1542 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001543 _PyUnicode_UTF8(unicode) = NULL;
1544 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001545 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1546 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001547 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001548 PyObject_FREE(_PyUnicode_WSTR(unicode));
1549 _PyUnicode_WSTR(unicode) = NULL;
1550 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1551#else
1552 assert(num_surrogates == 0);
1553
Victor Stinnerc3c74152011-10-02 20:39:55 +02001554 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001555 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001556 _PyUnicode_UTF8(unicode) = NULL;
1557 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001558 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1559#endif
1560 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1561 }
1562 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001563 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564 return 0;
1565}
1566
Alexander Belopolsky40018472011-02-26 01:02:56 +00001567static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001568unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001569{
Walter Dörwald16807132007-05-25 13:52:07 +00001570 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001571 case SSTATE_NOT_INTERNED:
1572 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001573
Benjamin Peterson29060642009-01-31 22:14:21 +00001574 case SSTATE_INTERNED_MORTAL:
1575 /* revive dead object temporarily for DelItem */
1576 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001577 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001578 Py_FatalError(
1579 "deletion of interned string failed");
1580 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001581
Benjamin Peterson29060642009-01-31 22:14:21 +00001582 case SSTATE_INTERNED_IMMORTAL:
1583 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001584
Benjamin Peterson29060642009-01-31 22:14:21 +00001585 default:
1586 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001587 }
1588
Victor Stinner03490912011-10-03 23:45:12 +02001589 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001590 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001591 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001592 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001593 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1594 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001595
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001596 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001597}
1598
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001599#ifdef Py_DEBUG
1600static int
1601unicode_is_singleton(PyObject *unicode)
1602{
1603 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1604 if (unicode == unicode_empty)
1605 return 1;
1606 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1607 {
1608 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1609 if (ch < 256 && unicode_latin1[ch] == unicode)
1610 return 1;
1611 }
1612 return 0;
1613}
1614#endif
1615
Alexander Belopolsky40018472011-02-26 01:02:56 +00001616static int
Victor Stinner488fa492011-12-12 00:01:39 +01001617unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001618{
Victor Stinner488fa492011-12-12 00:01:39 +01001619 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001620 if (Py_REFCNT(unicode) != 1)
1621 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001622 if (_PyUnicode_HASH(unicode) != -1)
1623 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001624 if (PyUnicode_CHECK_INTERNED(unicode))
1625 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001626 if (!PyUnicode_CheckExact(unicode))
1627 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001628#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001629 /* singleton refcount is greater than 1 */
1630 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001631#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001632 return 1;
1633}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001634
Victor Stinnerfe226c02011-10-03 03:52:20 +02001635static int
1636unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1637{
1638 PyObject *unicode;
1639 Py_ssize_t old_length;
1640
1641 assert(p_unicode != NULL);
1642 unicode = *p_unicode;
1643
1644 assert(unicode != NULL);
1645 assert(PyUnicode_Check(unicode));
1646 assert(0 <= length);
1647
Victor Stinner910337b2011-10-03 03:20:16 +02001648 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001649 old_length = PyUnicode_WSTR_LENGTH(unicode);
1650 else
1651 old_length = PyUnicode_GET_LENGTH(unicode);
1652 if (old_length == length)
1653 return 0;
1654
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001655 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001656 _Py_INCREF_UNICODE_EMPTY();
1657 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001658 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001659 Py_DECREF(*p_unicode);
1660 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 return 0;
1662 }
1663
Victor Stinner488fa492011-12-12 00:01:39 +01001664 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001665 PyObject *copy = resize_copy(unicode, length);
1666 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001667 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001668 Py_DECREF(*p_unicode);
1669 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001670 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001671 }
1672
Victor Stinnerfe226c02011-10-03 03:52:20 +02001673 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001674 PyObject *new_unicode = resize_compact(unicode, length);
1675 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001676 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001677 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001679 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001680 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001681}
1682
Alexander Belopolsky40018472011-02-26 01:02:56 +00001683int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001684PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001685{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686 PyObject *unicode;
1687 if (p_unicode == NULL) {
1688 PyErr_BadInternalCall();
1689 return -1;
1690 }
1691 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001692 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001693 {
1694 PyErr_BadInternalCall();
1695 return -1;
1696 }
1697 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001698}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001699
Victor Stinnerc5166102012-02-22 13:55:02 +01001700/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001701
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001702 WARNING: The function doesn't copy the terminating null character and
1703 doesn't check the maximum character (may write a latin1 character in an
1704 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001705static void
1706unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1707 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001708{
1709 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1710 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001711 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001712
1713 switch (kind) {
1714 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001715 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001716#ifdef Py_DEBUG
1717 if (PyUnicode_IS_ASCII(unicode)) {
1718 Py_UCS4 maxchar = ucs1lib_find_max_char(
1719 (const Py_UCS1*)str,
1720 (const Py_UCS1*)str + len);
1721 assert(maxchar < 128);
1722 }
1723#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001724 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001725 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001726 }
1727 case PyUnicode_2BYTE_KIND: {
1728 Py_UCS2 *start = (Py_UCS2 *)data + index;
1729 Py_UCS2 *ucs2 = start;
1730 assert(index <= PyUnicode_GET_LENGTH(unicode));
1731
Victor Stinner184252a2012-06-16 02:57:41 +02001732 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001733 *ucs2 = (Py_UCS2)*str;
1734
1735 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001736 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001737 }
1738 default: {
1739 Py_UCS4 *start = (Py_UCS4 *)data + index;
1740 Py_UCS4 *ucs4 = start;
1741 assert(kind == PyUnicode_4BYTE_KIND);
1742 assert(index <= PyUnicode_GET_LENGTH(unicode));
1743
Victor Stinner184252a2012-06-16 02:57:41 +02001744 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001745 *ucs4 = (Py_UCS4)*str;
1746
1747 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001748 }
1749 }
1750}
1751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752static PyObject*
1753get_latin1_char(unsigned char ch)
1754{
Victor Stinnera464fc12011-10-02 20:39:30 +02001755 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode)
1759 return NULL;
1760 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001761 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 unicode_latin1[ch] = unicode;
1763 }
1764 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001765 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766}
1767
Victor Stinner985a82a2014-01-03 12:53:47 +01001768static PyObject*
1769unicode_char(Py_UCS4 ch)
1770{
1771 PyObject *unicode;
1772
1773 assert(ch <= MAX_UNICODE);
1774
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001775 if (ch < 256)
1776 return get_latin1_char(ch);
1777
Victor Stinner985a82a2014-01-03 12:53:47 +01001778 unicode = PyUnicode_New(1, ch);
1779 if (unicode == NULL)
1780 return NULL;
1781 switch (PyUnicode_KIND(unicode)) {
1782 case PyUnicode_1BYTE_KIND:
1783 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1784 break;
1785 case PyUnicode_2BYTE_KIND:
1786 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1787 break;
1788 default:
1789 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1790 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1791 }
1792 assert(_PyUnicode_CheckConsistency(unicode, 1));
1793 return unicode;
1794}
1795
Alexander Belopolsky40018472011-02-26 01:02:56 +00001796PyObject *
1797PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001798{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001799 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 Py_UCS4 maxchar = 0;
1801 Py_ssize_t num_surrogates;
1802
1803 if (u == NULL)
1804 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001805
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001806 /* If the Unicode data is known at construction time, we can apply
1807 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001810 if (size == 0)
1811 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813 /* Single character Unicode objects in the Latin-1 range are
1814 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001815 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001816 return get_latin1_char((unsigned char)*u);
1817
1818 /* If not empty and not single character, copy the Unicode data
1819 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001820 if (find_maxchar_surrogates(u, u + size,
1821 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001822 return NULL;
1823
Victor Stinner8faf8212011-12-08 22:14:11 +01001824 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001825 if (!unicode)
1826 return NULL;
1827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 switch (PyUnicode_KIND(unicode)) {
1829 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001830 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001831 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1832 break;
1833 case PyUnicode_2BYTE_KIND:
1834#if Py_UNICODE_SIZE == 2
1835 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1836#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001837 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001838 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1839#endif
1840 break;
1841 case PyUnicode_4BYTE_KIND:
1842#if SIZEOF_WCHAR_T == 2
1843 /* This is the only case which has to process surrogates, thus
1844 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001845 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001846#else
1847 assert(num_surrogates == 0);
1848 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1849#endif
1850 break;
1851 default:
1852 assert(0 && "Impossible state");
1853 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001854
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001855 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001856}
1857
Alexander Belopolsky40018472011-02-26 01:02:56 +00001858PyObject *
1859PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001860{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001861 if (size < 0) {
1862 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001863 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001864 return NULL;
1865 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001866 if (u != NULL)
1867 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1868 else
1869 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001870}
1871
Alexander Belopolsky40018472011-02-26 01:02:56 +00001872PyObject *
1873PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001874{
1875 size_t size = strlen(u);
1876 if (size > PY_SSIZE_T_MAX) {
1877 PyErr_SetString(PyExc_OverflowError, "input too long");
1878 return NULL;
1879 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001880 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001881}
1882
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001883PyObject *
1884_PyUnicode_FromId(_Py_Identifier *id)
1885{
1886 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001887 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1888 strlen(id->string),
1889 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001890 if (!id->object)
1891 return NULL;
1892 PyUnicode_InternInPlace(&id->object);
1893 assert(!id->next);
1894 id->next = static_strings;
1895 static_strings = id;
1896 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001897 return id->object;
1898}
1899
1900void
1901_PyUnicode_ClearStaticStrings()
1902{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001903 _Py_Identifier *tmp, *s = static_strings;
1904 while (s) {
1905 Py_DECREF(s->object);
1906 s->object = NULL;
1907 tmp = s->next;
1908 s->next = NULL;
1909 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001910 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001911 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001912}
1913
Benjamin Peterson0df54292012-03-26 14:50:32 -04001914/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001915
Victor Stinnerd3f08822012-05-29 12:57:52 +02001916PyObject*
1917_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001918{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001919 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001920 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001921 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001922#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001923 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001924#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001925 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001926 }
Victor Stinner785938e2011-12-11 20:09:03 +01001927 unicode = PyUnicode_New(size, 127);
1928 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001929 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001930 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1931 assert(_PyUnicode_CheckConsistency(unicode, 1));
1932 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001933}
1934
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001935static Py_UCS4
1936kind_maxchar_limit(unsigned int kind)
1937{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001938 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001939 case PyUnicode_1BYTE_KIND:
1940 return 0x80;
1941 case PyUnicode_2BYTE_KIND:
1942 return 0x100;
1943 case PyUnicode_4BYTE_KIND:
1944 return 0x10000;
1945 default:
1946 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001947 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001948 }
1949}
1950
Victor Stinnere6abb482012-05-02 01:15:40 +02001951Py_LOCAL_INLINE(Py_UCS4)
1952align_maxchar(Py_UCS4 maxchar)
1953{
1954 if (maxchar <= 127)
1955 return 127;
1956 else if (maxchar <= 255)
1957 return 255;
1958 else if (maxchar <= 65535)
1959 return 65535;
1960 else
1961 return MAX_UNICODE;
1962}
1963
Victor Stinner702c7342011-10-05 13:50:52 +02001964static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001965_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001968 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001969
Serhiy Storchaka678db842013-01-26 12:16:36 +02001970 if (size == 0)
1971 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001972 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001973 if (size == 1)
1974 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001975
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001976 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001977 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 if (!res)
1979 return NULL;
1980 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001981 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001982 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001983}
1984
Victor Stinnere57b1c02011-09-28 22:20:48 +02001985static PyObject*
1986_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987{
1988 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001989 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001990
Serhiy Storchaka678db842013-01-26 12:16:36 +02001991 if (size == 0)
1992 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001993 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001994 if (size == 1)
1995 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001996
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001997 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001998 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 if (!res)
2000 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002001 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002003 else {
2004 _PyUnicode_CONVERT_BYTES(
2005 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2006 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002007 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 return res;
2009}
2010
Victor Stinnere57b1c02011-09-28 22:20:48 +02002011static PyObject*
2012_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013{
2014 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002015 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002016
Serhiy Storchaka678db842013-01-26 12:16:36 +02002017 if (size == 0)
2018 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002019 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002020 if (size == 1)
2021 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002022
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002023 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002024 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025 if (!res)
2026 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002027 if (max_char < 256)
2028 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2029 PyUnicode_1BYTE_DATA(res));
2030 else if (max_char < 0x10000)
2031 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2032 PyUnicode_2BYTE_DATA(res));
2033 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002035 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002036 return res;
2037}
2038
2039PyObject*
2040PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2041{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002042 if (size < 0) {
2043 PyErr_SetString(PyExc_ValueError, "size must be positive");
2044 return NULL;
2045 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002046 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002048 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002050 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002051 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002052 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002053 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 PyErr_SetString(PyExc_SystemError, "invalid kind");
2055 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057}
2058
Victor Stinnerece58de2012-04-23 23:36:38 +02002059Py_UCS4
2060_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2061{
2062 enum PyUnicode_Kind kind;
2063 void *startptr, *endptr;
2064
2065 assert(PyUnicode_IS_READY(unicode));
2066 assert(0 <= start);
2067 assert(end <= PyUnicode_GET_LENGTH(unicode));
2068 assert(start <= end);
2069
2070 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2071 return PyUnicode_MAX_CHAR_VALUE(unicode);
2072
2073 if (start == end)
2074 return 127;
2075
Victor Stinner94d558b2012-04-27 22:26:58 +02002076 if (PyUnicode_IS_ASCII(unicode))
2077 return 127;
2078
Victor Stinnerece58de2012-04-23 23:36:38 +02002079 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002080 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002081 endptr = (char *)startptr + end * kind;
2082 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002083 switch(kind) {
2084 case PyUnicode_1BYTE_KIND:
2085 return ucs1lib_find_max_char(startptr, endptr);
2086 case PyUnicode_2BYTE_KIND:
2087 return ucs2lib_find_max_char(startptr, endptr);
2088 case PyUnicode_4BYTE_KIND:
2089 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002090 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002091 assert(0);
2092 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002093 }
2094}
2095
Victor Stinner25a4b292011-10-06 12:31:55 +02002096/* Ensure that a string uses the most efficient storage, if it is not the
2097 case: create a new string with of the right kind. Write NULL into *p_unicode
2098 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002099static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002100unicode_adjust_maxchar(PyObject **p_unicode)
2101{
2102 PyObject *unicode, *copy;
2103 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002104 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002105 unsigned int kind;
2106
2107 assert(p_unicode != NULL);
2108 unicode = *p_unicode;
2109 assert(PyUnicode_IS_READY(unicode));
2110 if (PyUnicode_IS_ASCII(unicode))
2111 return;
2112
2113 len = PyUnicode_GET_LENGTH(unicode);
2114 kind = PyUnicode_KIND(unicode);
2115 if (kind == PyUnicode_1BYTE_KIND) {
2116 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002117 max_char = ucs1lib_find_max_char(u, u + len);
2118 if (max_char >= 128)
2119 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002120 }
2121 else if (kind == PyUnicode_2BYTE_KIND) {
2122 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002123 max_char = ucs2lib_find_max_char(u, u + len);
2124 if (max_char >= 256)
2125 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002126 }
2127 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002128 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002129 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002130 max_char = ucs4lib_find_max_char(u, u + len);
2131 if (max_char >= 0x10000)
2132 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002133 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002135 if (copy != NULL)
2136 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002137 Py_DECREF(unicode);
2138 *p_unicode = copy;
2139}
2140
Victor Stinner034f6cf2011-09-30 02:26:44 +02002141PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002142_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002143{
Victor Stinner87af4f22011-11-21 23:03:47 +01002144 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002145 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146
Victor Stinner034f6cf2011-09-30 02:26:44 +02002147 if (!PyUnicode_Check(unicode)) {
2148 PyErr_BadInternalCall();
2149 return NULL;
2150 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002151 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002152 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002153
Victor Stinner87af4f22011-11-21 23:03:47 +01002154 length = PyUnicode_GET_LENGTH(unicode);
2155 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002156 if (!copy)
2157 return NULL;
2158 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2159
Victor Stinner87af4f22011-11-21 23:03:47 +01002160 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2161 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002162 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002163 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002164}
2165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002166
Victor Stinnerbc603d12011-10-02 01:00:40 +02002167/* Widen Unicode objects to larger buffers. Don't write terminating null
2168 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169
2170void*
2171_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2172{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002173 Py_ssize_t len;
2174 void *result;
2175 unsigned int skind;
2176
Benjamin Petersonbac79492012-01-14 13:34:47 -05002177 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002178 return NULL;
2179
2180 len = PyUnicode_GET_LENGTH(s);
2181 skind = PyUnicode_KIND(s);
2182 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002183 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184 return NULL;
2185 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002186 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002187 case PyUnicode_2BYTE_KIND:
2188 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2189 if (!result)
2190 return PyErr_NoMemory();
2191 assert(skind == PyUnicode_1BYTE_KIND);
2192 _PyUnicode_CONVERT_BYTES(
2193 Py_UCS1, Py_UCS2,
2194 PyUnicode_1BYTE_DATA(s),
2195 PyUnicode_1BYTE_DATA(s) + len,
2196 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002198 case PyUnicode_4BYTE_KIND:
2199 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2200 if (!result)
2201 return PyErr_NoMemory();
2202 if (skind == PyUnicode_2BYTE_KIND) {
2203 _PyUnicode_CONVERT_BYTES(
2204 Py_UCS2, Py_UCS4,
2205 PyUnicode_2BYTE_DATA(s),
2206 PyUnicode_2BYTE_DATA(s) + len,
2207 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002209 else {
2210 assert(skind == PyUnicode_1BYTE_KIND);
2211 _PyUnicode_CONVERT_BYTES(
2212 Py_UCS1, Py_UCS4,
2213 PyUnicode_1BYTE_DATA(s),
2214 PyUnicode_1BYTE_DATA(s) + len,
2215 result);
2216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002218 default:
2219 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 }
Victor Stinner01698042011-10-04 00:04:26 +02002221 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 return NULL;
2223}
2224
2225static Py_UCS4*
2226as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2227 int copy_null)
2228{
2229 int kind;
2230 void *data;
2231 Py_ssize_t len, targetlen;
2232 if (PyUnicode_READY(string) == -1)
2233 return NULL;
2234 kind = PyUnicode_KIND(string);
2235 data = PyUnicode_DATA(string);
2236 len = PyUnicode_GET_LENGTH(string);
2237 targetlen = len;
2238 if (copy_null)
2239 targetlen++;
2240 if (!target) {
2241 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2242 PyErr_NoMemory();
2243 return NULL;
2244 }
2245 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2246 if (!target) {
2247 PyErr_NoMemory();
2248 return NULL;
2249 }
2250 }
2251 else {
2252 if (targetsize < targetlen) {
2253 PyErr_Format(PyExc_SystemError,
2254 "string is longer than the buffer");
2255 if (copy_null && 0 < targetsize)
2256 target[0] = 0;
2257 return NULL;
2258 }
2259 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002260 if (kind == PyUnicode_1BYTE_KIND) {
2261 Py_UCS1 *start = (Py_UCS1 *) data;
2262 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002263 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002264 else if (kind == PyUnicode_2BYTE_KIND) {
2265 Py_UCS2 *start = (Py_UCS2 *) data;
2266 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2267 }
2268 else {
2269 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002270 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 if (copy_null)
2273 target[len] = 0;
2274 return target;
2275}
2276
2277Py_UCS4*
2278PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2279 int copy_null)
2280{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002281 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002282 PyErr_BadInternalCall();
2283 return NULL;
2284 }
2285 return as_ucs4(string, target, targetsize, copy_null);
2286}
2287
2288Py_UCS4*
2289PyUnicode_AsUCS4Copy(PyObject *string)
2290{
2291 return as_ucs4(string, NULL, 0, 1);
2292}
2293
2294#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002295
Alexander Belopolsky40018472011-02-26 01:02:56 +00002296PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002297PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002298{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002299 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002301 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002302 PyErr_BadInternalCall();
2303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304 }
2305
Martin v. Löwis790465f2008-04-05 20:41:37 +00002306 if (size == -1) {
2307 size = wcslen(w);
2308 }
2309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002311}
2312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002314
Walter Dörwald346737f2007-05-31 10:44:43 +00002315static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002316makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002317 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002318{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002319 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002320 if (longflag)
2321 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002322 else if (longlongflag) {
2323 /* longlongflag should only ever be nonzero on machines with
2324 HAVE_LONG_LONG defined */
2325#ifdef HAVE_LONG_LONG
2326 char *f = PY_FORMAT_LONG_LONG;
2327 while (*f)
2328 *fmt++ = *f++;
2329#else
2330 /* we shouldn't ever get here */
2331 assert(0);
2332 *fmt++ = 'l';
2333#endif
2334 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002335 else if (size_tflag) {
2336 char *f = PY_FORMAT_SIZE_T;
2337 while (*f)
2338 *fmt++ = *f++;
2339 }
2340 *fmt++ = c;
2341 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002342}
2343
Victor Stinner15a11362012-10-06 23:48:20 +02002344/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002345 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2346 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2347#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002348
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002349static int
2350unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2351 Py_ssize_t width, Py_ssize_t precision)
2352{
2353 Py_ssize_t length, fill, arglen;
2354 Py_UCS4 maxchar;
2355
2356 if (PyUnicode_READY(str) == -1)
2357 return -1;
2358
2359 length = PyUnicode_GET_LENGTH(str);
2360 if ((precision == -1 || precision >= length)
2361 && width <= length)
2362 return _PyUnicodeWriter_WriteStr(writer, str);
2363
2364 if (precision != -1)
2365 length = Py_MIN(precision, length);
2366
2367 arglen = Py_MAX(length, width);
2368 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2369 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2370 else
2371 maxchar = writer->maxchar;
2372
2373 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2374 return -1;
2375
2376 if (width > length) {
2377 fill = width - length;
2378 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2379 return -1;
2380 writer->pos += fill;
2381 }
2382
2383 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2384 str, 0, length);
2385 writer->pos += length;
2386 return 0;
2387}
2388
2389static int
2390unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2391 Py_ssize_t width, Py_ssize_t precision)
2392{
2393 /* UTF-8 */
2394 Py_ssize_t length;
2395 PyObject *unicode;
2396 int res;
2397
2398 length = strlen(str);
2399 if (precision != -1)
2400 length = Py_MIN(length, precision);
2401 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2402 if (unicode == NULL)
2403 return -1;
2404
2405 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2406 Py_DECREF(unicode);
2407 return res;
2408}
2409
Victor Stinner96865452011-03-01 23:44:09 +00002410static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002411unicode_fromformat_arg(_PyUnicodeWriter *writer,
2412 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002413{
Victor Stinnere215d962012-10-06 23:03:36 +02002414 const char *p;
2415 Py_ssize_t len;
2416 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002417 Py_ssize_t width;
2418 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002419 int longflag;
2420 int longlongflag;
2421 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002422 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002423
2424 p = f;
2425 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002426 zeropad = 0;
2427 if (*f == '0') {
2428 zeropad = 1;
2429 f++;
2430 }
Victor Stinner96865452011-03-01 23:44:09 +00002431
2432 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002433 width = -1;
2434 if (Py_ISDIGIT((unsigned)*f)) {
2435 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002436 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002437 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002438 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002439 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002440 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002441 return NULL;
2442 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002443 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002444 f++;
2445 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002446 }
2447 precision = -1;
2448 if (*f == '.') {
2449 f++;
2450 if (Py_ISDIGIT((unsigned)*f)) {
2451 precision = (*f - '0');
2452 f++;
2453 while (Py_ISDIGIT((unsigned)*f)) {
2454 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2455 PyErr_SetString(PyExc_ValueError,
2456 "precision too big");
2457 return NULL;
2458 }
2459 precision = (precision * 10) + (*f - '0');
2460 f++;
2461 }
2462 }
Victor Stinner96865452011-03-01 23:44:09 +00002463 if (*f == '%') {
2464 /* "%.3%s" => f points to "3" */
2465 f--;
2466 }
2467 }
2468 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002469 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002470 f--;
2471 }
Victor Stinner96865452011-03-01 23:44:09 +00002472
2473 /* Handle %ld, %lu, %lld and %llu. */
2474 longflag = 0;
2475 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002476 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002477 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002478 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002479 longflag = 1;
2480 ++f;
2481 }
2482#ifdef HAVE_LONG_LONG
2483 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002484 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002485 longlongflag = 1;
2486 f += 2;
2487 }
2488#endif
2489 }
2490 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002491 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002492 size_tflag = 1;
2493 ++f;
2494 }
Victor Stinnere215d962012-10-06 23:03:36 +02002495
2496 if (f[1] == '\0')
2497 writer->overallocate = 0;
2498
2499 switch (*f) {
2500 case 'c':
2501 {
2502 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002503 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002504 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002505 "character argument not in range(0x110000)");
2506 return NULL;
2507 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002508 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002509 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002510 break;
2511 }
2512
2513 case 'i':
2514 case 'd':
2515 case 'u':
2516 case 'x':
2517 {
2518 /* used by sprintf */
2519 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002520 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002521 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002522
2523 if (*f == 'u') {
2524 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2525
2526 if (longflag)
2527 len = sprintf(buffer, fmt,
2528 va_arg(*vargs, unsigned long));
2529#ifdef HAVE_LONG_LONG
2530 else if (longlongflag)
2531 len = sprintf(buffer, fmt,
2532 va_arg(*vargs, unsigned PY_LONG_LONG));
2533#endif
2534 else if (size_tflag)
2535 len = sprintf(buffer, fmt,
2536 va_arg(*vargs, size_t));
2537 else
2538 len = sprintf(buffer, fmt,
2539 va_arg(*vargs, unsigned int));
2540 }
2541 else if (*f == 'x') {
2542 makefmt(fmt, 0, 0, 0, 'x');
2543 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2544 }
2545 else {
2546 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2547
2548 if (longflag)
2549 len = sprintf(buffer, fmt,
2550 va_arg(*vargs, long));
2551#ifdef HAVE_LONG_LONG
2552 else if (longlongflag)
2553 len = sprintf(buffer, fmt,
2554 va_arg(*vargs, PY_LONG_LONG));
2555#endif
2556 else if (size_tflag)
2557 len = sprintf(buffer, fmt,
2558 va_arg(*vargs, Py_ssize_t));
2559 else
2560 len = sprintf(buffer, fmt,
2561 va_arg(*vargs, int));
2562 }
2563 assert(len >= 0);
2564
Victor Stinnere215d962012-10-06 23:03:36 +02002565 if (precision < len)
2566 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002567
2568 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002569 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2570 return NULL;
2571
Victor Stinnere215d962012-10-06 23:03:36 +02002572 if (width > precision) {
2573 Py_UCS4 fillchar;
2574 fill = width - precision;
2575 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002576 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2577 return NULL;
2578 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002579 }
Victor Stinner15a11362012-10-06 23:48:20 +02002580 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002581 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002582 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2583 return NULL;
2584 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002585 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002586
Victor Stinner4a587072013-11-19 12:54:53 +01002587 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2588 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002589 break;
2590 }
2591
2592 case 'p':
2593 {
2594 char number[MAX_LONG_LONG_CHARS];
2595
2596 len = sprintf(number, "%p", va_arg(*vargs, void*));
2597 assert(len >= 0);
2598
2599 /* %p is ill-defined: ensure leading 0x. */
2600 if (number[1] == 'X')
2601 number[1] = 'x';
2602 else if (number[1] != 'x') {
2603 memmove(number + 2, number,
2604 strlen(number) + 1);
2605 number[0] = '0';
2606 number[1] = 'x';
2607 len += 2;
2608 }
2609
Victor Stinner4a587072013-11-19 12:54:53 +01002610 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002611 return NULL;
2612 break;
2613 }
2614
2615 case 's':
2616 {
2617 /* UTF-8 */
2618 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002619 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002620 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002621 break;
2622 }
2623
2624 case 'U':
2625 {
2626 PyObject *obj = va_arg(*vargs, PyObject *);
2627 assert(obj && _PyUnicode_CHECK(obj));
2628
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002629 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002630 return NULL;
2631 break;
2632 }
2633
2634 case 'V':
2635 {
2636 PyObject *obj = va_arg(*vargs, PyObject *);
2637 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002638 if (obj) {
2639 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002640 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002641 return NULL;
2642 }
2643 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002644 assert(str != NULL);
2645 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002646 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002647 }
2648 break;
2649 }
2650
2651 case 'S':
2652 {
2653 PyObject *obj = va_arg(*vargs, PyObject *);
2654 PyObject *str;
2655 assert(obj);
2656 str = PyObject_Str(obj);
2657 if (!str)
2658 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002659 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002660 Py_DECREF(str);
2661 return NULL;
2662 }
2663 Py_DECREF(str);
2664 break;
2665 }
2666
2667 case 'R':
2668 {
2669 PyObject *obj = va_arg(*vargs, PyObject *);
2670 PyObject *repr;
2671 assert(obj);
2672 repr = PyObject_Repr(obj);
2673 if (!repr)
2674 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002675 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002676 Py_DECREF(repr);
2677 return NULL;
2678 }
2679 Py_DECREF(repr);
2680 break;
2681 }
2682
2683 case 'A':
2684 {
2685 PyObject *obj = va_arg(*vargs, PyObject *);
2686 PyObject *ascii;
2687 assert(obj);
2688 ascii = PyObject_ASCII(obj);
2689 if (!ascii)
2690 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002691 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002692 Py_DECREF(ascii);
2693 return NULL;
2694 }
2695 Py_DECREF(ascii);
2696 break;
2697 }
2698
2699 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002700 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002701 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002702 break;
2703
2704 default:
2705 /* if we stumble upon an unknown formatting code, copy the rest
2706 of the format string to the output string. (we cannot just
2707 skip the code, since there's no way to know what's in the
2708 argument list) */
2709 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002710 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002711 return NULL;
2712 f = p+len;
2713 return f;
2714 }
2715
2716 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002717 return f;
2718}
2719
Walter Dörwaldd2034312007-05-18 16:29:38 +00002720PyObject *
2721PyUnicode_FromFormatV(const char *format, va_list vargs)
2722{
Victor Stinnere215d962012-10-06 23:03:36 +02002723 va_list vargs2;
2724 const char *f;
2725 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002726
Victor Stinner8f674cc2013-04-17 23:02:17 +02002727 _PyUnicodeWriter_Init(&writer);
2728 writer.min_length = strlen(format) + 100;
2729 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002730
2731 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2732 Copy it to be able to pass a reference to a subfunction. */
2733 Py_VA_COPY(vargs2, vargs);
2734
2735 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002736 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002737 f = unicode_fromformat_arg(&writer, f, &vargs2);
2738 if (f == NULL)
2739 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002742 const char *p;
2743 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002744
Victor Stinnere215d962012-10-06 23:03:36 +02002745 p = f;
2746 do
2747 {
2748 if ((unsigned char)*p > 127) {
2749 PyErr_Format(PyExc_ValueError,
2750 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2751 "string, got a non-ASCII byte: 0x%02x",
2752 (unsigned char)*p);
2753 return NULL;
2754 }
2755 p++;
2756 }
2757 while (*p != '\0' && *p != '%');
2758 len = p - f;
2759
2760 if (*p == '\0')
2761 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002762
2763 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002764 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002765
2766 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002767 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002768 }
Victor Stinnere215d962012-10-06 23:03:36 +02002769 return _PyUnicodeWriter_Finish(&writer);
2770
2771 fail:
2772 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002773 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002774}
2775
Walter Dörwaldd2034312007-05-18 16:29:38 +00002776PyObject *
2777PyUnicode_FromFormat(const char *format, ...)
2778{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002779 PyObject* ret;
2780 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002781
2782#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002783 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002784#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002785 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002786#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002787 ret = PyUnicode_FromFormatV(format, vargs);
2788 va_end(vargs);
2789 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002790}
2791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792#ifdef HAVE_WCHAR_H
2793
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2795 convert a Unicode object to a wide character string.
2796
Victor Stinnerd88d9832011-09-06 02:00:05 +02002797 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002798 character) required to convert the unicode object. Ignore size argument.
2799
Victor Stinnerd88d9832011-09-06 02:00:05 +02002800 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002801 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002802 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002803static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002804unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002805 wchar_t *w,
2806 Py_ssize_t size)
2807{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002808 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002809 const wchar_t *wstr;
2810
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002811 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 if (wstr == NULL)
2813 return -1;
2814
Victor Stinner5593d8a2010-10-02 11:11:27 +00002815 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002816 if (size > res)
2817 size = res + 1;
2818 else
2819 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002821 return res;
2822 }
2823 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002824 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002825}
2826
2827Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002828PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002829 wchar_t *w,
2830 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002831{
2832 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002833 PyErr_BadInternalCall();
2834 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002835 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002836 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002837}
2838
Victor Stinner137c34c2010-09-29 10:25:54 +00002839wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002840PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002841 Py_ssize_t *size)
2842{
2843 wchar_t* buffer;
2844 Py_ssize_t buflen;
2845
2846 if (unicode == NULL) {
2847 PyErr_BadInternalCall();
2848 return NULL;
2849 }
2850
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002851 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002852 if (buflen == -1)
2853 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002854 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002855 PyErr_NoMemory();
2856 return NULL;
2857 }
2858
Victor Stinner137c34c2010-09-29 10:25:54 +00002859 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2860 if (buffer == NULL) {
2861 PyErr_NoMemory();
2862 return NULL;
2863 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002864 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002865 if (buflen == -1) {
2866 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002867 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002868 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002869 if (size != NULL)
2870 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002871 return buffer;
2872}
2873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002874#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875
Alexander Belopolsky40018472011-02-26 01:02:56 +00002876PyObject *
2877PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002878{
Victor Stinner8faf8212011-12-08 22:14:11 +01002879 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002880 PyErr_SetString(PyExc_ValueError,
2881 "chr() arg not in range(0x110000)");
2882 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002883 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002884
Victor Stinner985a82a2014-01-03 12:53:47 +01002885 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002886}
2887
Alexander Belopolsky40018472011-02-26 01:02:56 +00002888PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002889PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002890{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002891 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002892 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002893 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002894 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002895 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002896 Py_INCREF(obj);
2897 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002898 }
2899 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002900 /* For a Unicode subtype that's not a Unicode object,
2901 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002902 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002903 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002904 PyErr_Format(PyExc_TypeError,
2905 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002906 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002907 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002908}
2909
Alexander Belopolsky40018472011-02-26 01:02:56 +00002910PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002911PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002912 const char *encoding,
2913 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002914{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002915 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002916 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002917
Guido van Rossumd57fd912000-03-10 22:53:23 +00002918 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002919 PyErr_BadInternalCall();
2920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002922
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002923 /* Decoding bytes objects is the most common case and should be fast */
2924 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002925 if (PyBytes_GET_SIZE(obj) == 0)
2926 _Py_RETURN_UNICODE_EMPTY();
2927 v = PyUnicode_Decode(
2928 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2929 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002930 return v;
2931 }
2932
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002933 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002934 PyErr_SetString(PyExc_TypeError,
2935 "decoding str is not supported");
2936 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002937 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002938
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002939 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2940 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2941 PyErr_Format(PyExc_TypeError,
2942 "coercing to str: need bytes, bytearray "
2943 "or buffer-like object, %.80s found",
2944 Py_TYPE(obj)->tp_name);
2945 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002946 }
Tim Petersced69f82003-09-16 20:30:58 +00002947
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002948 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002949 PyBuffer_Release(&buffer);
2950 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002952
Serhiy Storchaka05997252013-01-26 12:14:02 +02002953 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002954 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002955 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002956}
2957
Victor Stinner600d3be2010-06-10 12:00:55 +00002958/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002959 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2960 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002961int
2962_Py_normalize_encoding(const char *encoding,
2963 char *lower,
2964 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002965{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002966 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002967 char *l;
2968 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002969
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002970 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002971 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002972 if (lower_len < 6)
2973 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002974 strcpy(lower, "utf-8");
2975 return 1;
2976 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002977 e = encoding;
2978 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002979 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002980 while (*e) {
2981 if (l == l_end)
2982 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002983 if (Py_ISUPPER(*e)) {
2984 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002985 }
2986 else if (*e == '_') {
2987 *l++ = '-';
2988 e++;
2989 }
2990 else {
2991 *l++ = *e++;
2992 }
2993 }
2994 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002995 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002996}
2997
Alexander Belopolsky40018472011-02-26 01:02:56 +00002998PyObject *
2999PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003000 Py_ssize_t size,
3001 const char *encoding,
3002 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003003{
3004 PyObject *buffer = NULL, *unicode;
3005 Py_buffer info;
3006 char lower[11]; /* Enough for any encoding shortcut */
3007
Fred Drakee4315f52000-05-09 19:53:39 +00003008 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003009 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003010 if ((strcmp(lower, "utf-8") == 0) ||
3011 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003012 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003013 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003014 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003015 (strcmp(lower, "iso-8859-1") == 0) ||
3016 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003017 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003018#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003019 else if (strcmp(lower, "mbcs") == 0)
3020 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003021#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003022 else if (strcmp(lower, "ascii") == 0)
3023 return PyUnicode_DecodeASCII(s, size, errors);
3024 else if (strcmp(lower, "utf-16") == 0)
3025 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3026 else if (strcmp(lower, "utf-32") == 0)
3027 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3028 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003029
3030 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003031 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003032 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003033 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003034 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003035 if (buffer == NULL)
3036 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003037 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003038 if (unicode == NULL)
3039 goto onError;
3040 if (!PyUnicode_Check(unicode)) {
3041 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003042 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3043 "use codecs.decode() to decode to arbitrary types",
3044 encoding,
3045 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 Py_DECREF(unicode);
3047 goto onError;
3048 }
3049 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003050 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003051
Benjamin Peterson29060642009-01-31 22:14:21 +00003052 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003053 Py_XDECREF(buffer);
3054 return NULL;
3055}
3056
Alexander Belopolsky40018472011-02-26 01:02:56 +00003057PyObject *
3058PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003059 const char *encoding,
3060 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061{
3062 PyObject *v;
3063
3064 if (!PyUnicode_Check(unicode)) {
3065 PyErr_BadArgument();
3066 goto onError;
3067 }
3068
3069 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003070 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003071
3072 /* Decode via the codec registry */
3073 v = PyCodec_Decode(unicode, encoding, errors);
3074 if (v == NULL)
3075 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003076 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003077
Benjamin Peterson29060642009-01-31 22:14:21 +00003078 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003079 return NULL;
3080}
3081
Alexander Belopolsky40018472011-02-26 01:02:56 +00003082PyObject *
3083PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003084 const char *encoding,
3085 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003086{
3087 PyObject *v;
3088
3089 if (!PyUnicode_Check(unicode)) {
3090 PyErr_BadArgument();
3091 goto onError;
3092 }
3093
3094 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003095 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003096
3097 /* Decode via the codec registry */
3098 v = PyCodec_Decode(unicode, encoding, errors);
3099 if (v == NULL)
3100 goto onError;
3101 if (!PyUnicode_Check(v)) {
3102 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003103 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3104 "use codecs.decode() to decode to arbitrary types",
3105 encoding,
3106 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003107 Py_DECREF(v);
3108 goto onError;
3109 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003110 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003111
Benjamin Peterson29060642009-01-31 22:14:21 +00003112 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003113 return NULL;
3114}
3115
Alexander Belopolsky40018472011-02-26 01:02:56 +00003116PyObject *
3117PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003118 Py_ssize_t size,
3119 const char *encoding,
3120 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121{
3122 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003123
Guido van Rossumd57fd912000-03-10 22:53:23 +00003124 unicode = PyUnicode_FromUnicode(s, size);
3125 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003126 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3128 Py_DECREF(unicode);
3129 return v;
3130}
3131
Alexander Belopolsky40018472011-02-26 01:02:56 +00003132PyObject *
3133PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003134 const char *encoding,
3135 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003136{
3137 PyObject *v;
3138
3139 if (!PyUnicode_Check(unicode)) {
3140 PyErr_BadArgument();
3141 goto onError;
3142 }
3143
3144 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003146
3147 /* Encode via the codec registry */
3148 v = PyCodec_Encode(unicode, encoding, errors);
3149 if (v == NULL)
3150 goto onError;
3151 return v;
3152
Benjamin Peterson29060642009-01-31 22:14:21 +00003153 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003154 return NULL;
3155}
3156
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003157static size_t
3158wcstombs_errorpos(const wchar_t *wstr)
3159{
3160 size_t len;
3161#if SIZEOF_WCHAR_T == 2
3162 wchar_t buf[3];
3163#else
3164 wchar_t buf[2];
3165#endif
3166 char outbuf[MB_LEN_MAX];
3167 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003168
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003169#if SIZEOF_WCHAR_T == 2
3170 buf[2] = 0;
3171#else
3172 buf[1] = 0;
3173#endif
3174 start = wstr;
3175 while (*wstr != L'\0')
3176 {
3177 previous = wstr;
3178#if SIZEOF_WCHAR_T == 2
3179 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3180 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3181 {
3182 buf[0] = wstr[0];
3183 buf[1] = wstr[1];
3184 wstr += 2;
3185 }
3186 else {
3187 buf[0] = *wstr;
3188 buf[1] = 0;
3189 wstr++;
3190 }
3191#else
3192 buf[0] = *wstr;
3193 wstr++;
3194#endif
3195 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003196 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003197 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 }
3199
3200 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003201 return 0;
3202}
3203
Victor Stinner1b579672011-12-17 05:47:23 +01003204static int
3205locale_error_handler(const char *errors, int *surrogateescape)
3206{
3207 if (errors == NULL) {
3208 *surrogateescape = 0;
3209 return 0;
3210 }
3211
3212 if (strcmp(errors, "strict") == 0) {
3213 *surrogateescape = 0;
3214 return 0;
3215 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003216 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003217 *surrogateescape = 1;
3218 return 0;
3219 }
3220 PyErr_Format(PyExc_ValueError,
3221 "only 'strict' and 'surrogateescape' error handlers "
3222 "are supported, not '%s'",
3223 errors);
3224 return -1;
3225}
3226
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003227PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003228PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003229{
3230 Py_ssize_t wlen, wlen2;
3231 wchar_t *wstr;
3232 PyObject *bytes = NULL;
3233 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003234 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003235 PyObject *exc;
3236 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003237 int surrogateescape;
3238
3239 if (locale_error_handler(errors, &surrogateescape) < 0)
3240 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003241
3242 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3243 if (wstr == NULL)
3244 return NULL;
3245
3246 wlen2 = wcslen(wstr);
3247 if (wlen2 != wlen) {
3248 PyMem_Free(wstr);
3249 PyErr_SetString(PyExc_TypeError, "embedded null character");
3250 return NULL;
3251 }
3252
3253 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003254 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003255 char *str;
3256
3257 str = _Py_wchar2char(wstr, &error_pos);
3258 if (str == NULL) {
3259 if (error_pos == (size_t)-1) {
3260 PyErr_NoMemory();
3261 PyMem_Free(wstr);
3262 return NULL;
3263 }
3264 else {
3265 goto encode_error;
3266 }
3267 }
3268 PyMem_Free(wstr);
3269
3270 bytes = PyBytes_FromString(str);
3271 PyMem_Free(str);
3272 }
3273 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003274 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003275 size_t len, len2;
3276
3277 len = wcstombs(NULL, wstr, 0);
3278 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003279 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 goto encode_error;
3281 }
3282
3283 bytes = PyBytes_FromStringAndSize(NULL, len);
3284 if (bytes == NULL) {
3285 PyMem_Free(wstr);
3286 return NULL;
3287 }
3288
3289 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3290 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003291 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003292 goto encode_error;
3293 }
3294 PyMem_Free(wstr);
3295 }
3296 return bytes;
3297
3298encode_error:
3299 errmsg = strerror(errno);
3300 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003301
3302 if (error_pos == (size_t)-1)
3303 error_pos = wcstombs_errorpos(wstr);
3304
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003305 PyMem_Free(wstr);
3306 Py_XDECREF(bytes);
3307
Victor Stinner2f197072011-12-17 07:08:30 +01003308 if (errmsg != NULL) {
3309 size_t errlen;
3310 wstr = _Py_char2wchar(errmsg, &errlen);
3311 if (wstr != NULL) {
3312 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003313 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003314 } else
3315 errmsg = NULL;
3316 }
3317 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003318 reason = PyUnicode_FromString(
3319 "wcstombs() encountered an unencodable "
3320 "wide character");
3321 if (reason == NULL)
3322 return NULL;
3323
3324 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3325 "locale", unicode,
3326 (Py_ssize_t)error_pos,
3327 (Py_ssize_t)(error_pos+1),
3328 reason);
3329 Py_DECREF(reason);
3330 if (exc != NULL) {
3331 PyCodec_StrictErrors(exc);
3332 Py_XDECREF(exc);
3333 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003334 return NULL;
3335}
3336
Victor Stinnerad158722010-10-27 00:25:46 +00003337PyObject *
3338PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003339{
Victor Stinner99b95382011-07-04 14:23:54 +02003340#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003341 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003342#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003343 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003344#else
Victor Stinner793b5312011-04-27 00:24:21 +02003345 PyInterpreterState *interp = PyThreadState_GET()->interp;
3346 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3347 cannot use it to encode and decode filenames before it is loaded. Load
3348 the Python codec requires to encode at least its own filename. Use the C
3349 version of the locale codec until the codec registry is initialized and
3350 the Python codec is loaded.
3351
3352 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3353 cannot only rely on it: check also interp->fscodec_initialized for
3354 subinterpreters. */
3355 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003356 return PyUnicode_AsEncodedString(unicode,
3357 Py_FileSystemDefaultEncoding,
3358 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003359 }
3360 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003361 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003362 }
Victor Stinnerad158722010-10-27 00:25:46 +00003363#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003364}
3365
Alexander Belopolsky40018472011-02-26 01:02:56 +00003366PyObject *
3367PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003368 const char *encoding,
3369 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003370{
3371 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003372 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003373
Guido van Rossumd57fd912000-03-10 22:53:23 +00003374 if (!PyUnicode_Check(unicode)) {
3375 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003376 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003377 }
Fred Drakee4315f52000-05-09 19:53:39 +00003378
Fred Drakee4315f52000-05-09 19:53:39 +00003379 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003380 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003381 if ((strcmp(lower, "utf-8") == 0) ||
3382 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003383 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003384 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003385 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003386 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003388 }
Victor Stinner37296e82010-06-10 13:36:23 +00003389 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003390 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003391 (strcmp(lower, "iso-8859-1") == 0) ||
3392 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003394#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003395 else if (strcmp(lower, "mbcs") == 0)
3396 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003397#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003398 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003399 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003400 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003401
3402 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003403 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003404 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003405 return NULL;
3406
3407 /* The normal path */
3408 if (PyBytes_Check(v))
3409 return v;
3410
3411 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003412 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003413 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003414 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003415
3416 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003417 "encoder %s returned bytearray instead of bytes; "
3418 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003419 encoding);
3420 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003421 Py_DECREF(v);
3422 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003423 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003425 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3426 Py_DECREF(v);
3427 return b;
3428 }
3429
3430 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003431 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3432 "use codecs.encode() to encode to arbitrary types",
3433 encoding,
3434 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003435 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003436 return NULL;
3437}
3438
Alexander Belopolsky40018472011-02-26 01:02:56 +00003439PyObject *
3440PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003441 const char *encoding,
3442 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003443{
3444 PyObject *v;
3445
3446 if (!PyUnicode_Check(unicode)) {
3447 PyErr_BadArgument();
3448 goto onError;
3449 }
3450
3451 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003452 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003453
3454 /* Encode via the codec registry */
3455 v = PyCodec_Encode(unicode, encoding, errors);
3456 if (v == NULL)
3457 goto onError;
3458 if (!PyUnicode_Check(v)) {
3459 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003460 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3461 "use codecs.encode() to encode to arbitrary types",
3462 encoding,
3463 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003464 Py_DECREF(v);
3465 goto onError;
3466 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003467 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003468
Benjamin Peterson29060642009-01-31 22:14:21 +00003469 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003470 return NULL;
3471}
3472
Victor Stinner2f197072011-12-17 07:08:30 +01003473static size_t
3474mbstowcs_errorpos(const char *str, size_t len)
3475{
3476#ifdef HAVE_MBRTOWC
3477 const char *start = str;
3478 mbstate_t mbs;
3479 size_t converted;
3480 wchar_t ch;
3481
3482 memset(&mbs, 0, sizeof mbs);
3483 while (len)
3484 {
3485 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3486 if (converted == 0)
3487 /* Reached end of string */
3488 break;
3489 if (converted == (size_t)-1 || converted == (size_t)-2) {
3490 /* Conversion error or incomplete character */
3491 return str - start;
3492 }
3493 else {
3494 str += converted;
3495 len -= converted;
3496 }
3497 }
3498 /* failed to find the undecodable byte sequence */
3499 return 0;
3500#endif
3501 return 0;
3502}
3503
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003504PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003505PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003506 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003507{
3508 wchar_t smallbuf[256];
3509 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3510 wchar_t *wstr;
3511 size_t wlen, wlen2;
3512 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003513 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003514 size_t error_pos;
3515 char *errmsg;
3516 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003517
3518 if (locale_error_handler(errors, &surrogateescape) < 0)
3519 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003520
3521 if (str[len] != '\0' || len != strlen(str)) {
3522 PyErr_SetString(PyExc_TypeError, "embedded null character");
3523 return NULL;
3524 }
3525
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003526 if (surrogateescape) {
3527 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003528 wstr = _Py_char2wchar(str, &wlen);
3529 if (wstr == NULL) {
3530 if (wlen == (size_t)-1)
3531 PyErr_NoMemory();
3532 else
3533 PyErr_SetFromErrno(PyExc_OSError);
3534 return NULL;
3535 }
3536
3537 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003538 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003539 }
3540 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003541 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003542#ifndef HAVE_BROKEN_MBSTOWCS
3543 wlen = mbstowcs(NULL, str, 0);
3544#else
3545 wlen = len;
3546#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003547 if (wlen == (size_t)-1)
3548 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549 if (wlen+1 <= smallbuf_len) {
3550 wstr = smallbuf;
3551 }
3552 else {
3553 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3554 return PyErr_NoMemory();
3555
3556 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3557 if (!wstr)
3558 return PyErr_NoMemory();
3559 }
3560
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003561 wlen2 = mbstowcs(wstr, str, wlen+1);
3562 if (wlen2 == (size_t)-1) {
3563 if (wstr != smallbuf)
3564 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003565 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003566 }
3567#ifdef HAVE_BROKEN_MBSTOWCS
3568 assert(wlen2 == wlen);
3569#endif
3570 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3571 if (wstr != smallbuf)
3572 PyMem_Free(wstr);
3573 }
3574 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003575
3576decode_error:
3577 errmsg = strerror(errno);
3578 assert(errmsg != NULL);
3579
3580 error_pos = mbstowcs_errorpos(str, len);
3581 if (errmsg != NULL) {
3582 size_t errlen;
3583 wstr = _Py_char2wchar(errmsg, &errlen);
3584 if (wstr != NULL) {
3585 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003586 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003587 } else
3588 errmsg = NULL;
3589 }
3590 if (errmsg == NULL)
3591 reason = PyUnicode_FromString(
3592 "mbstowcs() encountered an invalid multibyte sequence");
3593 if (reason == NULL)
3594 return NULL;
3595
3596 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3597 "locale", str, len,
3598 (Py_ssize_t)error_pos,
3599 (Py_ssize_t)(error_pos+1),
3600 reason);
3601 Py_DECREF(reason);
3602 if (exc != NULL) {
3603 PyCodec_StrictErrors(exc);
3604 Py_XDECREF(exc);
3605 }
3606 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003607}
3608
3609PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003610PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003611{
3612 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003613 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003614}
3615
3616
3617PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003618PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003619 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003620 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3621}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003622
Christian Heimes5894ba72007-11-04 11:43:14 +00003623PyObject*
3624PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3625{
Victor Stinner99b95382011-07-04 14:23:54 +02003626#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003627 return PyUnicode_DecodeMBCS(s, size, NULL);
3628#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003629 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003630#else
Victor Stinner793b5312011-04-27 00:24:21 +02003631 PyInterpreterState *interp = PyThreadState_GET()->interp;
3632 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3633 cannot use it to encode and decode filenames before it is loaded. Load
3634 the Python codec requires to encode at least its own filename. Use the C
3635 version of the locale codec until the codec registry is initialized and
3636 the Python codec is loaded.
3637
3638 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3639 cannot only rely on it: check also interp->fscodec_initialized for
3640 subinterpreters. */
3641 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003642 return PyUnicode_Decode(s, size,
3643 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003644 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003645 }
3646 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003647 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003648 }
Victor Stinnerad158722010-10-27 00:25:46 +00003649#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003650}
3651
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652
3653int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003654_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003655{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003656 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003657
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003658 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003659 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003660 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3661 PyUnicode_GET_LENGTH(str), '\0', 1);
3662 if (pos == -1)
3663 return 0;
3664 else
3665 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003666}
3667
Antoine Pitrou13348842012-01-29 18:36:34 +01003668int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003669PyUnicode_FSConverter(PyObject* arg, void* addr)
3670{
3671 PyObject *output = NULL;
3672 Py_ssize_t size;
3673 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003674 if (arg == NULL) {
3675 Py_DECREF(*(PyObject**)addr);
3676 return 1;
3677 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003678 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003679 output = arg;
3680 Py_INCREF(output);
3681 }
3682 else {
3683 arg = PyUnicode_FromObject(arg);
3684 if (!arg)
3685 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003686 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003687 Py_DECREF(arg);
3688 if (!output)
3689 return 0;
3690 if (!PyBytes_Check(output)) {
3691 Py_DECREF(output);
3692 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3693 return 0;
3694 }
3695 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003696 size = PyBytes_GET_SIZE(output);
3697 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003698 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003699 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003700 Py_DECREF(output);
3701 return 0;
3702 }
3703 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003704 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003705}
3706
3707
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003708int
3709PyUnicode_FSDecoder(PyObject* arg, void* addr)
3710{
3711 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003712 if (arg == NULL) {
3713 Py_DECREF(*(PyObject**)addr);
3714 return 1;
3715 }
3716 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003717 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003718 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003719 output = arg;
3720 Py_INCREF(output);
3721 }
3722 else {
3723 arg = PyBytes_FromObject(arg);
3724 if (!arg)
3725 return 0;
3726 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3727 PyBytes_GET_SIZE(arg));
3728 Py_DECREF(arg);
3729 if (!output)
3730 return 0;
3731 if (!PyUnicode_Check(output)) {
3732 Py_DECREF(output);
3733 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3734 return 0;
3735 }
3736 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003737 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003738 Py_DECREF(output);
3739 return 0;
3740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003741 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003742 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003743 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3744 Py_DECREF(output);
3745 return 0;
3746 }
3747 *(PyObject**)addr = output;
3748 return Py_CLEANUP_SUPPORTED;
3749}
3750
3751
Martin v. Löwis5b222132007-06-10 09:51:05 +00003752char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003753PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003754{
Christian Heimesf3863112007-11-22 07:46:41 +00003755 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003757 if (!PyUnicode_Check(unicode)) {
3758 PyErr_BadArgument();
3759 return NULL;
3760 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003761 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003762 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003763
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003764 if (PyUnicode_UTF8(unicode) == NULL) {
3765 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3767 if (bytes == NULL)
3768 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003769 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3770 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003771 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003772 Py_DECREF(bytes);
3773 return NULL;
3774 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003775 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3776 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3777 PyBytes_AS_STRING(bytes),
3778 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 Py_DECREF(bytes);
3780 }
3781
3782 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003783 *psize = PyUnicode_UTF8_LENGTH(unicode);
3784 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003785}
3786
3787char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003789{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003790 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3791}
3792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793Py_UNICODE *
3794PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796 const unsigned char *one_byte;
3797#if SIZEOF_WCHAR_T == 4
3798 const Py_UCS2 *two_bytes;
3799#else
3800 const Py_UCS4 *four_bytes;
3801 const Py_UCS4 *ucs4_end;
3802 Py_ssize_t num_surrogates;
3803#endif
3804 wchar_t *w;
3805 wchar_t *wchar_end;
3806
3807 if (!PyUnicode_Check(unicode)) {
3808 PyErr_BadArgument();
3809 return NULL;
3810 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003811 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003813 assert(_PyUnicode_KIND(unicode) != 0);
3814 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003818 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3819 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 num_surrogates = 0;
3821
3822 for (; four_bytes < ucs4_end; ++four_bytes) {
3823 if (*four_bytes > 0xFFFF)
3824 ++num_surrogates;
3825 }
3826
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003827 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3828 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3829 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830 PyErr_NoMemory();
3831 return NULL;
3832 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003833 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 w = _PyUnicode_WSTR(unicode);
3836 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3837 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003838 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3839 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003840 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003842 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3843 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 }
3845 else
3846 *w = *four_bytes;
3847
3848 if (w > wchar_end) {
3849 assert(0 && "Miscalculated string end");
3850 }
3851 }
3852 *w = 0;
3853#else
3854 /* sizeof(wchar_t) == 4 */
3855 Py_FatalError("Impossible unicode object state, wstr and str "
3856 "should share memory already.");
3857 return NULL;
3858#endif
3859 }
3860 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003861 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3862 (_PyUnicode_LENGTH(unicode) + 1));
3863 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003864 PyErr_NoMemory();
3865 return NULL;
3866 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003867 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3868 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3869 w = _PyUnicode_WSTR(unicode);
3870 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003872 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3873 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 for (; w < wchar_end; ++one_byte, ++w)
3875 *w = *one_byte;
3876 /* null-terminate the wstr */
3877 *w = 0;
3878 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003879 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003882 for (; w < wchar_end; ++two_bytes, ++w)
3883 *w = *two_bytes;
3884 /* null-terminate the wstr */
3885 *w = 0;
3886#else
3887 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 PyObject_FREE(_PyUnicode_WSTR(unicode));
3889 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 Py_FatalError("Impossible unicode object state, wstr "
3891 "and str should share memory already.");
3892 return NULL;
3893#endif
3894 }
3895 else {
3896 assert(0 && "This should never happen.");
3897 }
3898 }
3899 }
3900 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003901 *size = PyUnicode_WSTR_LENGTH(unicode);
3902 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003903}
3904
Alexander Belopolsky40018472011-02-26 01:02:56 +00003905Py_UNICODE *
3906PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003909}
3910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911
Alexander Belopolsky40018472011-02-26 01:02:56 +00003912Py_ssize_t
3913PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003914{
3915 if (!PyUnicode_Check(unicode)) {
3916 PyErr_BadArgument();
3917 goto onError;
3918 }
3919 return PyUnicode_GET_SIZE(unicode);
3920
Benjamin Peterson29060642009-01-31 22:14:21 +00003921 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003922 return -1;
3923}
3924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003925Py_ssize_t
3926PyUnicode_GetLength(PyObject *unicode)
3927{
Victor Stinner07621332012-06-16 04:53:46 +02003928 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003929 PyErr_BadArgument();
3930 return -1;
3931 }
Victor Stinner07621332012-06-16 04:53:46 +02003932 if (PyUnicode_READY(unicode) == -1)
3933 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934 return PyUnicode_GET_LENGTH(unicode);
3935}
3936
3937Py_UCS4
3938PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3939{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003940 void *data;
3941 int kind;
3942
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003943 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3944 PyErr_BadArgument();
3945 return (Py_UCS4)-1;
3946 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003947 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003948 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949 return (Py_UCS4)-1;
3950 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003951 data = PyUnicode_DATA(unicode);
3952 kind = PyUnicode_KIND(unicode);
3953 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954}
3955
3956int
3957PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3958{
3959 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003960 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 return -1;
3962 }
Victor Stinner488fa492011-12-12 00:01:39 +01003963 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003964 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003965 PyErr_SetString(PyExc_IndexError, "string index out of range");
3966 return -1;
3967 }
Victor Stinner488fa492011-12-12 00:01:39 +01003968 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003969 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003970 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3971 PyErr_SetString(PyExc_ValueError, "character out of range");
3972 return -1;
3973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3975 index, ch);
3976 return 0;
3977}
3978
Alexander Belopolsky40018472011-02-26 01:02:56 +00003979const char *
3980PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003981{
Victor Stinner42cb4622010-09-01 19:39:01 +00003982 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003983}
3984
Victor Stinner554f3f02010-06-16 23:33:54 +00003985/* create or adjust a UnicodeDecodeError */
3986static void
3987make_decode_exception(PyObject **exceptionObject,
3988 const char *encoding,
3989 const char *input, Py_ssize_t length,
3990 Py_ssize_t startpos, Py_ssize_t endpos,
3991 const char *reason)
3992{
3993 if (*exceptionObject == NULL) {
3994 *exceptionObject = PyUnicodeDecodeError_Create(
3995 encoding, input, length, startpos, endpos, reason);
3996 }
3997 else {
3998 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3999 goto onError;
4000 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4001 goto onError;
4002 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4003 goto onError;
4004 }
4005 return;
4006
4007onError:
4008 Py_DECREF(*exceptionObject);
4009 *exceptionObject = NULL;
4010}
4011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013/* error handling callback helper:
4014 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004015 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 and adjust various state variables.
4017 return 0 on success, -1 on error
4018*/
4019
Alexander Belopolsky40018472011-02-26 01:02:56 +00004020static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004021unicode_decode_call_errorhandler_wchar(
4022 const char *errors, PyObject **errorHandler,
4023 const char *encoding, const char *reason,
4024 const char **input, const char **inend, Py_ssize_t *startinpos,
4025 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4026 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004028 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029
4030 PyObject *restuple = NULL;
4031 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004032 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004033 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004034 Py_ssize_t requiredsize;
4035 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004036 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004037 wchar_t *repwstr;
4038 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004040 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4041 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004042
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004043 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 *errorHandler = PyCodec_LookupError(errors);
4045 if (*errorHandler == NULL)
4046 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004047 }
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049 make_decode_exception(exceptionObject,
4050 encoding,
4051 *input, *inend - *input,
4052 *startinpos, *endinpos,
4053 reason);
4054 if (*exceptionObject == NULL)
4055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056
4057 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4058 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004061 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004062 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 }
4064 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004066
4067 /* Copy back the bytes variables, which might have been modified by the
4068 callback */
4069 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4070 if (!inputobj)
4071 goto onError;
4072 if (!PyBytes_Check(inputobj)) {
4073 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4074 }
4075 *input = PyBytes_AS_STRING(inputobj);
4076 insize = PyBytes_GET_SIZE(inputobj);
4077 *inend = *input + insize;
4078 /* we can DECREF safely, as the exception has another reference,
4079 so the object won't go away. */
4080 Py_DECREF(inputobj);
4081
4082 if (newpos<0)
4083 newpos = insize+newpos;
4084 if (newpos<0 || newpos>insize) {
4085 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4086 goto onError;
4087 }
4088
4089 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4090 if (repwstr == NULL)
4091 goto onError;
4092 /* need more space? (at least enough for what we
4093 have+the replacement+the rest of the string (starting
4094 at the new input position), so we won't have to check space
4095 when there are no errors in the rest of the string) */
4096 requiredsize = *outpos + repwlen + insize-newpos;
4097 if (requiredsize > outsize) {
4098 if (requiredsize < 2*outsize)
4099 requiredsize = 2*outsize;
4100 if (unicode_resize(output, requiredsize) < 0)
4101 goto onError;
4102 }
4103 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4104 *outpos += repwlen;
4105
4106 *endinpos = newpos;
4107 *inptr = *input + newpos;
4108
4109 /* we made it! */
4110 Py_XDECREF(restuple);
4111 return 0;
4112
4113 onError:
4114 Py_XDECREF(restuple);
4115 return -1;
4116}
4117#endif /* HAVE_MBCS */
4118
4119static int
4120unicode_decode_call_errorhandler_writer(
4121 const char *errors, PyObject **errorHandler,
4122 const char *encoding, const char *reason,
4123 const char **input, const char **inend, Py_ssize_t *startinpos,
4124 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4125 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4126{
4127 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4128
4129 PyObject *restuple = NULL;
4130 PyObject *repunicode = NULL;
4131 Py_ssize_t insize;
4132 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004133 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004134 PyObject *inputobj = NULL;
4135
4136 if (*errorHandler == NULL) {
4137 *errorHandler = PyCodec_LookupError(errors);
4138 if (*errorHandler == NULL)
4139 goto onError;
4140 }
4141
4142 make_decode_exception(exceptionObject,
4143 encoding,
4144 *input, *inend - *input,
4145 *startinpos, *endinpos,
4146 reason);
4147 if (*exceptionObject == NULL)
4148 goto onError;
4149
4150 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4151 if (restuple == NULL)
4152 goto onError;
4153 if (!PyTuple_Check(restuple)) {
4154 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4155 goto onError;
4156 }
4157 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004158 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
4160 /* Copy back the bytes variables, which might have been modified by the
4161 callback */
4162 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4163 if (!inputobj)
4164 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004165 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004168 *input = PyBytes_AS_STRING(inputobj);
4169 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004170 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004171 /* we can DECREF safely, as the exception has another reference,
4172 so the object won't go away. */
4173 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004174
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004177 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004178 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4179 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004180 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181
Victor Stinner8f674cc2013-04-17 23:02:17 +02004182 if (PyUnicode_READY(repunicode) < 0)
4183 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004184 replen = PyUnicode_GET_LENGTH(repunicode);
4185 writer->min_length += replen;
4186 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004187 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004189 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004191 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004192 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004193
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004195 Py_XDECREF(restuple);
4196 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004200 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201}
4202
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004203/* --- UTF-7 Codec -------------------------------------------------------- */
4204
Antoine Pitrou244651a2009-05-04 18:56:13 +00004205/* See RFC2152 for details. We encode conservatively and decode liberally. */
4206
4207/* Three simple macros defining base-64. */
4208
4209/* Is c a base-64 character? */
4210
4211#define IS_BASE64(c) \
4212 (((c) >= 'A' && (c) <= 'Z') || \
4213 ((c) >= 'a' && (c) <= 'z') || \
4214 ((c) >= '0' && (c) <= '9') || \
4215 (c) == '+' || (c) == '/')
4216
4217/* given that c is a base-64 character, what is its base-64 value? */
4218
4219#define FROM_BASE64(c) \
4220 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4221 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4222 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4223 (c) == '+' ? 62 : 63)
4224
4225/* What is the base-64 character of the bottom 6 bits of n? */
4226
4227#define TO_BASE64(n) \
4228 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4229
4230/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4231 * decoded as itself. We are permissive on decoding; the only ASCII
4232 * byte not decoding to itself is the + which begins a base64
4233 * string. */
4234
4235#define DECODE_DIRECT(c) \
4236 ((c) <= 127 && (c) != '+')
4237
4238/* The UTF-7 encoder treats ASCII characters differently according to
4239 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4240 * the above). See RFC2152. This array identifies these different
4241 * sets:
4242 * 0 : "Set D"
4243 * alphanumeric and '(),-./:?
4244 * 1 : "Set O"
4245 * !"#$%&*;<=>@[]^_`{|}
4246 * 2 : "whitespace"
4247 * ht nl cr sp
4248 * 3 : special (must be base64 encoded)
4249 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4250 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251
Tim Petersced69f82003-09-16 20:30:58 +00004252static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253char utf7_category[128] = {
4254/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4255 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4256/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4257 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4258/* sp ! " # $ % & ' ( ) * + , - . / */
4259 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4260/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4261 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4262/* @ A B C D E F G H I J K L M N O */
4263 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4264/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4266/* ` a b c d e f g h i j k l m n o */
4267 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4268/* p q r s t u v w x y z { | } ~ del */
4269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004270};
4271
Antoine Pitrou244651a2009-05-04 18:56:13 +00004272/* ENCODE_DIRECT: this character should be encoded as itself. The
4273 * answer depends on whether we are encoding set O as itself, and also
4274 * on whether we are encoding whitespace as itself. RFC2152 makes it
4275 * clear that the answers to these questions vary between
4276 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004277
Antoine Pitrou244651a2009-05-04 18:56:13 +00004278#define ENCODE_DIRECT(c, directO, directWS) \
4279 ((c) < 128 && (c) > 0 && \
4280 ((utf7_category[(c)] == 0) || \
4281 (directWS && (utf7_category[(c)] == 2)) || \
4282 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283
Alexander Belopolsky40018472011-02-26 01:02:56 +00004284PyObject *
4285PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004286 Py_ssize_t size,
4287 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4290}
4291
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292/* The decoder. The only state we preserve is our read position,
4293 * i.e. how many characters we have consumed. So if we end in the
4294 * middle of a shift sequence we have to back off the read position
4295 * and the output to the beginning of the sequence, otherwise we lose
4296 * all the shift state (seen bits, number of bits seen, high
4297 * surrogate). */
4298
Alexander Belopolsky40018472011-02-26 01:02:56 +00004299PyObject *
4300PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004301 Py_ssize_t size,
4302 const char *errors,
4303 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004304{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004305 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t startinpos;
4307 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *errmsg = "";
4311 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004312 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313 unsigned int base64bits = 0;
4314 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004315 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 PyObject *errorHandler = NULL;
4317 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004319 if (size == 0) {
4320 if (consumed)
4321 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004322 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004323 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004326 _PyUnicodeWriter_Init(&writer);
4327 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328
4329 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 e = s + size;
4331
4332 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004335 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 if (inShift) { /* in a base-64 section */
4338 if (IS_BASE64(ch)) { /* consume a base-64 character */
4339 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4340 base64bits += 6;
4341 s++;
4342 if (base64bits >= 16) {
4343 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004344 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 base64bits -= 16;
4346 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004347 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 if (surrogate) {
4349 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004350 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4351 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004352 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004355 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 }
4357 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004358 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 }
4362 }
Victor Stinner551ac952011-11-29 22:58:13 +01004363 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 /* first surrogate */
4365 surrogate = outCh;
4366 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004368 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 }
4372 }
4373 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 inShift = 0;
4375 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004377 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004379 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (base64bits > 0) { /* left-over bits */
4382 if (base64bits >= 6) {
4383 /* We've seen at least one base-64 character */
4384 errmsg = "partial character in shift sequence";
4385 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004387 else {
4388 /* Some bits remain; they should be zero */
4389 if (base64buffer != 0) {
4390 errmsg = "non-zero padding bits in shift sequence";
4391 goto utf7Error;
4392 }
4393 }
4394 }
4395 if (ch != '-') {
4396 /* '-' is absorbed; other terminating
4397 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004398 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
4402 }
4403 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004404 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 s++; /* consume '+' */
4406 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004408 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 }
4411 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004413 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004415 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004419 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004420 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004448 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004452 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004462 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004463 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004464 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004465 writer.kind, writer.data, shiftOutStart);
4466 Py_XDECREF(errorHandler);
4467 Py_XDECREF(exc);
4468 _PyUnicodeWriter_Dealloc(&writer);
4469 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004470 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004471 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 }
4473 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004474 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004476 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004478 Py_XDECREF(errorHandler);
4479 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004480 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481
Benjamin Peterson29060642009-01-31 22:14:21 +00004482 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004483 Py_XDECREF(errorHandler);
4484 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004485 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486 return NULL;
4487}
4488
4489
Alexander Belopolsky40018472011-02-26 01:02:56 +00004490PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491_PyUnicode_EncodeUTF7(PyObject *str,
4492 int base64SetO,
4493 int base64WhiteSpace,
4494 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004496 int kind;
4497 void *data;
4498 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004499 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004501 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 unsigned int base64bits = 0;
4503 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504 char * out;
4505 char * start;
4506
Benjamin Petersonbac79492012-01-14 13:34:47 -05004507 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004508 return NULL;
4509 kind = PyUnicode_KIND(str);
4510 data = PyUnicode_DATA(str);
4511 len = PyUnicode_GET_LENGTH(str);
4512
4513 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004514 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004517 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004518 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004519 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520 if (v == NULL)
4521 return NULL;
4522
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004523 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004524 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004525 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 if (inShift) {
4528 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4529 /* shifting out */
4530 if (base64bits) { /* output remaining bits */
4531 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4532 base64buffer = 0;
4533 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534 }
4535 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536 /* Characters not in the BASE64 set implicitly unshift the sequence
4537 so no '-' is required, except if the character is itself a '-' */
4538 if (IS_BASE64(ch) || ch == '-') {
4539 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004541 *out++ = (char) ch;
4542 }
4543 else {
4544 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004545 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 else { /* not in a shift sequence */
4548 if (ch == '+') {
4549 *out++ = '+';
4550 *out++ = '-';
4551 }
4552 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4553 *out++ = (char) ch;
4554 }
4555 else {
4556 *out++ = '+';
4557 inShift = 1;
4558 goto encode_char;
4559 }
4560 }
4561 continue;
4562encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004563 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004564 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 /* code first surrogate */
4567 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004568 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 while (base64bits >= 6) {
4570 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4571 base64bits -= 6;
4572 }
4573 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004574 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 base64bits += 16;
4577 base64buffer = (base64buffer << 16) | ch;
4578 while (base64bits >= 6) {
4579 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4580 base64bits -= 6;
4581 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004582 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 if (base64bits)
4584 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4585 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004586 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004587 if (_PyBytes_Resize(&v, out - start) < 0)
4588 return NULL;
4589 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004590}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004591PyObject *
4592PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4593 Py_ssize_t size,
4594 int base64SetO,
4595 int base64WhiteSpace,
4596 const char *errors)
4597{
4598 PyObject *result;
4599 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4600 if (tmp == NULL)
4601 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004602 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004603 base64WhiteSpace, errors);
4604 Py_DECREF(tmp);
4605 return result;
4606}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004607
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608#undef IS_BASE64
4609#undef FROM_BASE64
4610#undef TO_BASE64
4611#undef DECODE_DIRECT
4612#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613
Guido van Rossumd57fd912000-03-10 22:53:23 +00004614/* --- UTF-8 Codec -------------------------------------------------------- */
4615
Alexander Belopolsky40018472011-02-26 01:02:56 +00004616PyObject *
4617PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004618 Py_ssize_t size,
4619 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004620{
Walter Dörwald69652032004-09-07 20:24:22 +00004621 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4622}
4623
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004624#include "stringlib/asciilib.h"
4625#include "stringlib/codecs.h"
4626#include "stringlib/undef.h"
4627
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004628#include "stringlib/ucs1lib.h"
4629#include "stringlib/codecs.h"
4630#include "stringlib/undef.h"
4631
4632#include "stringlib/ucs2lib.h"
4633#include "stringlib/codecs.h"
4634#include "stringlib/undef.h"
4635
4636#include "stringlib/ucs4lib.h"
4637#include "stringlib/codecs.h"
4638#include "stringlib/undef.h"
4639
Antoine Pitrouab868312009-01-10 15:40:25 +00004640/* Mask to quickly check whether a C 'long' contains a
4641 non-ASCII, UTF8-encoded char. */
4642#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004643# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004644#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004645# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004646#else
4647# error C 'long' size should be either 4 or 8!
4648#endif
4649
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004650static Py_ssize_t
4651ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004652{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004653 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004654 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004656 /*
4657 * Issue #17237: m68k is a bit different from most architectures in
4658 * that objects do not use "natural alignment" - for example, int and
4659 * long are only aligned at 2-byte boundaries. Therefore the assert()
4660 * won't work; also, tests have shown that skipping the "optimised
4661 * version" will even speed up m68k.
4662 */
4663#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004665 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4666 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 /* Fast path, see in STRINGLIB(utf8_decode) for
4668 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004669 /* Help allocation */
4670 const char *_p = p;
4671 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672 while (_p < aligned_end) {
4673 unsigned long value = *(const unsigned long *) _p;
4674 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004675 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 *((unsigned long *)q) = value;
4677 _p += SIZEOF_LONG;
4678 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004679 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 p = _p;
4681 while (p < end) {
4682 if ((unsigned char)*p & 0x80)
4683 break;
4684 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004686 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004689#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690 while (p < end) {
4691 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4692 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004693 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004694 /* Help allocation */
4695 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696 while (_p < aligned_end) {
4697 unsigned long value = *(unsigned long *) _p;
4698 if (value & ASCII_CHAR_MASK)
4699 break;
4700 _p += SIZEOF_LONG;
4701 }
4702 p = _p;
4703 if (_p == end)
4704 break;
4705 }
4706 if ((unsigned char)*p & 0x80)
4707 break;
4708 ++p;
4709 }
4710 memcpy(dest, start, p - start);
4711 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004712}
Antoine Pitrouab868312009-01-10 15:40:25 +00004713
Victor Stinner785938e2011-12-11 20:09:03 +01004714PyObject *
4715PyUnicode_DecodeUTF8Stateful(const char *s,
4716 Py_ssize_t size,
4717 const char *errors,
4718 Py_ssize_t *consumed)
4719{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004720 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004721 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004722 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723
4724 Py_ssize_t startinpos;
4725 Py_ssize_t endinpos;
4726 const char *errmsg = "";
4727 PyObject *errorHandler = NULL;
4728 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004729
4730 if (size == 0) {
4731 if (consumed)
4732 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004733 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004734 }
4735
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004736 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4737 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004738 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 *consumed = 1;
4740 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004741 }
4742
Victor Stinner8f674cc2013-04-17 23:02:17 +02004743 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004744 writer.min_length = size;
4745 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004746 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004747
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004748 writer.pos = ascii_decode(s, end, writer.data);
4749 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 while (s < end) {
4751 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004752 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 if (PyUnicode_IS_ASCII(writer.buffer))
4755 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004756 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004757 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004759 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760 } else {
4761 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 }
4764
4765 switch (ch) {
4766 case 0:
4767 if (s == end || consumed)
4768 goto End;
4769 errmsg = "unexpected end of data";
4770 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004771 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 break;
4773 case 1:
4774 errmsg = "invalid start byte";
4775 startinpos = s - starts;
4776 endinpos = startinpos + 1;
4777 break;
4778 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004779 case 3:
4780 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004781 errmsg = "invalid continuation byte";
4782 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004783 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784 break;
4785 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004786 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004787 goto onError;
4788 continue;
4789 }
4790
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004791 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 errors, &errorHandler,
4793 "utf-8", errmsg,
4794 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004795 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004797 }
4798
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 if (consumed)
4801 *consumed = s - starts;
4802
4803 Py_XDECREF(errorHandler);
4804 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004805 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806
4807onError:
4808 Py_XDECREF(errorHandler);
4809 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004810 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004812}
4813
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004814#ifdef __APPLE__
4815
4816/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004817 used to decode the command line arguments on Mac OS X.
4818
4819 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004820 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004821
4822wchar_t*
4823_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4824{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826 wchar_t *unicode;
4827 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004828
4829 /* Note: size will always be longer than the resulting Unicode
4830 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004831 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004833 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 if (!unicode)
4835 return NULL;
4836
4837 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 if (ch > 0xFF) {
4848#if SIZEOF_WCHAR_T == 4
4849 assert(0);
4850#else
4851 assert(Py_UNICODE_IS_SURROGATE(ch));
4852 /* compute and append the two surrogates: */
4853 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4854 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4855#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004856 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004857 else {
4858 if (!ch && s == e)
4859 break;
4860 /* surrogateescape */
4861 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4862 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004863 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 return unicode;
4866}
4867
4868#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004870/* Primary internal function which creates utf8 encoded bytes objects.
4871
4872 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004873 and allocate exactly as much space needed at the end. Else allocate the
4874 maximum possible needed (4 result bytes per Unicode character), and return
4875 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004876*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004877PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004878_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879{
Victor Stinner6099a032011-12-18 14:22:26 +01004880 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881 void *data;
4882 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884 if (!PyUnicode_Check(unicode)) {
4885 PyErr_BadArgument();
4886 return NULL;
4887 }
4888
4889 if (PyUnicode_READY(unicode) == -1)
4890 return NULL;
4891
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004892 if (PyUnicode_UTF8(unicode))
4893 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4894 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004895
4896 kind = PyUnicode_KIND(unicode);
4897 data = PyUnicode_DATA(unicode);
4898 size = PyUnicode_GET_LENGTH(unicode);
4899
Benjamin Petersonead6b532011-12-20 17:23:42 -06004900 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004901 default:
4902 assert(0);
4903 case PyUnicode_1BYTE_KIND:
4904 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4905 assert(!PyUnicode_IS_ASCII(unicode));
4906 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4907 case PyUnicode_2BYTE_KIND:
4908 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4909 case PyUnicode_4BYTE_KIND:
4910 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004911 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004912}
4913
Alexander Belopolsky40018472011-02-26 01:02:56 +00004914PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004915PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4916 Py_ssize_t size,
4917 const char *errors)
4918{
4919 PyObject *v, *unicode;
4920
4921 unicode = PyUnicode_FromUnicode(s, size);
4922 if (unicode == NULL)
4923 return NULL;
4924 v = _PyUnicode_AsUTF8String(unicode, errors);
4925 Py_DECREF(unicode);
4926 return v;
4927}
4928
4929PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004930PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004932 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933}
4934
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935/* --- UTF-32 Codec ------------------------------------------------------- */
4936
4937PyObject *
4938PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004939 Py_ssize_t size,
4940 const char *errors,
4941 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942{
4943 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4944}
4945
4946PyObject *
4947PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004948 Py_ssize_t size,
4949 const char *errors,
4950 int *byteorder,
4951 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004952{
4953 const char *starts = s;
4954 Py_ssize_t startinpos;
4955 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004956 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004957 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004958 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004959 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961 PyObject *errorHandler = NULL;
4962 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004963
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 q = (unsigned char *)s;
4965 e = q + size;
4966
4967 if (byteorder)
4968 bo = *byteorder;
4969
4970 /* Check for BOM marks (U+FEFF) in the input and adjust current
4971 byte order setting accordingly. In native mode, the leading BOM
4972 mark is skipped, in all other modes, it is copied to the output
4973 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004974 if (bo == 0 && size >= 4) {
4975 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4976 if (bom == 0x0000FEFF) {
4977 bo = -1;
4978 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004980 else if (bom == 0xFFFE0000) {
4981 bo = 1;
4982 q += 4;
4983 }
4984 if (byteorder)
4985 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986 }
4987
Victor Stinnere64322e2012-10-30 23:12:47 +01004988 if (q == e) {
4989 if (consumed)
4990 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004991 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992 }
4993
Victor Stinnere64322e2012-10-30 23:12:47 +01004994#ifdef WORDS_BIGENDIAN
4995 le = bo < 0;
4996#else
4997 le = bo <= 0;
4998#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004999 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005000
Victor Stinner8f674cc2013-04-17 23:02:17 +02005001 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005002 writer.min_length = (e - q + 3) / 4;
5003 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005004 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005005
Victor Stinnere64322e2012-10-30 23:12:47 +01005006 while (1) {
5007 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005009
Victor Stinnere64322e2012-10-30 23:12:47 +01005010 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005011 enum PyUnicode_Kind kind = writer.kind;
5012 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005013 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005014 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005015 if (le) {
5016 do {
5017 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5018 if (ch > maxch)
5019 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005020 if (kind != PyUnicode_1BYTE_KIND &&
5021 Py_UNICODE_IS_SURROGATE(ch))
5022 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005023 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 q += 4;
5025 } while (q <= last);
5026 }
5027 else {
5028 do {
5029 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5030 if (ch > maxch)
5031 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005032 if (kind != PyUnicode_1BYTE_KIND &&
5033 Py_UNICODE_IS_SURROGATE(ch))
5034 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005036 q += 4;
5037 } while (q <= last);
5038 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005039 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005040 }
5041
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005042 if (Py_UNICODE_IS_SURROGATE(ch)) {
5043 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5044 startinpos = ((const char *)q) - starts;
5045 endinpos = startinpos + 4;
5046 }
5047 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005050 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005052 startinpos = ((const char *)q) - starts;
5053 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005054 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005055 else {
5056 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005057 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005058 goto onError;
5059 q += 4;
5060 continue;
5061 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005063 startinpos = ((const char *)q) - starts;
5064 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005066
5067 /* The remaining input chars are ignored if the callback
5068 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005069 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005070 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005071 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005073 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005074 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 }
5076
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080 Py_XDECREF(errorHandler);
5081 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005082 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005085 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 Py_XDECREF(errorHandler);
5087 Py_XDECREF(exc);
5088 return NULL;
5089}
5090
5091PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005092_PyUnicode_EncodeUTF32(PyObject *str,
5093 const char *errors,
5094 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005096 int kind;
5097 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005099 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005100 unsigned char *p;
5101 Py_ssize_t nsize, i;
5102 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005103#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005106 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005108 const char *encoding;
5109 PyObject *errorHandler = NULL;
5110 PyObject *exc = NULL;
5111 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112
Serhiy Storchaka30793282014-01-04 22:44:01 +02005113#define STORECHAR(CH) \
5114 do { \
5115 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5116 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5117 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5118 p[iorder[0]] = (CH) & 0xff; \
5119 p += 4; \
5120 } while(0)
5121
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005122 if (!PyUnicode_Check(str)) {
5123 PyErr_BadArgument();
5124 return NULL;
5125 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005126 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005127 return NULL;
5128 kind = PyUnicode_KIND(str);
5129 data = PyUnicode_DATA(str);
5130 len = PyUnicode_GET_LENGTH(str);
5131
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005132 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005133 if (nsize > PY_SSIZE_T_MAX / 4)
5134 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005135 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136 if (v == NULL)
5137 return NULL;
5138
Serhiy Storchaka30793282014-01-04 22:44:01 +02005139 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005140 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005142 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005143 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144
Serhiy Storchaka30793282014-01-04 22:44:01 +02005145 if (byteorder == -1) {
5146 /* force LE */
5147 iorder[0] = 0;
5148 iorder[1] = 1;
5149 iorder[2] = 2;
5150 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005151 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005152 }
5153 else if (byteorder == 1) {
5154 /* force BE */
5155 iorder[0] = 3;
5156 iorder[1] = 2;
5157 iorder[2] = 1;
5158 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005159 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005160 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005161 else
5162 encoding = "utf-32";
5163
5164 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005165 for (i = 0; i < len; i++)
5166 STORECHAR(PyUnicode_READ(kind, data, i));
5167 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005168 }
5169
Serhiy Storchaka30793282014-01-04 22:44:01 +02005170 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005171 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005172 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5173 i++;
5174 assert(ch <= MAX_UNICODE);
5175 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5176 STORECHAR(ch);
5177 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005178 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005179
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005180 rep = unicode_encode_call_errorhandler(
5181 errors, &errorHandler,
5182 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005183 str, &exc, i-1, i, &i);
5184
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005185 if (!rep)
5186 goto error;
5187
5188 if (PyBytes_Check(rep)) {
5189 repsize = PyBytes_GET_SIZE(rep);
5190 if (repsize & 3) {
5191 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005192 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 "surrogates not allowed");
5194 goto error;
5195 }
5196 moreunits = repsize / 4;
5197 }
5198 else {
5199 assert(PyUnicode_Check(rep));
5200 if (PyUnicode_READY(rep) < 0)
5201 goto error;
5202 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5203 if (!PyUnicode_IS_ASCII(rep)) {
5204 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005205 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005206 "surrogates not allowed");
5207 goto error;
5208 }
5209 }
5210
5211 /* four bytes are reserved for each surrogate */
5212 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005213 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005214 Py_ssize_t morebytes = 4 * (moreunits - 1);
5215 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5216 /* integer overflow */
5217 PyErr_NoMemory();
5218 goto error;
5219 }
5220 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5221 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005222 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005223 }
5224
5225 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005226 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5227 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005228 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005229 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005230 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005231 repdata = PyUnicode_1BYTE_DATA(rep);
5232 while (repsize--) {
5233 Py_UCS4 ch = *repdata++;
5234 STORECHAR(ch);
5235 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005236 }
5237
5238 Py_CLEAR(rep);
5239 }
5240
5241 /* Cut back to size actually needed. This is necessary for, for example,
5242 encoding of a string containing isolated surrogates and the 'ignore'
5243 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005244 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005245 if (nsize != PyBytes_GET_SIZE(v))
5246 _PyBytes_Resize(&v, nsize);
5247 Py_XDECREF(errorHandler);
5248 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005249 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005250 error:
5251 Py_XDECREF(rep);
5252 Py_XDECREF(errorHandler);
5253 Py_XDECREF(exc);
5254 Py_XDECREF(v);
5255 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005256#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257}
5258
Alexander Belopolsky40018472011-02-26 01:02:56 +00005259PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005260PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5261 Py_ssize_t size,
5262 const char *errors,
5263 int byteorder)
5264{
5265 PyObject *result;
5266 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5267 if (tmp == NULL)
5268 return NULL;
5269 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5270 Py_DECREF(tmp);
5271 return result;
5272}
5273
5274PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005275PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
Victor Stinnerb960b342011-11-20 19:12:52 +01005277 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005278}
5279
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280/* --- UTF-16 Codec ------------------------------------------------------- */
5281
Tim Peters772747b2001-08-09 22:21:55 +00005282PyObject *
5283PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005284 Py_ssize_t size,
5285 const char *errors,
5286 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005287{
Walter Dörwald69652032004-09-07 20:24:22 +00005288 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5289}
5290
5291PyObject *
5292PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005293 Py_ssize_t size,
5294 const char *errors,
5295 int *byteorder,
5296 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005297{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005298 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005299 Py_ssize_t startinpos;
5300 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005302 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005303 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005304 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005305 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005306 PyObject *errorHandler = NULL;
5307 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005308 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005309
Tim Peters772747b2001-08-09 22:21:55 +00005310 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005311 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005312
5313 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005314 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005315
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005316 /* Check for BOM marks (U+FEFF) in the input and adjust current
5317 byte order setting accordingly. In native mode, the leading BOM
5318 mark is skipped, in all other modes, it is copied to the output
5319 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005320 if (bo == 0 && size >= 2) {
5321 const Py_UCS4 bom = (q[1] << 8) | q[0];
5322 if (bom == 0xFEFF) {
5323 q += 2;
5324 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 else if (bom == 0xFFFE) {
5327 q += 2;
5328 bo = 1;
5329 }
5330 if (byteorder)
5331 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005332 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005333
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 if (q == e) {
5335 if (consumed)
5336 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005337 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005338 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005339
Christian Heimes743e0cd2012-10-17 23:52:17 +02005340#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005341 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005342 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005343#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005344 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005345 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005346#endif
Tim Peters772747b2001-08-09 22:21:55 +00005347
Antoine Pitrou63065d72012-05-15 23:48:04 +02005348 /* Note: size will always be longer than the resulting Unicode
5349 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005350 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005351 writer.min_length = (e - q + 1) / 2;
5352 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005354
Antoine Pitrou63065d72012-05-15 23:48:04 +02005355 while (1) {
5356 Py_UCS4 ch = 0;
5357 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005358 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005359 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005360 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005361 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 native_ordering);
5364 else
5365 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 native_ordering);
5368 } else if (kind == PyUnicode_2BYTE_KIND) {
5369 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005370 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 native_ordering);
5372 } else {
5373 assert(kind == PyUnicode_4BYTE_KIND);
5374 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005375 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005376 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005377 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005378 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005379
Antoine Pitrou63065d72012-05-15 23:48:04 +02005380 switch (ch)
5381 {
5382 case 0:
5383 /* remaining byte at the end? (size should be even) */
5384 if (q == e || consumed)
5385 goto End;
5386 errmsg = "truncated data";
5387 startinpos = ((const char *)q) - starts;
5388 endinpos = ((const char *)e) - starts;
5389 break;
5390 /* The remaining input chars are ignored if the callback
5391 chooses to skip the input */
5392 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005393 q -= 2;
5394 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005395 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005396 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005397 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005398 endinpos = ((const char *)e) - starts;
5399 break;
5400 case 2:
5401 errmsg = "illegal encoding";
5402 startinpos = ((const char *)q) - 2 - starts;
5403 endinpos = startinpos + 2;
5404 break;
5405 case 3:
5406 errmsg = "illegal UTF-16 surrogate";
5407 startinpos = ((const char *)q) - 4 - starts;
5408 endinpos = startinpos + 2;
5409 break;
5410 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005411 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005412 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 continue;
5414 }
5415
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005416 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005417 errors,
5418 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005419 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005420 &starts,
5421 (const char **)&e,
5422 &startinpos,
5423 &endinpos,
5424 &exc,
5425 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005426 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005427 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 }
5429
Antoine Pitrou63065d72012-05-15 23:48:04 +02005430End:
Walter Dörwald69652032004-09-07 20:24:22 +00005431 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005433
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 Py_XDECREF(errorHandler);
5435 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005436 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005439 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005440 Py_XDECREF(errorHandler);
5441 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442 return NULL;
5443}
5444
Tim Peters772747b2001-08-09 22:21:55 +00005445PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005446_PyUnicode_EncodeUTF16(PyObject *str,
5447 const char *errors,
5448 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005449{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005450 enum PyUnicode_Kind kind;
5451 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005452 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005453 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005454 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005455 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005456#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005457 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005458#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005460#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005461 const char *encoding;
5462 Py_ssize_t nsize, pos;
5463 PyObject *errorHandler = NULL;
5464 PyObject *exc = NULL;
5465 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005466
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005467 if (!PyUnicode_Check(str)) {
5468 PyErr_BadArgument();
5469 return NULL;
5470 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005471 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005472 return NULL;
5473 kind = PyUnicode_KIND(str);
5474 data = PyUnicode_DATA(str);
5475 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005476
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005477 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005478 if (kind == PyUnicode_4BYTE_KIND) {
5479 const Py_UCS4 *in = (const Py_UCS4 *)data;
5480 const Py_UCS4 *end = in + len;
5481 while (in < end)
5482 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005483 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005484 }
5485 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005486 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 nsize = len + pairs + (byteorder == 0);
5488 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489 if (v == NULL)
5490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005492 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005493 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005494 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005496 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005497 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005498 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005499
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005500 if (kind == PyUnicode_1BYTE_KIND) {
5501 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5502 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005503 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005504
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005505 if (byteorder < 0)
5506 encoding = "utf-16-le";
5507 else if (byteorder > 0)
5508 encoding = "utf-16-be";
5509 else
5510 encoding = "utf-16";
5511
5512 pos = 0;
5513 while (pos < len) {
5514 Py_ssize_t repsize, moreunits;
5515
5516 if (kind == PyUnicode_2BYTE_KIND) {
5517 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5518 &out, native_ordering);
5519 }
5520 else {
5521 assert(kind == PyUnicode_4BYTE_KIND);
5522 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5523 &out, native_ordering);
5524 }
5525 if (pos == len)
5526 break;
5527
5528 rep = unicode_encode_call_errorhandler(
5529 errors, &errorHandler,
5530 encoding, "surrogates not allowed",
5531 str, &exc, pos, pos + 1, &pos);
5532 if (!rep)
5533 goto error;
5534
5535 if (PyBytes_Check(rep)) {
5536 repsize = PyBytes_GET_SIZE(rep);
5537 if (repsize & 1) {
5538 raise_encode_exception(&exc, encoding,
5539 str, pos - 1, pos,
5540 "surrogates not allowed");
5541 goto error;
5542 }
5543 moreunits = repsize / 2;
5544 }
5545 else {
5546 assert(PyUnicode_Check(rep));
5547 if (PyUnicode_READY(rep) < 0)
5548 goto error;
5549 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5550 if (!PyUnicode_IS_ASCII(rep)) {
5551 raise_encode_exception(&exc, encoding,
5552 str, pos - 1, pos,
5553 "surrogates not allowed");
5554 goto error;
5555 }
5556 }
5557
5558 /* two bytes are reserved for each surrogate */
5559 if (moreunits > 1) {
5560 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5561 Py_ssize_t morebytes = 2 * (moreunits - 1);
5562 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5563 /* integer overflow */
5564 PyErr_NoMemory();
5565 goto error;
5566 }
5567 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5568 goto error;
5569 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5570 }
5571
5572 if (PyBytes_Check(rep)) {
5573 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5574 out += moreunits;
5575 } else /* rep is unicode */ {
5576 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5577 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5578 &out, native_ordering);
5579 }
5580
5581 Py_CLEAR(rep);
5582 }
5583
5584 /* Cut back to size actually needed. This is necessary for, for example,
5585 encoding of a string containing isolated surrogates and the 'ignore' handler
5586 is used. */
5587 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5588 if (nsize != PyBytes_GET_SIZE(v))
5589 _PyBytes_Resize(&v, nsize);
5590 Py_XDECREF(errorHandler);
5591 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005592 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005593 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005594 error:
5595 Py_XDECREF(rep);
5596 Py_XDECREF(errorHandler);
5597 Py_XDECREF(exc);
5598 Py_XDECREF(v);
5599 return NULL;
5600#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601}
5602
Alexander Belopolsky40018472011-02-26 01:02:56 +00005603PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005604PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5605 Py_ssize_t size,
5606 const char *errors,
5607 int byteorder)
5608{
5609 PyObject *result;
5610 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5611 if (tmp == NULL)
5612 return NULL;
5613 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5614 Py_DECREF(tmp);
5615 return result;
5616}
5617
5618PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005619PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005621 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622}
5623
5624/* --- Unicode Escape Codec ----------------------------------------------- */
5625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005626/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5627 if all the escapes in the string make it still a valid ASCII string.
5628 Returns -1 if any escapes were found which cause the string to
5629 pop out of ASCII range. Otherwise returns the length of the
5630 required buffer to hold the string.
5631 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005632static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005633length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5634{
5635 const unsigned char *p = (const unsigned char *)s;
5636 const unsigned char *end = p + size;
5637 Py_ssize_t length = 0;
5638
5639 if (size < 0)
5640 return -1;
5641
5642 for (; p < end; ++p) {
5643 if (*p > 127) {
5644 /* Non-ASCII */
5645 return -1;
5646 }
5647 else if (*p != '\\') {
5648 /* Normal character */
5649 ++length;
5650 }
5651 else {
5652 /* Backslash-escape, check next char */
5653 ++p;
5654 /* Escape sequence reaches till end of string or
5655 non-ASCII follow-up. */
5656 if (p >= end || *p > 127)
5657 return -1;
5658 switch (*p) {
5659 case '\n':
5660 /* backslash + \n result in zero characters */
5661 break;
5662 case '\\': case '\'': case '\"':
5663 case 'b': case 'f': case 't':
5664 case 'n': case 'r': case 'v': case 'a':
5665 ++length;
5666 break;
5667 case '0': case '1': case '2': case '3':
5668 case '4': case '5': case '6': case '7':
5669 case 'x': case 'u': case 'U': case 'N':
5670 /* these do not guarantee ASCII characters */
5671 return -1;
5672 default:
5673 /* count the backslash + the other character */
5674 length += 2;
5675 }
5676 }
5677 }
5678 return length;
5679}
5680
Fredrik Lundh06d12682001-01-24 07:59:11 +00005681static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005682
Alexander Belopolsky40018472011-02-26 01:02:56 +00005683PyObject *
5684PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005685 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005686 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005688 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005689 Py_ssize_t startinpos;
5690 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005693 char* message;
5694 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005695 PyObject *errorHandler = NULL;
5696 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005697 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005698
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005699 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005700 if (len == 0)
5701 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005702
5703 /* After length_of_escaped_ascii_string() there are two alternatives,
5704 either the string is pure ASCII with named escapes like \n, etc.
5705 and we determined it's exact size (common case)
5706 or it contains \x, \u, ... escape sequences. then we create a
5707 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005708 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005709 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005710 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711 }
5712 else {
5713 /* Escaped strings will always be longer than the resulting
5714 Unicode string, so we start with size here and then reduce the
5715 length after conversion to the true value.
5716 (but if the error callback returns a long replacement string
5717 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005718 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005719 }
5720
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005722 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005724
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 while (s < end) {
5726 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005727 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005728 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729
5730 /* Non-escape characters are interpreted as Unicode ordinals */
5731 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005732 x = (unsigned char)*s;
5733 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005734 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005735 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 continue;
5737 }
5738
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005739 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 /* \ - Escapes */
5741 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005742 c = *s++;
5743 if (s > end)
5744 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005745
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005746 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005749#define WRITECHAR(ch) \
5750 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005751 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005752 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005753 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005754
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005756 case '\\': WRITECHAR('\\'); break;
5757 case '\'': WRITECHAR('\''); break;
5758 case '\"': WRITECHAR('\"'); break;
5759 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005761 case 'f': WRITECHAR('\014'); break;
5762 case 't': WRITECHAR('\t'); break;
5763 case 'n': WRITECHAR('\n'); break;
5764 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005765 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005766 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005768 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005769
Benjamin Peterson29060642009-01-31 22:14:21 +00005770 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771 case '0': case '1': case '2': case '3':
5772 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005773 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005774 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005775 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005776 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005777 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005779 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 break;
5781
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 /* hex escapes */
5783 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005785 digits = 2;
5786 message = "truncated \\xXX escape";
5787 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005788
Benjamin Peterson29060642009-01-31 22:14:21 +00005789 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005791 digits = 4;
5792 message = "truncated \\uXXXX escape";
5793 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794
Benjamin Peterson29060642009-01-31 22:14:21 +00005795 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005796 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 digits = 8;
5798 message = "truncated \\UXXXXXXXX escape";
5799 hexescape:
5800 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005801 if (end - s < digits) {
5802 /* count only hex digits */
5803 for (; s < end; ++s) {
5804 c = (unsigned char)*s;
5805 if (!Py_ISXDIGIT(c))
5806 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005807 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005808 goto error;
5809 }
5810 for (; digits--; ++s) {
5811 c = (unsigned char)*s;
5812 if (!Py_ISXDIGIT(c))
5813 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005814 chr = (chr<<4) & ~0xF;
5815 if (c >= '0' && c <= '9')
5816 chr += c - '0';
5817 else if (c >= 'a' && c <= 'f')
5818 chr += 10 + c - 'a';
5819 else
5820 chr += 10 + c - 'A';
5821 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005822 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005823 /* _decoding_error will have already written into the
5824 target buffer. */
5825 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005826 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005827 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005828 message = "illegal Unicode character";
5829 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005831 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005832 break;
5833
Benjamin Peterson29060642009-01-31 22:14:21 +00005834 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005835 case 'N':
5836 message = "malformed \\N character escape";
5837 if (ucnhash_CAPI == NULL) {
5838 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005839 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5840 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005841 if (ucnhash_CAPI == NULL)
5842 goto ucnhashError;
5843 }
5844 if (*s == '{') {
5845 const char *start = s+1;
5846 /* look for the closing brace */
5847 while (*s != '}' && s < end)
5848 s++;
5849 if (s > start && s < end && *s == '}') {
5850 /* found a name. look it up in the unicode database */
5851 message = "unknown Unicode character name";
5852 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005853 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005854 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005855 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005856 goto store;
5857 }
5858 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005859 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860
5861 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005862 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 message = "\\ at end of string";
5864 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005865 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005866 }
5867 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005868 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005869 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005871 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005873 continue;
5874
5875 error:
5876 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005877 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005878 errors, &errorHandler,
5879 "unicodeescape", message,
5880 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005881 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005882 goto onError;
5883 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005885#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005887 Py_XDECREF(errorHandler);
5888 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005889 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005890
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005892 PyErr_SetString(
5893 PyExc_UnicodeError,
5894 "\\N escapes not supported (can't load unicodedata module)"
5895 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005896 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005897 Py_XDECREF(errorHandler);
5898 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005899 return NULL;
5900
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005902 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 Py_XDECREF(errorHandler);
5904 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 return NULL;
5906}
5907
5908/* Return a Unicode-Escape string version of the Unicode object.
5909
5910 If quotes is true, the string is enclosed in u"" or u'' quotes as
5911 appropriate.
5912
5913*/
5914
Alexander Belopolsky40018472011-02-26 01:02:56 +00005915PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005918 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005919 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 int kind;
5922 void *data;
5923 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924
Ezio Melottie7f90372012-10-05 03:33:31 +03005925 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005926 escape.
5927
Ezio Melottie7f90372012-10-05 03:33:31 +03005928 For UCS1 strings it's '\xxx', 4 bytes per source character.
5929 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5930 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005931 */
5932
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005933 if (!PyUnicode_Check(unicode)) {
5934 PyErr_BadArgument();
5935 return NULL;
5936 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005937 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005938 return NULL;
5939 len = PyUnicode_GET_LENGTH(unicode);
5940 kind = PyUnicode_KIND(unicode);
5941 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005942 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005943 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5944 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5945 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5946 }
5947
5948 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005949 return PyBytes_FromStringAndSize(NULL, 0);
5950
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005953
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005954 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005956 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958 if (repr == NULL)
5959 return NULL;
5960
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005961 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005963 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005964 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005965
Walter Dörwald79e913e2007-05-12 11:08:06 +00005966 /* Escape backslashes */
5967 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 *p++ = '\\';
5969 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005970 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005971 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005972
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005973 /* Map 21-bit characters to '\U00xxxxxx' */
5974 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005975 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005976 *p++ = '\\';
5977 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005978 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5979 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5980 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5981 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5982 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5983 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5984 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5985 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005987 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005988
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005990 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 *p++ = '\\';
5992 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005993 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5994 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5995 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5996 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005998
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005999 /* Map special whitespace to '\t', \n', '\r' */
6000 else if (ch == '\t') {
6001 *p++ = '\\';
6002 *p++ = 't';
6003 }
6004 else if (ch == '\n') {
6005 *p++ = '\\';
6006 *p++ = 'n';
6007 }
6008 else if (ch == '\r') {
6009 *p++ = '\\';
6010 *p++ = 'r';
6011 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006012
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006013 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006014 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006016 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006017 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6018 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006019 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006020
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021 /* Copy everything else as-is */
6022 else
6023 *p++ = (char) ch;
6024 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006026 assert(p - PyBytes_AS_STRING(repr) > 0);
6027 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6028 return NULL;
6029 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030}
6031
Alexander Belopolsky40018472011-02-26 01:02:56 +00006032PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006033PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6034 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 PyObject *result;
6037 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6038 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006040 result = PyUnicode_AsUnicodeEscapeString(tmp);
6041 Py_DECREF(tmp);
6042 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043}
6044
6045/* --- Raw Unicode Escape Codec ------------------------------------------- */
6046
Alexander Belopolsky40018472011-02-26 01:02:56 +00006047PyObject *
6048PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006049 Py_ssize_t size,
6050 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006052 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006053 Py_ssize_t startinpos;
6054 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006055 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056 const char *end;
6057 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006058 PyObject *errorHandler = NULL;
6059 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006060
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006061 if (size == 0)
6062 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006063
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 /* Escaped strings will always be longer than the resulting
6065 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006066 length after conversion to the true value. (But decoding error
6067 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006068 _PyUnicodeWriter_Init(&writer);
6069 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006070
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071 end = s + size;
6072 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 unsigned char c;
6074 Py_UCS4 x;
6075 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006076 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 /* Non-escape characters are interpreted as Unicode ordinals */
6079 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006080 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006081 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006082 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006084 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 startinpos = s-starts;
6086
6087 /* \u-escapes are only interpreted iff the number of leading
6088 backslashes if odd */
6089 bs = s;
6090 for (;s < end;) {
6091 if (*s != '\\')
6092 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006093 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006094 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006095 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006096 }
6097 if (((s - bs) & 1) == 0 ||
6098 s >= end ||
6099 (*s != 'u' && *s != 'U')) {
6100 continue;
6101 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006102 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 count = *s=='u' ? 4 : 8;
6104 s++;
6105
6106 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 for (x = 0, i = 0; i < count; ++i, ++s) {
6108 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006109 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006111 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 errors, &errorHandler,
6113 "rawunicodeescape", "truncated \\uXXXX",
6114 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006115 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 goto onError;
6117 goto nextByte;
6118 }
6119 x = (x<<4) & ~0xF;
6120 if (c >= '0' && c <= '9')
6121 x += c - '0';
6122 else if (c >= 'a' && c <= 'f')
6123 x += 10 + c - 'a';
6124 else
6125 x += 10 + c - 'A';
6126 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006127 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006128 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006129 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006130 }
6131 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006132 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006133 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006134 errors, &errorHandler,
6135 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006136 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006137 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006139 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 nextByte:
6141 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006143 Py_XDECREF(errorHandler);
6144 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006145 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006146
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006148 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006149 Py_XDECREF(errorHandler);
6150 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 return NULL;
6152}
6153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154
Alexander Belopolsky40018472011-02-26 01:02:56 +00006155PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006158 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 char *p;
6160 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006161 Py_ssize_t expandsize, pos;
6162 int kind;
6163 void *data;
6164 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166 if (!PyUnicode_Check(unicode)) {
6167 PyErr_BadArgument();
6168 return NULL;
6169 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006170 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 return NULL;
6172 kind = PyUnicode_KIND(unicode);
6173 data = PyUnicode_DATA(unicode);
6174 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006175 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6176 bytes, and 1 byte characters 4. */
6177 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006178
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006181
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006182 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183 if (repr == NULL)
6184 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006185 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006186 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006188 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 for (pos = 0; pos < len; pos++) {
6190 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 /* Map 32-bit characters to '\Uxxxxxxxx' */
6192 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006193 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006194 *p++ = '\\';
6195 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006196 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6197 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6198 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6199 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6200 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6201 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6202 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6203 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006204 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207 *p++ = '\\';
6208 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006209 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6211 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6212 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006214 /* Copy everything else as-is */
6215 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 *p++ = (char) ch;
6217 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006218
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219 assert(p > q);
6220 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006221 return NULL;
6222 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006223}
6224
Alexander Belopolsky40018472011-02-26 01:02:56 +00006225PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6227 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229 PyObject *result;
6230 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6231 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006232 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006233 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6234 Py_DECREF(tmp);
6235 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236}
6237
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006238/* --- Unicode Internal Codec ------------------------------------------- */
6239
Alexander Belopolsky40018472011-02-26 01:02:56 +00006240PyObject *
6241_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006242 Py_ssize_t size,
6243 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006244{
6245 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006246 Py_ssize_t startinpos;
6247 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006248 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006249 const char *end;
6250 const char *reason;
6251 PyObject *errorHandler = NULL;
6252 PyObject *exc = NULL;
6253
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006254 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006255 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006256 1))
6257 return NULL;
6258
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006259 if (size == 0)
6260 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006261
Victor Stinner8f674cc2013-04-17 23:02:17 +02006262 _PyUnicodeWriter_Init(&writer);
6263 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6264 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006266 }
6267 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006268
Victor Stinner8f674cc2013-04-17 23:02:17 +02006269 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006271 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006272 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006273 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006274 endinpos = end-starts;
6275 reason = "truncated input";
6276 goto error;
6277 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006278 /* We copy the raw representation one byte at a time because the
6279 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006280 ((char *) &uch)[0] = s[0];
6281 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006282#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006283 ((char *) &uch)[2] = s[2];
6284 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006285#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006286 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006287#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006288 /* We have to sanity check the raw data, otherwise doom looms for
6289 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006290 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006291 endinpos = s - starts + Py_UNICODE_SIZE;
6292 reason = "illegal code point (> 0x10FFFF)";
6293 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006294 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006296 s += Py_UNICODE_SIZE;
6297#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006298 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006299 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006300 Py_UNICODE uch2;
6301 ((char *) &uch2)[0] = s[0];
6302 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006303 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006304 {
Victor Stinner551ac952011-11-29 22:58:13 +01006305 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006306 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006307 }
6308 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006309#endif
6310
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006311 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006313 continue;
6314
6315 error:
6316 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006317 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006318 errors, &errorHandler,
6319 "unicode_internal", reason,
6320 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006321 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006322 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323 }
6324
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325 Py_XDECREF(errorHandler);
6326 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006327 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328
Benjamin Peterson29060642009-01-31 22:14:21 +00006329 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006330 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331 Py_XDECREF(errorHandler);
6332 Py_XDECREF(exc);
6333 return NULL;
6334}
6335
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336/* --- Latin-1 Codec ------------------------------------------------------ */
6337
Alexander Belopolsky40018472011-02-26 01:02:56 +00006338PyObject *
6339PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006340 Py_ssize_t size,
6341 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006344 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345}
6346
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006347/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006348static void
6349make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006350 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006351 PyObject *unicode,
6352 Py_ssize_t startpos, Py_ssize_t endpos,
6353 const char *reason)
6354{
6355 if (*exceptionObject == NULL) {
6356 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006358 encoding, unicode, startpos, endpos, reason);
6359 }
6360 else {
6361 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6362 goto onError;
6363 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6364 goto onError;
6365 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6366 goto onError;
6367 return;
6368 onError:
6369 Py_DECREF(*exceptionObject);
6370 *exceptionObject = NULL;
6371 }
6372}
6373
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006374/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006375static void
6376raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006377 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006378 PyObject *unicode,
6379 Py_ssize_t startpos, Py_ssize_t endpos,
6380 const char *reason)
6381{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006382 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006383 encoding, unicode, startpos, endpos, reason);
6384 if (*exceptionObject != NULL)
6385 PyCodec_StrictErrors(*exceptionObject);
6386}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006387
6388/* error handling callback helper:
6389 build arguments, call the callback and check the arguments,
6390 put the result into newpos and return the replacement string, which
6391 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006392static PyObject *
6393unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006394 PyObject **errorHandler,
6395 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006397 Py_ssize_t startpos, Py_ssize_t endpos,
6398 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006399{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006400 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006401 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402 PyObject *restuple;
6403 PyObject *resunicode;
6404
6405 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 }
6410
Benjamin Petersonbac79492012-01-14 13:34:47 -05006411 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006412 return NULL;
6413 len = PyUnicode_GET_LENGTH(unicode);
6414
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006415 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006416 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006418 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419
6420 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006425 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 Py_DECREF(restuple);
6427 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006429 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 &resunicode, newpos)) {
6431 Py_DECREF(restuple);
6432 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006434 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6435 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6436 Py_DECREF(restuple);
6437 return NULL;
6438 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006439 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006440 *newpos = len + *newpos;
6441 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006442 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6443 Py_DECREF(restuple);
6444 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006445 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006446 Py_INCREF(resunicode);
6447 Py_DECREF(restuple);
6448 return resunicode;
6449}
6450
Alexander Belopolsky40018472011-02-26 01:02:56 +00006451static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006452unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006453 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006454 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006455{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006456 /* input state */
6457 Py_ssize_t pos=0, size;
6458 int kind;
6459 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006460 /* output object */
6461 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462 /* pointer into the output */
6463 char *str;
6464 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006465 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006466 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6467 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006468 PyObject *errorHandler = NULL;
6469 PyObject *exc = NULL;
6470 /* the following variable is used for caching string comparisons
6471 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6472 int known_errorHandler = -1;
6473
Benjamin Petersonbac79492012-01-14 13:34:47 -05006474 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006475 return NULL;
6476 size = PyUnicode_GET_LENGTH(unicode);
6477 kind = PyUnicode_KIND(unicode);
6478 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006479 /* allocate enough for a simple encoding without
6480 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006481 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006482 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006483 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006484 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006485 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006486 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006487 ressize = size;
6488
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006489 while (pos < size) {
6490 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491
Benjamin Peterson29060642009-01-31 22:14:21 +00006492 /* can we encode this? */
6493 if (c<limit) {
6494 /* no overflow check, because we know that the space is enough */
6495 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006497 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 Py_ssize_t requiredsize;
6500 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 Py_ssize_t collstart = pos;
6504 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 ++collend;
6508 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6509 if (known_errorHandler==-1) {
6510 if ((errors==NULL) || (!strcmp(errors, "strict")))
6511 known_errorHandler = 1;
6512 else if (!strcmp(errors, "replace"))
6513 known_errorHandler = 2;
6514 else if (!strcmp(errors, "ignore"))
6515 known_errorHandler = 3;
6516 else if (!strcmp(errors, "xmlcharrefreplace"))
6517 known_errorHandler = 4;
6518 else
6519 known_errorHandler = 0;
6520 }
6521 switch (known_errorHandler) {
6522 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006523 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 goto onError;
6525 case 2: /* replace */
6526 while (collstart++<collend)
6527 *str++ = '?'; /* fall through */
6528 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006529 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 break;
6531 case 4: /* xmlcharrefreplace */
6532 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006533 /* determine replacement size */
6534 for (i = collstart, repsize = 0; i < collend; ++i) {
6535 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6536 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006538 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006540 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006541 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006542 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006545 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006548 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006549 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006551 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 if (requiredsize > ressize) {
6555 if (requiredsize<2*ressize)
6556 requiredsize = 2*ressize;
6557 if (_PyBytes_Resize(&res, requiredsize))
6558 goto onError;
6559 str = PyBytes_AS_STRING(res) + respos;
6560 ressize = requiredsize;
6561 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006562 /* generate replacement */
6563 for (i = collstart; i < collend; ++i) {
6564 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006566 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 break;
6568 default:
6569 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006570 encoding, reason, unicode, &exc,
6571 collstart, collend, &newpos);
6572 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006573 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006575 if (PyBytes_Check(repunicode)) {
6576 /* Directly copy bytes result to output. */
6577 repsize = PyBytes_Size(repunicode);
6578 if (repsize > 1) {
6579 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006580 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006581 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6582 Py_DECREF(repunicode);
6583 goto onError;
6584 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006585 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006586 ressize += repsize-1;
6587 }
6588 memcpy(str, PyBytes_AsString(repunicode), repsize);
6589 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006590 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006591 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006592 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006593 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 /* need more space? (at least enough for what we
6595 have+the replacement+the rest of the string, so
6596 we won't have to check space for encodable characters) */
6597 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 repsize = PyUnicode_GET_LENGTH(repunicode);
6599 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 if (requiredsize > ressize) {
6601 if (requiredsize<2*ressize)
6602 requiredsize = 2*ressize;
6603 if (_PyBytes_Resize(&res, requiredsize)) {
6604 Py_DECREF(repunicode);
6605 goto onError;
6606 }
6607 str = PyBytes_AS_STRING(res) + respos;
6608 ressize = requiredsize;
6609 }
6610 /* check if there is anything unencodable in the replacement
6611 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006612 for (i = 0; repsize-->0; ++i, ++str) {
6613 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006614 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006615 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006617 Py_DECREF(repunicode);
6618 goto onError;
6619 }
6620 *str = (char)c;
6621 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006623 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006624 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006625 }
6626 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006627 /* Resize if we allocated to much */
6628 size = str - PyBytes_AS_STRING(res);
6629 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006630 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006631 if (_PyBytes_Resize(&res, size) < 0)
6632 goto onError;
6633 }
6634
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635 Py_XDECREF(errorHandler);
6636 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006637 return res;
6638
6639 onError:
6640 Py_XDECREF(res);
6641 Py_XDECREF(errorHandler);
6642 Py_XDECREF(exc);
6643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644}
6645
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006647PyObject *
6648PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006649 Py_ssize_t size,
6650 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006651{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006652 PyObject *result;
6653 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6654 if (unicode == NULL)
6655 return NULL;
6656 result = unicode_encode_ucs1(unicode, errors, 256);
6657 Py_DECREF(unicode);
6658 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006659}
6660
Alexander Belopolsky40018472011-02-26 01:02:56 +00006661PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006662_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006663{
6664 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 PyErr_BadArgument();
6666 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006668 if (PyUnicode_READY(unicode) == -1)
6669 return NULL;
6670 /* Fast path: if it is a one-byte string, construct
6671 bytes object directly. */
6672 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6673 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6674 PyUnicode_GET_LENGTH(unicode));
6675 /* Non-Latin-1 characters present. Defer to above function to
6676 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006678}
6679
6680PyObject*
6681PyUnicode_AsLatin1String(PyObject *unicode)
6682{
6683 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006684}
6685
6686/* --- 7-bit ASCII Codec -------------------------------------------------- */
6687
Alexander Belopolsky40018472011-02-26 01:02:56 +00006688PyObject *
6689PyUnicode_DecodeASCII(const char *s,
6690 Py_ssize_t size,
6691 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006694 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006695 int kind;
6696 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006697 Py_ssize_t startinpos;
6698 Py_ssize_t endinpos;
6699 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 const char *e;
6701 PyObject *errorHandler = NULL;
6702 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006703
Guido van Rossumd57fd912000-03-10 22:53:23 +00006704 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006705 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006706
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006708 if (size == 1 && (unsigned char)s[0] < 128)
6709 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006710
Victor Stinner8f674cc2013-04-17 23:02:17 +02006711 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006712 writer.min_length = size;
6713 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006714 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006715
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006717 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006718 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006719 writer.pos = outpos;
6720 if (writer.pos == size)
6721 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006722
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006723 s += writer.pos;
6724 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006725 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006726 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006728 PyUnicode_WRITE(kind, data, writer.pos, c);
6729 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 ++s;
6731 }
6732 else {
6733 startinpos = s-starts;
6734 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006735 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 errors, &errorHandler,
6737 "ascii", "ordinal not in range(128)",
6738 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006739 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006741 kind = writer.kind;
6742 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006745 Py_XDECREF(errorHandler);
6746 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006747 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006748
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006750 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006751 Py_XDECREF(errorHandler);
6752 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006753 return NULL;
6754}
6755
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006756/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006757PyObject *
6758PyUnicode_EncodeASCII(const Py_UNICODE *p,
6759 Py_ssize_t size,
6760 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006761{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006762 PyObject *result;
6763 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6764 if (unicode == NULL)
6765 return NULL;
6766 result = unicode_encode_ucs1(unicode, errors, 128);
6767 Py_DECREF(unicode);
6768 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006769}
6770
Alexander Belopolsky40018472011-02-26 01:02:56 +00006771PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006772_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006773{
6774 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006775 PyErr_BadArgument();
6776 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006777 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006778 if (PyUnicode_READY(unicode) == -1)
6779 return NULL;
6780 /* Fast path: if it is an ASCII-only string, construct bytes object
6781 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006782 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006783 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6784 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006785 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006786}
6787
6788PyObject *
6789PyUnicode_AsASCIIString(PyObject *unicode)
6790{
6791 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006792}
6793
Victor Stinner99b95382011-07-04 14:23:54 +02006794#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006795
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006796/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006797
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006798#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006799#define NEED_RETRY
6800#endif
6801
Victor Stinner3a50e702011-10-18 21:21:00 +02006802#ifndef WC_ERR_INVALID_CHARS
6803# define WC_ERR_INVALID_CHARS 0x0080
6804#endif
6805
6806static char*
6807code_page_name(UINT code_page, PyObject **obj)
6808{
6809 *obj = NULL;
6810 if (code_page == CP_ACP)
6811 return "mbcs";
6812 if (code_page == CP_UTF7)
6813 return "CP_UTF7";
6814 if (code_page == CP_UTF8)
6815 return "CP_UTF8";
6816
6817 *obj = PyBytes_FromFormat("cp%u", code_page);
6818 if (*obj == NULL)
6819 return NULL;
6820 return PyBytes_AS_STRING(*obj);
6821}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006822
Alexander Belopolsky40018472011-02-26 01:02:56 +00006823static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006824is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006825{
6826 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006827 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006828
Victor Stinner3a50e702011-10-18 21:21:00 +02006829 if (!IsDBCSLeadByteEx(code_page, *curr))
6830 return 0;
6831
6832 prev = CharPrevExA(code_page, s, curr, 0);
6833 if (prev == curr)
6834 return 1;
6835 /* FIXME: This code is limited to "true" double-byte encodings,
6836 as it assumes an incomplete character consists of a single
6837 byte. */
6838 if (curr - prev == 2)
6839 return 1;
6840 if (!IsDBCSLeadByteEx(code_page, *prev))
6841 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006842 return 0;
6843}
6844
Victor Stinner3a50e702011-10-18 21:21:00 +02006845static DWORD
6846decode_code_page_flags(UINT code_page)
6847{
6848 if (code_page == CP_UTF7) {
6849 /* The CP_UTF7 decoder only supports flags=0 */
6850 return 0;
6851 }
6852 else
6853 return MB_ERR_INVALID_CHARS;
6854}
6855
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006856/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006857 * Decode a byte string from a Windows code page into unicode object in strict
6858 * mode.
6859 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006860 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6861 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006862 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006863static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006864decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006865 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006866 const char *in,
6867 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006868{
Victor Stinner3a50e702011-10-18 21:21:00 +02006869 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006870 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006871 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006872
6873 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006874 assert(insize > 0);
6875 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6876 if (outsize <= 0)
6877 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006878
6879 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006881 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006882 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 if (*v == NULL)
6884 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006886 }
6887 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006888 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006889 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006890 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006891 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006892 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006893 }
6894
6895 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006896 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6897 if (outsize <= 0)
6898 goto error;
6899 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006900
Victor Stinner3a50e702011-10-18 21:21:00 +02006901error:
6902 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6903 return -2;
6904 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006905 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006906}
6907
Victor Stinner3a50e702011-10-18 21:21:00 +02006908/*
6909 * Decode a byte string from a code page into unicode object with an error
6910 * handler.
6911 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006912 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 * UnicodeDecodeError exception and returns -1 on error.
6914 */
6915static int
6916decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006917 PyObject **v,
6918 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006919 const char *errors)
6920{
6921 const char *startin = in;
6922 const char *endin = in + size;
6923 const DWORD flags = decode_code_page_flags(code_page);
6924 /* Ideally, we should get reason from FormatMessage. This is the Windows
6925 2000 English version of the message. */
6926 const char *reason = "No mapping for the Unicode character exists "
6927 "in the target code page.";
6928 /* each step cannot decode more than 1 character, but a character can be
6929 represented as a surrogate pair */
6930 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006931 int insize;
6932 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006933 PyObject *errorHandler = NULL;
6934 PyObject *exc = NULL;
6935 PyObject *encoding_obj = NULL;
6936 char *encoding;
6937 DWORD err;
6938 int ret = -1;
6939
6940 assert(size > 0);
6941
6942 encoding = code_page_name(code_page, &encoding_obj);
6943 if (encoding == NULL)
6944 return -1;
6945
6946 if (errors == NULL || strcmp(errors, "strict") == 0) {
6947 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6948 UnicodeDecodeError. */
6949 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6950 if (exc != NULL) {
6951 PyCodec_StrictErrors(exc);
6952 Py_CLEAR(exc);
6953 }
6954 goto error;
6955 }
6956
6957 if (*v == NULL) {
6958 /* Create unicode object */
6959 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6960 PyErr_NoMemory();
6961 goto error;
6962 }
Victor Stinnerab595942011-12-17 04:59:06 +01006963 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006964 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006965 if (*v == NULL)
6966 goto error;
6967 startout = PyUnicode_AS_UNICODE(*v);
6968 }
6969 else {
6970 /* Extend unicode object */
6971 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6972 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6973 PyErr_NoMemory();
6974 goto error;
6975 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006976 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006977 goto error;
6978 startout = PyUnicode_AS_UNICODE(*v) + n;
6979 }
6980
6981 /* Decode the byte string character per character */
6982 out = startout;
6983 while (in < endin)
6984 {
6985 /* Decode a character */
6986 insize = 1;
6987 do
6988 {
6989 outsize = MultiByteToWideChar(code_page, flags,
6990 in, insize,
6991 buffer, Py_ARRAY_LENGTH(buffer));
6992 if (outsize > 0)
6993 break;
6994 err = GetLastError();
6995 if (err != ERROR_NO_UNICODE_TRANSLATION
6996 && err != ERROR_INSUFFICIENT_BUFFER)
6997 {
6998 PyErr_SetFromWindowsErr(0);
6999 goto error;
7000 }
7001 insize++;
7002 }
7003 /* 4=maximum length of a UTF-8 sequence */
7004 while (insize <= 4 && (in + insize) <= endin);
7005
7006 if (outsize <= 0) {
7007 Py_ssize_t startinpos, endinpos, outpos;
7008
7009 startinpos = in - startin;
7010 endinpos = startinpos + 1;
7011 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007012 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 errors, &errorHandler,
7014 encoding, reason,
7015 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007016 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 {
7018 goto error;
7019 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007020 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007021 }
7022 else {
7023 in += insize;
7024 memcpy(out, buffer, outsize * sizeof(wchar_t));
7025 out += outsize;
7026 }
7027 }
7028
7029 /* write a NUL character at the end */
7030 *out = 0;
7031
7032 /* Extend unicode object */
7033 outsize = out - startout;
7034 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007035 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007036 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007037 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007038
7039error:
7040 Py_XDECREF(encoding_obj);
7041 Py_XDECREF(errorHandler);
7042 Py_XDECREF(exc);
7043 return ret;
7044}
7045
Victor Stinner3a50e702011-10-18 21:21:00 +02007046static PyObject *
7047decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007048 const char *s, Py_ssize_t size,
7049 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007050{
Victor Stinner76a31a62011-11-04 00:05:13 +01007051 PyObject *v = NULL;
7052 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053
Victor Stinner3a50e702011-10-18 21:21:00 +02007054 if (code_page < 0) {
7055 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7056 return NULL;
7057 }
7058
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007060 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007061
Victor Stinner76a31a62011-11-04 00:05:13 +01007062 do
7063 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007064#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007065 if (size > INT_MAX) {
7066 chunk_size = INT_MAX;
7067 final = 0;
7068 done = 0;
7069 }
7070 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007072 {
7073 chunk_size = (int)size;
7074 final = (consumed == NULL);
7075 done = 1;
7076 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077
Victor Stinner76a31a62011-11-04 00:05:13 +01007078 /* Skip trailing lead-byte unless 'final' is set */
7079 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7080 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
Victor Stinner76a31a62011-11-04 00:05:13 +01007082 if (chunk_size == 0 && done) {
7083 if (v != NULL)
7084 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007085 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007086 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087
Victor Stinner76a31a62011-11-04 00:05:13 +01007088
7089 converted = decode_code_page_strict(code_page, &v,
7090 s, chunk_size);
7091 if (converted == -2)
7092 converted = decode_code_page_errors(code_page, &v,
7093 s, chunk_size,
7094 errors);
7095 assert(converted != 0);
7096
7097 if (converted < 0) {
7098 Py_XDECREF(v);
7099 return NULL;
7100 }
7101
7102 if (consumed)
7103 *consumed += converted;
7104
7105 s += converted;
7106 size -= converted;
7107 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007108
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007109 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110}
7111
Alexander Belopolsky40018472011-02-26 01:02:56 +00007112PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007113PyUnicode_DecodeCodePageStateful(int code_page,
7114 const char *s,
7115 Py_ssize_t size,
7116 const char *errors,
7117 Py_ssize_t *consumed)
7118{
7119 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7120}
7121
7122PyObject *
7123PyUnicode_DecodeMBCSStateful(const char *s,
7124 Py_ssize_t size,
7125 const char *errors,
7126 Py_ssize_t *consumed)
7127{
7128 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7129}
7130
7131PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007132PyUnicode_DecodeMBCS(const char *s,
7133 Py_ssize_t size,
7134 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007135{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007136 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7137}
7138
Victor Stinner3a50e702011-10-18 21:21:00 +02007139static DWORD
7140encode_code_page_flags(UINT code_page, const char *errors)
7141{
7142 if (code_page == CP_UTF8) {
7143 if (winver.dwMajorVersion >= 6)
7144 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7145 and later */
7146 return WC_ERR_INVALID_CHARS;
7147 else
7148 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7149 return 0;
7150 }
7151 else if (code_page == CP_UTF7) {
7152 /* CP_UTF7 only supports flags=0 */
7153 return 0;
7154 }
7155 else {
7156 if (errors != NULL && strcmp(errors, "replace") == 0)
7157 return 0;
7158 else
7159 return WC_NO_BEST_FIT_CHARS;
7160 }
7161}
7162
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007163/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007164 * Encode a Unicode string to a Windows code page into a byte string in strict
7165 * mode.
7166 *
7167 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007168 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007169 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007170static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007171encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007172 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007174{
Victor Stinner554f3f02010-06-16 23:33:54 +00007175 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 BOOL *pusedDefaultChar = &usedDefaultChar;
7177 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007178 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007179 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007180 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007181 const DWORD flags = encode_code_page_flags(code_page, NULL);
7182 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 /* Create a substring so that we can get the UTF-16 representation
7184 of just the slice under consideration. */
7185 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007186
Martin v. Löwis3d325192011-11-04 18:23:06 +01007187 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007188
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007190 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007192 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007193
Victor Stinner2fc507f2011-11-04 20:06:39 +01007194 substring = PyUnicode_Substring(unicode, offset, offset+len);
7195 if (substring == NULL)
7196 return -1;
7197 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7198 if (p == NULL) {
7199 Py_DECREF(substring);
7200 return -1;
7201 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007202 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007203
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007204 /* First get the size of the result */
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 NULL, 0,
7208 NULL, pusedDefaultChar);
7209 if (outsize <= 0)
7210 goto error;
7211 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007212 if (pusedDefaultChar && *pusedDefaultChar) {
7213 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007215 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007216
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007218 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007220 if (*outbytes == NULL) {
7221 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007222 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007223 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007225 }
7226 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007227 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 const Py_ssize_t n = PyBytes_Size(*outbytes);
7229 if (outsize > PY_SSIZE_T_MAX - n) {
7230 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007231 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007232 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007234 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7235 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007239 }
7240
7241 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007243 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 out, outsize,
7245 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007246 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 if (outsize <= 0)
7248 goto error;
7249 if (pusedDefaultChar && *pusedDefaultChar)
7250 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007252
Victor Stinner3a50e702011-10-18 21:21:00 +02007253error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007254 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7256 return -2;
7257 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007258 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007259}
7260
Victor Stinner3a50e702011-10-18 21:21:00 +02007261/*
7262 * Encode a Unicode string to a Windows code page into a byte string using a
7263 * error handler.
7264 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007265 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 * -1 on other error.
7267 */
7268static int
7269encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007270 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007271 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007272{
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007274 Py_ssize_t pos = unicode_offset;
7275 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007276 /* Ideally, we should get reason from FormatMessage. This is the Windows
7277 2000 English version of the message. */
7278 const char *reason = "invalid character";
7279 /* 4=maximum length of a UTF-8 sequence */
7280 char buffer[4];
7281 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7282 Py_ssize_t outsize;
7283 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 PyObject *errorHandler = NULL;
7285 PyObject *exc = NULL;
7286 PyObject *encoding_obj = NULL;
7287 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007288 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 PyObject *rep;
7290 int ret = -1;
7291
7292 assert(insize > 0);
7293
7294 encoding = code_page_name(code_page, &encoding_obj);
7295 if (encoding == NULL)
7296 return -1;
7297
7298 if (errors == NULL || strcmp(errors, "strict") == 0) {
7299 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7300 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007301 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007302 if (exc != NULL) {
7303 PyCodec_StrictErrors(exc);
7304 Py_DECREF(exc);
7305 }
7306 Py_XDECREF(encoding_obj);
7307 return -1;
7308 }
7309
7310 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7311 pusedDefaultChar = &usedDefaultChar;
7312 else
7313 pusedDefaultChar = NULL;
7314
7315 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7316 PyErr_NoMemory();
7317 goto error;
7318 }
7319 outsize = insize * Py_ARRAY_LENGTH(buffer);
7320
7321 if (*outbytes == NULL) {
7322 /* Create string object */
7323 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7324 if (*outbytes == NULL)
7325 goto error;
7326 out = PyBytes_AS_STRING(*outbytes);
7327 }
7328 else {
7329 /* Extend string object */
7330 Py_ssize_t n = PyBytes_Size(*outbytes);
7331 if (n > PY_SSIZE_T_MAX - outsize) {
7332 PyErr_NoMemory();
7333 goto error;
7334 }
7335 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7336 goto error;
7337 out = PyBytes_AS_STRING(*outbytes) + n;
7338 }
7339
7340 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007341 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007342 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007343 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7344 wchar_t chars[2];
7345 int charsize;
7346 if (ch < 0x10000) {
7347 chars[0] = (wchar_t)ch;
7348 charsize = 1;
7349 }
7350 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007351 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7352 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007353 charsize = 2;
7354 }
7355
Victor Stinner3a50e702011-10-18 21:21:00 +02007356 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007357 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007358 buffer, Py_ARRAY_LENGTH(buffer),
7359 NULL, pusedDefaultChar);
7360 if (outsize > 0) {
7361 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7362 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007363 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 memcpy(out, buffer, outsize);
7365 out += outsize;
7366 continue;
7367 }
7368 }
7369 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7370 PyErr_SetFromWindowsErr(0);
7371 goto error;
7372 }
7373
Victor Stinner3a50e702011-10-18 21:21:00 +02007374 rep = unicode_encode_call_errorhandler(
7375 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007376 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007377 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 if (rep == NULL)
7379 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007380 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007381
7382 if (PyBytes_Check(rep)) {
7383 outsize = PyBytes_GET_SIZE(rep);
7384 if (outsize != 1) {
7385 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7386 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7387 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7388 Py_DECREF(rep);
7389 goto error;
7390 }
7391 out = PyBytes_AS_STRING(*outbytes) + offset;
7392 }
7393 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7394 out += outsize;
7395 }
7396 else {
7397 Py_ssize_t i;
7398 enum PyUnicode_Kind kind;
7399 void *data;
7400
Benjamin Petersonbac79492012-01-14 13:34:47 -05007401 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 Py_DECREF(rep);
7403 goto error;
7404 }
7405
7406 outsize = PyUnicode_GET_LENGTH(rep);
7407 if (outsize != 1) {
7408 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7409 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7410 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7411 Py_DECREF(rep);
7412 goto error;
7413 }
7414 out = PyBytes_AS_STRING(*outbytes) + offset;
7415 }
7416 kind = PyUnicode_KIND(rep);
7417 data = PyUnicode_DATA(rep);
7418 for (i=0; i < outsize; i++) {
7419 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7420 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007421 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007422 encoding, unicode,
7423 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007424 "unable to encode error handler result to ASCII");
7425 Py_DECREF(rep);
7426 goto error;
7427 }
7428 *out = (unsigned char)ch;
7429 out++;
7430 }
7431 }
7432 Py_DECREF(rep);
7433 }
7434 /* write a NUL byte */
7435 *out = 0;
7436 outsize = out - PyBytes_AS_STRING(*outbytes);
7437 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7438 if (_PyBytes_Resize(outbytes, outsize) < 0)
7439 goto error;
7440 ret = 0;
7441
7442error:
7443 Py_XDECREF(encoding_obj);
7444 Py_XDECREF(errorHandler);
7445 Py_XDECREF(exc);
7446 return ret;
7447}
7448
Victor Stinner3a50e702011-10-18 21:21:00 +02007449static PyObject *
7450encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007451 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 const char *errors)
7453{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007454 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007456 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007457 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007458
Benjamin Petersonbac79492012-01-14 13:34:47 -05007459 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007460 return NULL;
7461 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007462
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 if (code_page < 0) {
7464 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7465 return NULL;
7466 }
7467
Martin v. Löwis3d325192011-11-04 18:23:06 +01007468 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007469 return PyBytes_FromStringAndSize(NULL, 0);
7470
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 offset = 0;
7472 do
7473 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007474#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007476 chunks. */
7477 if (len > INT_MAX/2) {
7478 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007479 done = 0;
7480 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007481 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007482#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007483 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007484 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007485 done = 1;
7486 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007487
Victor Stinner76a31a62011-11-04 00:05:13 +01007488 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007490 errors);
7491 if (ret == -2)
7492 ret = encode_code_page_errors(code_page, &outbytes,
7493 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007494 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007495 if (ret < 0) {
7496 Py_XDECREF(outbytes);
7497 return NULL;
7498 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007499
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007501 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007502 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 return outbytes;
7505}
7506
7507PyObject *
7508PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7509 Py_ssize_t size,
7510 const char *errors)
7511{
Victor Stinner7581cef2011-11-03 22:32:33 +01007512 PyObject *unicode, *res;
7513 unicode = PyUnicode_FromUnicode(p, size);
7514 if (unicode == NULL)
7515 return NULL;
7516 res = encode_code_page(CP_ACP, unicode, errors);
7517 Py_DECREF(unicode);
7518 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007519}
7520
7521PyObject *
7522PyUnicode_EncodeCodePage(int code_page,
7523 PyObject *unicode,
7524 const char *errors)
7525{
Victor Stinner7581cef2011-11-03 22:32:33 +01007526 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007527}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007528
Alexander Belopolsky40018472011-02-26 01:02:56 +00007529PyObject *
7530PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007531{
7532 if (!PyUnicode_Check(unicode)) {
7533 PyErr_BadArgument();
7534 return NULL;
7535 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007536 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007537}
7538
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007539#undef NEED_RETRY
7540
Victor Stinner99b95382011-07-04 14:23:54 +02007541#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007542
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543/* --- Character Mapping Codec -------------------------------------------- */
7544
Victor Stinnerfb161b12013-04-18 01:44:27 +02007545static int
7546charmap_decode_string(const char *s,
7547 Py_ssize_t size,
7548 PyObject *mapping,
7549 const char *errors,
7550 _PyUnicodeWriter *writer)
7551{
7552 const char *starts = s;
7553 const char *e;
7554 Py_ssize_t startinpos, endinpos;
7555 PyObject *errorHandler = NULL, *exc = NULL;
7556 Py_ssize_t maplen;
7557 enum PyUnicode_Kind mapkind;
7558 void *mapdata;
7559 Py_UCS4 x;
7560 unsigned char ch;
7561
7562 if (PyUnicode_READY(mapping) == -1)
7563 return -1;
7564
7565 maplen = PyUnicode_GET_LENGTH(mapping);
7566 mapdata = PyUnicode_DATA(mapping);
7567 mapkind = PyUnicode_KIND(mapping);
7568
7569 e = s + size;
7570
7571 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7572 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7573 * is disabled in encoding aliases, latin1 is preferred because
7574 * its implementation is faster. */
7575 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7576 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7577 Py_UCS4 maxchar = writer->maxchar;
7578
7579 assert (writer->kind == PyUnicode_1BYTE_KIND);
7580 while (s < e) {
7581 ch = *s;
7582 x = mapdata_ucs1[ch];
7583 if (x > maxchar) {
7584 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7585 goto onError;
7586 maxchar = writer->maxchar;
7587 outdata = (Py_UCS1 *)writer->data;
7588 }
7589 outdata[writer->pos] = x;
7590 writer->pos++;
7591 ++s;
7592 }
7593 return 0;
7594 }
7595
7596 while (s < e) {
7597 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7598 enum PyUnicode_Kind outkind = writer->kind;
7599 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7600 if (outkind == PyUnicode_1BYTE_KIND) {
7601 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7602 Py_UCS4 maxchar = writer->maxchar;
7603 while (s < e) {
7604 ch = *s;
7605 x = mapdata_ucs2[ch];
7606 if (x > maxchar)
7607 goto Error;
7608 outdata[writer->pos] = x;
7609 writer->pos++;
7610 ++s;
7611 }
7612 break;
7613 }
7614 else if (outkind == PyUnicode_2BYTE_KIND) {
7615 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7616 while (s < e) {
7617 ch = *s;
7618 x = mapdata_ucs2[ch];
7619 if (x == 0xFFFE)
7620 goto Error;
7621 outdata[writer->pos] = x;
7622 writer->pos++;
7623 ++s;
7624 }
7625 break;
7626 }
7627 }
7628 ch = *s;
7629
7630 if (ch < maplen)
7631 x = PyUnicode_READ(mapkind, mapdata, ch);
7632 else
7633 x = 0xfffe; /* invalid value */
7634Error:
7635 if (x == 0xfffe)
7636 {
7637 /* undefined mapping */
7638 startinpos = s-starts;
7639 endinpos = startinpos+1;
7640 if (unicode_decode_call_errorhandler_writer(
7641 errors, &errorHandler,
7642 "charmap", "character maps to <undefined>",
7643 &starts, &e, &startinpos, &endinpos, &exc, &s,
7644 writer)) {
7645 goto onError;
7646 }
7647 continue;
7648 }
7649
7650 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7651 goto onError;
7652 ++s;
7653 }
7654 Py_XDECREF(errorHandler);
7655 Py_XDECREF(exc);
7656 return 0;
7657
7658onError:
7659 Py_XDECREF(errorHandler);
7660 Py_XDECREF(exc);
7661 return -1;
7662}
7663
7664static int
7665charmap_decode_mapping(const char *s,
7666 Py_ssize_t size,
7667 PyObject *mapping,
7668 const char *errors,
7669 _PyUnicodeWriter *writer)
7670{
7671 const char *starts = s;
7672 const char *e;
7673 Py_ssize_t startinpos, endinpos;
7674 PyObject *errorHandler = NULL, *exc = NULL;
7675 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007676 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007677
7678 e = s + size;
7679
7680 while (s < e) {
7681 ch = *s;
7682
7683 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7684 key = PyLong_FromLong((long)ch);
7685 if (key == NULL)
7686 goto onError;
7687
7688 item = PyObject_GetItem(mapping, key);
7689 Py_DECREF(key);
7690 if (item == NULL) {
7691 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7692 /* No mapping found means: mapping is undefined. */
7693 PyErr_Clear();
7694 goto Undefined;
7695 } else
7696 goto onError;
7697 }
7698
7699 /* Apply mapping */
7700 if (item == Py_None)
7701 goto Undefined;
7702 if (PyLong_Check(item)) {
7703 long value = PyLong_AS_LONG(item);
7704 if (value == 0xFFFE)
7705 goto Undefined;
7706 if (value < 0 || value > MAX_UNICODE) {
7707 PyErr_Format(PyExc_TypeError,
7708 "character mapping must be in range(0x%lx)",
7709 (unsigned long)MAX_UNICODE + 1);
7710 goto onError;
7711 }
7712
7713 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7714 goto onError;
7715 }
7716 else if (PyUnicode_Check(item)) {
7717 if (PyUnicode_READY(item) == -1)
7718 goto onError;
7719 if (PyUnicode_GET_LENGTH(item) == 1) {
7720 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7721 if (value == 0xFFFE)
7722 goto Undefined;
7723 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7724 goto onError;
7725 }
7726 else {
7727 writer->overallocate = 1;
7728 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7729 goto onError;
7730 }
7731 }
7732 else {
7733 /* wrong return value */
7734 PyErr_SetString(PyExc_TypeError,
7735 "character mapping must return integer, None or str");
7736 goto onError;
7737 }
7738 Py_CLEAR(item);
7739 ++s;
7740 continue;
7741
7742Undefined:
7743 /* undefined mapping */
7744 Py_CLEAR(item);
7745 startinpos = s-starts;
7746 endinpos = startinpos+1;
7747 if (unicode_decode_call_errorhandler_writer(
7748 errors, &errorHandler,
7749 "charmap", "character maps to <undefined>",
7750 &starts, &e, &startinpos, &endinpos, &exc, &s,
7751 writer)) {
7752 goto onError;
7753 }
7754 }
7755 Py_XDECREF(errorHandler);
7756 Py_XDECREF(exc);
7757 return 0;
7758
7759onError:
7760 Py_XDECREF(item);
7761 Py_XDECREF(errorHandler);
7762 Py_XDECREF(exc);
7763 return -1;
7764}
7765
Alexander Belopolsky40018472011-02-26 01:02:56 +00007766PyObject *
7767PyUnicode_DecodeCharmap(const char *s,
7768 Py_ssize_t size,
7769 PyObject *mapping,
7770 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007772 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007773
Guido van Rossumd57fd912000-03-10 22:53:23 +00007774 /* Default to Latin-1 */
7775 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007776 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007777
Guido van Rossumd57fd912000-03-10 22:53:23 +00007778 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007779 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007780 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007781 writer.min_length = size;
7782 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007783 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007784
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007785 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007786 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7787 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007788 }
7789 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007790 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7791 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007792 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007793 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007794
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007796 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007797 return NULL;
7798}
7799
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007800/* Charmap encoding: the lookup table */
7801
Alexander Belopolsky40018472011-02-26 01:02:56 +00007802struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007803 PyObject_HEAD
7804 unsigned char level1[32];
7805 int count2, count3;
7806 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007807};
7808
7809static PyObject*
7810encoding_map_size(PyObject *obj, PyObject* args)
7811{
7812 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007813 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007814 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007815}
7816
7817static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007818 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 PyDoc_STR("Return the size (in bytes) of this object") },
7820 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007821};
7822
7823static void
7824encoding_map_dealloc(PyObject* o)
7825{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007826 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007827}
7828
7829static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007830 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 "EncodingMap", /*tp_name*/
7832 sizeof(struct encoding_map), /*tp_basicsize*/
7833 0, /*tp_itemsize*/
7834 /* methods */
7835 encoding_map_dealloc, /*tp_dealloc*/
7836 0, /*tp_print*/
7837 0, /*tp_getattr*/
7838 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007839 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007840 0, /*tp_repr*/
7841 0, /*tp_as_number*/
7842 0, /*tp_as_sequence*/
7843 0, /*tp_as_mapping*/
7844 0, /*tp_hash*/
7845 0, /*tp_call*/
7846 0, /*tp_str*/
7847 0, /*tp_getattro*/
7848 0, /*tp_setattro*/
7849 0, /*tp_as_buffer*/
7850 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7851 0, /*tp_doc*/
7852 0, /*tp_traverse*/
7853 0, /*tp_clear*/
7854 0, /*tp_richcompare*/
7855 0, /*tp_weaklistoffset*/
7856 0, /*tp_iter*/
7857 0, /*tp_iternext*/
7858 encoding_map_methods, /*tp_methods*/
7859 0, /*tp_members*/
7860 0, /*tp_getset*/
7861 0, /*tp_base*/
7862 0, /*tp_dict*/
7863 0, /*tp_descr_get*/
7864 0, /*tp_descr_set*/
7865 0, /*tp_dictoffset*/
7866 0, /*tp_init*/
7867 0, /*tp_alloc*/
7868 0, /*tp_new*/
7869 0, /*tp_free*/
7870 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871};
7872
7873PyObject*
7874PyUnicode_BuildEncodingMap(PyObject* string)
7875{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007876 PyObject *result;
7877 struct encoding_map *mresult;
7878 int i;
7879 int need_dict = 0;
7880 unsigned char level1[32];
7881 unsigned char level2[512];
7882 unsigned char *mlevel1, *mlevel2, *mlevel3;
7883 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007884 int kind;
7885 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007886 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007887 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007889 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007890 PyErr_BadArgument();
7891 return NULL;
7892 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007893 kind = PyUnicode_KIND(string);
7894 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007895 length = PyUnicode_GET_LENGTH(string);
7896 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 memset(level1, 0xFF, sizeof level1);
7898 memset(level2, 0xFF, sizeof level2);
7899
7900 /* If there isn't a one-to-one mapping of NULL to \0,
7901 or if there are non-BMP characters, we need to use
7902 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007903 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007905 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007906 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007907 ch = PyUnicode_READ(kind, data, i);
7908 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007909 need_dict = 1;
7910 break;
7911 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007912 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007913 /* unmapped character */
7914 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007915 l1 = ch >> 11;
7916 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917 if (level1[l1] == 0xFF)
7918 level1[l1] = count2++;
7919 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007920 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007921 }
7922
7923 if (count2 >= 0xFF || count3 >= 0xFF)
7924 need_dict = 1;
7925
7926 if (need_dict) {
7927 PyObject *result = PyDict_New();
7928 PyObject *key, *value;
7929 if (!result)
7930 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007931 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007932 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007933 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934 if (!key || !value)
7935 goto failed1;
7936 if (PyDict_SetItem(result, key, value) == -1)
7937 goto failed1;
7938 Py_DECREF(key);
7939 Py_DECREF(value);
7940 }
7941 return result;
7942 failed1:
7943 Py_XDECREF(key);
7944 Py_XDECREF(value);
7945 Py_DECREF(result);
7946 return NULL;
7947 }
7948
7949 /* Create a three-level trie */
7950 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7951 16*count2 + 128*count3 - 1);
7952 if (!result)
7953 return PyErr_NoMemory();
7954 PyObject_Init(result, &EncodingMapType);
7955 mresult = (struct encoding_map*)result;
7956 mresult->count2 = count2;
7957 mresult->count3 = count3;
7958 mlevel1 = mresult->level1;
7959 mlevel2 = mresult->level23;
7960 mlevel3 = mresult->level23 + 16*count2;
7961 memcpy(mlevel1, level1, 32);
7962 memset(mlevel2, 0xFF, 16*count2);
7963 memset(mlevel3, 0, 128*count3);
7964 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007965 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007966 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007967 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7968 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969 /* unmapped character */
7970 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007971 o1 = ch>>11;
7972 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007973 i2 = 16*mlevel1[o1] + o2;
7974 if (mlevel2[i2] == 0xFF)
7975 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007976 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007977 i3 = 128*mlevel2[i2] + o3;
7978 mlevel3[i3] = i;
7979 }
7980 return result;
7981}
7982
7983static int
Victor Stinner22168992011-11-20 17:09:18 +01007984encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007985{
7986 struct encoding_map *map = (struct encoding_map*)mapping;
7987 int l1 = c>>11;
7988 int l2 = (c>>7) & 0xF;
7989 int l3 = c & 0x7F;
7990 int i;
7991
Victor Stinner22168992011-11-20 17:09:18 +01007992 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994 if (c == 0)
7995 return 0;
7996 /* level 1*/
7997 i = map->level1[l1];
7998 if (i == 0xFF) {
7999 return -1;
8000 }
8001 /* level 2*/
8002 i = map->level23[16*i+l2];
8003 if (i == 0xFF) {
8004 return -1;
8005 }
8006 /* level 3 */
8007 i = map->level23[16*map->count2 + 128*i + l3];
8008 if (i == 0) {
8009 return -1;
8010 }
8011 return i;
8012}
8013
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008014/* Lookup the character ch in the mapping. If the character
8015 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008016 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008017static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008018charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019{
Christian Heimes217cfd12007-12-02 14:31:20 +00008020 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021 PyObject *x;
8022
8023 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008025 x = PyObject_GetItem(mapping, w);
8026 Py_DECREF(w);
8027 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8029 /* No mapping found means: mapping is undefined. */
8030 PyErr_Clear();
8031 x = Py_None;
8032 Py_INCREF(x);
8033 return x;
8034 } else
8035 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008036 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008037 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008039 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 long value = PyLong_AS_LONG(x);
8041 if (value < 0 || value > 255) {
8042 PyErr_SetString(PyExc_TypeError,
8043 "character mapping must be in range(256)");
8044 Py_DECREF(x);
8045 return NULL;
8046 }
8047 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008048 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008049 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008051 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 /* wrong return value */
8053 PyErr_Format(PyExc_TypeError,
8054 "character mapping must return integer, bytes or None, not %.400s",
8055 x->ob_type->tp_name);
8056 Py_DECREF(x);
8057 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008058 }
8059}
8060
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008061static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008062charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008064 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8065 /* exponentially overallocate to minimize reallocations */
8066 if (requiredsize < 2*outsize)
8067 requiredsize = 2*outsize;
8068 if (_PyBytes_Resize(outobj, requiredsize))
8069 return -1;
8070 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008071}
8072
Benjamin Peterson14339b62009-01-31 16:36:08 +00008073typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008074 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008075} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008076/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008077 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078 space is available. Return a new reference to the object that
8079 was put in the output buffer, or Py_None, if the mapping was undefined
8080 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008081 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008082static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008083charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008084 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008086 PyObject *rep;
8087 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008088 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008089
Christian Heimes90aa7642007-12-19 02:45:37 +00008090 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008092 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093 if (res == -1)
8094 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 if (outsize<requiredsize)
8096 if (charmapencode_resize(outobj, outpos, requiredsize))
8097 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008098 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008099 outstart[(*outpos)++] = (char)res;
8100 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008101 }
8102
8103 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008104 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 Py_DECREF(rep);
8108 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008109 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008110 if (PyLong_Check(rep)) {
8111 Py_ssize_t requiredsize = *outpos+1;
8112 if (outsize<requiredsize)
8113 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8114 Py_DECREF(rep);
8115 return enc_EXCEPTION;
8116 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008117 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008119 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 else {
8121 const char *repchars = PyBytes_AS_STRING(rep);
8122 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8123 Py_ssize_t requiredsize = *outpos+repsize;
8124 if (outsize<requiredsize)
8125 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8126 Py_DECREF(rep);
8127 return enc_EXCEPTION;
8128 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008129 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 memcpy(outstart + *outpos, repchars, repsize);
8131 *outpos += repsize;
8132 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 Py_DECREF(rep);
8135 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008136}
8137
8138/* handle an error in PyUnicode_EncodeCharmap
8139 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008140static int
8141charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008142 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008143 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008144 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008145 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146{
8147 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008148 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008149 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008150 enum PyUnicode_Kind kind;
8151 void *data;
8152 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008153 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008154 Py_ssize_t collstartpos = *inpos;
8155 Py_ssize_t collendpos = *inpos+1;
8156 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008157 char *encoding = "charmap";
8158 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008159 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008160 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008161 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008162
Benjamin Petersonbac79492012-01-14 13:34:47 -05008163 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008164 return -1;
8165 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008166 /* find all unencodable characters */
8167 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008168 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008169 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008170 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008171 val = encoding_map_lookup(ch, mapping);
8172 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 break;
8174 ++collendpos;
8175 continue;
8176 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008178 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8179 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 if (rep==NULL)
8181 return -1;
8182 else if (rep!=Py_None) {
8183 Py_DECREF(rep);
8184 break;
8185 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008186 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008187 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008188 }
8189 /* cache callback name lookup
8190 * (if not done yet, i.e. it's the first error) */
8191 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 if ((errors==NULL) || (!strcmp(errors, "strict")))
8193 *known_errorHandler = 1;
8194 else if (!strcmp(errors, "replace"))
8195 *known_errorHandler = 2;
8196 else if (!strcmp(errors, "ignore"))
8197 *known_errorHandler = 3;
8198 else if (!strcmp(errors, "xmlcharrefreplace"))
8199 *known_errorHandler = 4;
8200 else
8201 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008202 }
8203 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008205 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206 return -1;
8207 case 2: /* replace */
8208 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 x = charmapencode_output('?', mapping, res, respos);
8210 if (x==enc_EXCEPTION) {
8211 return -1;
8212 }
8213 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008214 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 return -1;
8216 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008217 }
8218 /* fall through */
8219 case 3: /* ignore */
8220 *inpos = collendpos;
8221 break;
8222 case 4: /* xmlcharrefreplace */
8223 /* generate replacement (temporarily (mis)uses p) */
8224 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 char buffer[2+29+1+1];
8226 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008227 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 for (cp = buffer; *cp; ++cp) {
8229 x = charmapencode_output(*cp, mapping, res, respos);
8230 if (x==enc_EXCEPTION)
8231 return -1;
8232 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008233 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 return -1;
8235 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008236 }
8237 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 *inpos = collendpos;
8239 break;
8240 default:
8241 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008242 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008244 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008246 if (PyBytes_Check(repunicode)) {
8247 /* Directly copy bytes result to output. */
8248 Py_ssize_t outsize = PyBytes_Size(*res);
8249 Py_ssize_t requiredsize;
8250 repsize = PyBytes_Size(repunicode);
8251 requiredsize = *respos + repsize;
8252 if (requiredsize > outsize)
8253 /* Make room for all additional bytes. */
8254 if (charmapencode_resize(res, respos, requiredsize)) {
8255 Py_DECREF(repunicode);
8256 return -1;
8257 }
8258 memcpy(PyBytes_AsString(*res) + *respos,
8259 PyBytes_AsString(repunicode), repsize);
8260 *respos += repsize;
8261 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008262 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008263 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008264 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008265 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008266 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008267 Py_DECREF(repunicode);
8268 return -1;
8269 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008270 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008271 data = PyUnicode_DATA(repunicode);
8272 kind = PyUnicode_KIND(repunicode);
8273 for (index = 0; index < repsize; index++) {
8274 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8275 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008277 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 return -1;
8279 }
8280 else if (x==enc_FAILED) {
8281 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008282 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008283 return -1;
8284 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008285 }
8286 *inpos = newpos;
8287 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288 }
8289 return 0;
8290}
8291
Alexander Belopolsky40018472011-02-26 01:02:56 +00008292PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008293_PyUnicode_EncodeCharmap(PyObject *unicode,
8294 PyObject *mapping,
8295 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008297 /* output object */
8298 PyObject *res = NULL;
8299 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008300 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008301 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008303 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304 PyObject *errorHandler = NULL;
8305 PyObject *exc = NULL;
8306 /* the following variable is used for caching string comparisons
8307 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8308 * 3=ignore, 4=xmlcharrefreplace */
8309 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008310 void *data;
8311 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008312
Benjamin Petersonbac79492012-01-14 13:34:47 -05008313 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008314 return NULL;
8315 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008316 data = PyUnicode_DATA(unicode);
8317 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008318
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319 /* Default to Latin-1 */
8320 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008322
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323 /* allocate enough for a simple encoding without
8324 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008325 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326 if (res == NULL)
8327 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008328 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008332 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008334 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 if (x==enc_EXCEPTION) /* error */
8336 goto onError;
8337 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008338 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008339 &exc,
8340 &known_errorHandler, &errorHandler, errors,
8341 &res, &respos)) {
8342 goto onError;
8343 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008344 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 else
8346 /* done with this character => adjust input position */
8347 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008349
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008351 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008352 if (_PyBytes_Resize(&res, respos) < 0)
8353 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008354
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 Py_XDECREF(exc);
8356 Py_XDECREF(errorHandler);
8357 return res;
8358
Benjamin Peterson29060642009-01-31 22:14:21 +00008359 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 Py_XDECREF(res);
8361 Py_XDECREF(exc);
8362 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008363 return NULL;
8364}
8365
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008366/* Deprecated */
8367PyObject *
8368PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8369 Py_ssize_t size,
8370 PyObject *mapping,
8371 const char *errors)
8372{
8373 PyObject *result;
8374 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8375 if (unicode == NULL)
8376 return NULL;
8377 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8378 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008379 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380}
8381
Alexander Belopolsky40018472011-02-26 01:02:56 +00008382PyObject *
8383PyUnicode_AsCharmapString(PyObject *unicode,
8384 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008385{
8386 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 PyErr_BadArgument();
8388 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008389 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008390 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391}
8392
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008394static void
8395make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008396 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008397 Py_ssize_t startpos, Py_ssize_t endpos,
8398 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008399{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008401 *exceptionObject = _PyUnicodeTranslateError_Create(
8402 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008403 }
8404 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8406 goto onError;
8407 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8408 goto onError;
8409 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8410 goto onError;
8411 return;
8412 onError:
8413 Py_DECREF(*exceptionObject);
8414 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415 }
8416}
8417
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418/* error handling callback helper:
8419 build arguments, call the callback and check the arguments,
8420 put the result into newpos and return the replacement string, which
8421 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008422static PyObject *
8423unicode_translate_call_errorhandler(const char *errors,
8424 PyObject **errorHandler,
8425 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008426 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008427 Py_ssize_t startpos, Py_ssize_t endpos,
8428 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008430 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008432 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433 PyObject *restuple;
8434 PyObject *resunicode;
8435
8436 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 }
8441
8442 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008443 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446
8447 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008451 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008452 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 Py_DECREF(restuple);
8454 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008455 }
8456 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 &resunicode, &i_newpos)) {
8458 Py_DECREF(restuple);
8459 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008461 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008463 else
8464 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008465 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8467 Py_DECREF(restuple);
8468 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008469 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 Py_INCREF(resunicode);
8471 Py_DECREF(restuple);
8472 return resunicode;
8473}
8474
8475/* Lookup the character ch in the mapping and put the result in result,
8476 which must be decrefed by the caller.
8477 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008478static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480{
Christian Heimes217cfd12007-12-02 14:31:20 +00008481 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 PyObject *x;
8483
8484 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486 x = PyObject_GetItem(mapping, w);
8487 Py_DECREF(w);
8488 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8490 /* No mapping found means: use 1:1 mapping. */
8491 PyErr_Clear();
8492 *result = NULL;
8493 return 0;
8494 } else
8495 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 }
8497 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 *result = x;
8499 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008501 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 long value = PyLong_AS_LONG(x);
8503 long max = PyUnicode_GetMax();
8504 if (value < 0 || value > max) {
8505 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008506 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 Py_DECREF(x);
8508 return -1;
8509 }
8510 *result = x;
8511 return 0;
8512 }
8513 else if (PyUnicode_Check(x)) {
8514 *result = x;
8515 return 0;
8516 }
8517 else {
8518 /* wrong return value */
8519 PyErr_SetString(PyExc_TypeError,
8520 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008521 Py_DECREF(x);
8522 return -1;
8523 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008524}
8525/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 if not reallocate and adjust various state variables.
8527 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008528static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008529charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008533 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008534 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 /* exponentially overallocate to minimize reallocations */
8536 if (requiredsize < 2 * oldsize)
8537 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008538 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8539 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008541 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008543 }
8544 return 0;
8545}
8546/* lookup the character, put the result in the output string and adjust
8547 various state variables. Return a new reference to the object that
8548 was put in the output buffer in *result, or Py_None, if the mapping was
8549 undefined (in which case no character was written).
8550 The called must decref result.
8551 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008552static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008553charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8554 PyObject *mapping, Py_UCS4 **output,
8555 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008556 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008558 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8559 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008564 }
8565 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008567 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008569 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 }
8571 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 Py_ssize_t repsize;
8573 if (PyUnicode_READY(*res) == -1)
8574 return -1;
8575 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 if (repsize==1) {
8577 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008578 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 }
8580 else if (repsize!=0) {
8581 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008582 Py_ssize_t requiredsize = *opos +
8583 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008584 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 Py_ssize_t i;
8586 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 for(i = 0; i < repsize; i++)
8589 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 }
8592 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 return 0;
8595}
8596
Alexander Belopolsky40018472011-02-26 01:02:56 +00008597PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008598_PyUnicode_TranslateCharmap(PyObject *input,
8599 PyObject *mapping,
8600 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 /* input object */
8603 char *idata;
8604 Py_ssize_t size, i;
8605 int kind;
8606 /* output buffer */
8607 Py_UCS4 *output = NULL;
8608 Py_ssize_t osize;
8609 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612 char *reason = "character maps to <undefined>";
8613 PyObject *errorHandler = NULL;
8614 PyObject *exc = NULL;
8615 /* the following variable is used for caching string comparisons
8616 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8617 * 3=ignore, 4=xmlcharrefreplace */
8618 int known_errorHandler = -1;
8619
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 PyErr_BadArgument();
8622 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008623 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 if (PyUnicode_READY(input) == -1)
8626 return NULL;
8627 idata = (char*)PyUnicode_DATA(input);
8628 kind = PyUnicode_KIND(input);
8629 size = PyUnicode_GET_LENGTH(input);
8630 i = 0;
8631
8632 if (size == 0) {
8633 Py_INCREF(input);
8634 return input;
8635 }
8636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 /* allocate enough for a simple 1:1 translation without
8638 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 osize = size;
8640 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8641 opos = 0;
8642 if (output == NULL) {
8643 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 /* try to encode it */
8649 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008650 if (charmaptranslate_output(input, i, mapping,
8651 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 Py_XDECREF(x);
8653 goto onError;
8654 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008655 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 else { /* untranslatable character */
8659 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8660 Py_ssize_t repsize;
8661 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 Py_ssize_t collstart = i;
8665 Py_ssize_t collend = i+1;
8666 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008667
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 while (collend < size) {
8670 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 goto onError;
8672 Py_XDECREF(x);
8673 if (x!=Py_None)
8674 break;
8675 ++collend;
8676 }
8677 /* cache callback name lookup
8678 * (if not done yet, i.e. it's the first error) */
8679 if (known_errorHandler==-1) {
8680 if ((errors==NULL) || (!strcmp(errors, "strict")))
8681 known_errorHandler = 1;
8682 else if (!strcmp(errors, "replace"))
8683 known_errorHandler = 2;
8684 else if (!strcmp(errors, "ignore"))
8685 known_errorHandler = 3;
8686 else if (!strcmp(errors, "xmlcharrefreplace"))
8687 known_errorHandler = 4;
8688 else
8689 known_errorHandler = 0;
8690 }
8691 switch (known_errorHandler) {
8692 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008693 make_translate_exception(&exc,
8694 input, collstart, collend, reason);
8695 if (exc != NULL)
8696 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008697 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 case 2: /* replace */
8699 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008700 for (coll = collstart; coll<collend; coll++)
8701 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 /* fall through */
8703 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 break;
8706 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008707 /* generate replacement (temporarily (mis)uses i) */
8708 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008709 char buffer[2+29+1+1];
8710 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8712 if (charmaptranslate_makespace(&output, &osize,
8713 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 goto onError;
8715 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 break;
8720 default:
8721 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722 reason, input, &exc,
8723 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008724 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008726 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008727 Py_DECREF(repunicode);
8728 goto onError;
8729 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731 repsize = PyUnicode_GET_LENGTH(repunicode);
8732 if (charmaptranslate_makespace(&output, &osize,
8733 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 Py_DECREF(repunicode);
8735 goto onError;
8736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 for (uni2 = 0; repsize-->0; ++uni2)
8738 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8739 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008741 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008742 }
8743 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8745 if (!res)
8746 goto onError;
8747 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748 Py_XDECREF(exc);
8749 Py_XDECREF(errorHandler);
8750 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008751
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008753 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008754 Py_XDECREF(exc);
8755 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008756 return NULL;
8757}
8758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759/* Deprecated. Use PyUnicode_Translate instead. */
8760PyObject *
8761PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8762 Py_ssize_t size,
8763 PyObject *mapping,
8764 const char *errors)
8765{
Christian Heimes5f520f42012-09-11 14:03:25 +02008766 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8768 if (!unicode)
8769 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008770 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8771 Py_DECREF(unicode);
8772 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773}
8774
Alexander Belopolsky40018472011-02-26 01:02:56 +00008775PyObject *
8776PyUnicode_Translate(PyObject *str,
8777 PyObject *mapping,
8778 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008779{
8780 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008781
Guido van Rossumd57fd912000-03-10 22:53:23 +00008782 str = PyUnicode_FromObject(str);
8783 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008784 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786 Py_DECREF(str);
8787 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008788}
Tim Petersced69f82003-09-16 20:30:58 +00008789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008791fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792{
8793 /* No need to call PyUnicode_READY(self) because this function is only
8794 called as a callback from fixup() which does it already. */
8795 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8796 const int kind = PyUnicode_KIND(self);
8797 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008798 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008799 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 Py_ssize_t i;
8801
8802 for (i = 0; i < len; ++i) {
8803 ch = PyUnicode_READ(kind, data, i);
8804 fixed = 0;
8805 if (ch > 127) {
8806 if (Py_UNICODE_ISSPACE(ch))
8807 fixed = ' ';
8808 else {
8809 const int decimal = Py_UNICODE_TODECIMAL(ch);
8810 if (decimal >= 0)
8811 fixed = '0' + decimal;
8812 }
8813 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008814 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008815 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008816 PyUnicode_WRITE(kind, data, i, fixed);
8817 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008818 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008819 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008821 }
8822
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008823 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008824}
8825
8826PyObject *
8827_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8828{
8829 if (!PyUnicode_Check(unicode)) {
8830 PyErr_BadInternalCall();
8831 return NULL;
8832 }
8833 if (PyUnicode_READY(unicode) == -1)
8834 return NULL;
8835 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8836 /* If the string is already ASCII, just return the same string */
8837 Py_INCREF(unicode);
8838 return unicode;
8839 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008840 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841}
8842
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008843PyObject *
8844PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8845 Py_ssize_t length)
8846{
Victor Stinnerf0124502011-11-21 23:12:56 +01008847 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008848 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008849 Py_UCS4 maxchar;
8850 enum PyUnicode_Kind kind;
8851 void *data;
8852
Victor Stinner99d7ad02012-02-22 13:37:39 +01008853 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008854 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008855 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008856 if (ch > 127) {
8857 int decimal = Py_UNICODE_TODECIMAL(ch);
8858 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008859 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008860 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008861 }
8862 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008863
8864 /* Copy to a new string */
8865 decimal = PyUnicode_New(length, maxchar);
8866 if (decimal == NULL)
8867 return decimal;
8868 kind = PyUnicode_KIND(decimal);
8869 data = PyUnicode_DATA(decimal);
8870 /* Iterate over code points */
8871 for (i = 0; i < length; i++) {
8872 Py_UNICODE ch = s[i];
8873 if (ch > 127) {
8874 int decimal = Py_UNICODE_TODECIMAL(ch);
8875 if (decimal >= 0)
8876 ch = '0' + decimal;
8877 }
8878 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008879 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008880 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008881}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008882/* --- Decimal Encoder ---------------------------------------------------- */
8883
Alexander Belopolsky40018472011-02-26 01:02:56 +00008884int
8885PyUnicode_EncodeDecimal(Py_UNICODE *s,
8886 Py_ssize_t length,
8887 char *output,
8888 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008889{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008890 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008891 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008892 enum PyUnicode_Kind kind;
8893 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008894
8895 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008896 PyErr_BadArgument();
8897 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008898 }
8899
Victor Stinner42bf7752011-11-21 22:52:58 +01008900 unicode = PyUnicode_FromUnicode(s, length);
8901 if (unicode == NULL)
8902 return -1;
8903
Benjamin Petersonbac79492012-01-14 13:34:47 -05008904 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008905 Py_DECREF(unicode);
8906 return -1;
8907 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008908 kind = PyUnicode_KIND(unicode);
8909 data = PyUnicode_DATA(unicode);
8910
Victor Stinnerb84d7232011-11-22 01:50:07 +01008911 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008912 PyObject *exc;
8913 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008914 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008915 Py_ssize_t startpos;
8916
8917 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008918
Benjamin Peterson29060642009-01-31 22:14:21 +00008919 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008920 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008921 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008922 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008923 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 decimal = Py_UNICODE_TODECIMAL(ch);
8925 if (decimal >= 0) {
8926 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008927 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 continue;
8929 }
8930 if (0 < ch && ch < 256) {
8931 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008932 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008933 continue;
8934 }
Victor Stinner6345be92011-11-25 20:09:01 +01008935
Victor Stinner42bf7752011-11-21 22:52:58 +01008936 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008937 exc = NULL;
8938 raise_encode_exception(&exc, "decimal", unicode,
8939 startpos, startpos+1,
8940 "invalid decimal Unicode string");
8941 Py_XDECREF(exc);
8942 Py_DECREF(unicode);
8943 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008944 }
8945 /* 0-terminate the output string */
8946 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008947 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008948 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008949}
8950
Guido van Rossumd57fd912000-03-10 22:53:23 +00008951/* --- Helpers ------------------------------------------------------------ */
8952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008953static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008954any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008955 Py_ssize_t start,
8956 Py_ssize_t end)
8957{
8958 int kind1, kind2, kind;
8959 void *buf1, *buf2;
8960 Py_ssize_t len1, len2, result;
8961
8962 kind1 = PyUnicode_KIND(s1);
8963 kind2 = PyUnicode_KIND(s2);
8964 kind = kind1 > kind2 ? kind1 : kind2;
8965 buf1 = PyUnicode_DATA(s1);
8966 buf2 = PyUnicode_DATA(s2);
8967 if (kind1 != kind)
8968 buf1 = _PyUnicode_AsKind(s1, kind);
8969 if (!buf1)
8970 return -2;
8971 if (kind2 != kind)
8972 buf2 = _PyUnicode_AsKind(s2, kind);
8973 if (!buf2) {
8974 if (kind1 != kind) PyMem_Free(buf1);
8975 return -2;
8976 }
8977 len1 = PyUnicode_GET_LENGTH(s1);
8978 len2 = PyUnicode_GET_LENGTH(s2);
8979
Victor Stinner794d5672011-10-10 03:21:36 +02008980 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008981 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008982 case PyUnicode_1BYTE_KIND:
8983 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8984 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8985 else
8986 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8987 break;
8988 case PyUnicode_2BYTE_KIND:
8989 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8990 break;
8991 case PyUnicode_4BYTE_KIND:
8992 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8993 break;
8994 default:
8995 assert(0); result = -2;
8996 }
8997 }
8998 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008999 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009000 case PyUnicode_1BYTE_KIND:
9001 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9002 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9003 else
9004 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9005 break;
9006 case PyUnicode_2BYTE_KIND:
9007 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9008 break;
9009 case PyUnicode_4BYTE_KIND:
9010 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9011 break;
9012 default:
9013 assert(0); result = -2;
9014 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015 }
9016
9017 if (kind1 != kind)
9018 PyMem_Free(buf1);
9019 if (kind2 != kind)
9020 PyMem_Free(buf2);
9021
9022 return result;
9023}
9024
9025Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009026_PyUnicode_InsertThousandsGrouping(
9027 PyObject *unicode, Py_ssize_t index,
9028 Py_ssize_t n_buffer,
9029 void *digits, Py_ssize_t n_digits,
9030 Py_ssize_t min_width,
9031 const char *grouping, PyObject *thousands_sep,
9032 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009033{
Victor Stinner41a863c2012-02-24 00:37:51 +01009034 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009035 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009036 Py_ssize_t thousands_sep_len;
9037 Py_ssize_t len;
9038
9039 if (unicode != NULL) {
9040 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009041 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009042 }
9043 else {
9044 kind = PyUnicode_1BYTE_KIND;
9045 data = NULL;
9046 }
9047 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9048 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9049 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9050 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009051 if (thousands_sep_kind < kind) {
9052 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9053 if (!thousands_sep_data)
9054 return -1;
9055 }
9056 else {
9057 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9058 if (!data)
9059 return -1;
9060 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009061 }
9062
Benjamin Petersonead6b532011-12-20 17:23:42 -06009063 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009065 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009066 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009067 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009068 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009069 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009070 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009071 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009072 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009073 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009074 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009075 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009077 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009078 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009079 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009080 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009081 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009082 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009083 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009084 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009085 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009086 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009087 break;
9088 default:
9089 assert(0);
9090 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009092 if (unicode != NULL && thousands_sep_kind != kind) {
9093 if (thousands_sep_kind < kind)
9094 PyMem_Free(thousands_sep_data);
9095 else
9096 PyMem_Free(data);
9097 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009098 if (unicode == NULL) {
9099 *maxchar = 127;
9100 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009101 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009102 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009103 }
9104 }
9105 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106}
9107
9108
Thomas Wouters477c8d52006-05-27 19:21:47 +00009109/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009110#define ADJUST_INDICES(start, end, len) \
9111 if (end > len) \
9112 end = len; \
9113 else if (end < 0) { \
9114 end += len; \
9115 if (end < 0) \
9116 end = 0; \
9117 } \
9118 if (start < 0) { \
9119 start += len; \
9120 if (start < 0) \
9121 start = 0; \
9122 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009123
Alexander Belopolsky40018472011-02-26 01:02:56 +00009124Py_ssize_t
9125PyUnicode_Count(PyObject *str,
9126 PyObject *substr,
9127 Py_ssize_t start,
9128 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009130 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009131 PyObject* str_obj;
9132 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 int kind1, kind2, kind;
9134 void *buf1 = NULL, *buf2 = NULL;
9135 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009136
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009137 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009138 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009139 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009140 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009141 if (!sub_obj) {
9142 Py_DECREF(str_obj);
9143 return -1;
9144 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009145 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009146 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 Py_DECREF(str_obj);
9148 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009149 }
Tim Petersced69f82003-09-16 20:30:58 +00009150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009151 kind1 = PyUnicode_KIND(str_obj);
9152 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009153 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009154 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009155 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009156 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009157 if (kind2 > kind) {
9158 Py_DECREF(sub_obj);
9159 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009160 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009161 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009162 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009163 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 if (!buf2)
9165 goto onError;
9166 len1 = PyUnicode_GET_LENGTH(str_obj);
9167 len2 = PyUnicode_GET_LENGTH(sub_obj);
9168
9169 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009170 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009172 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9173 result = asciilib_count(
9174 ((Py_UCS1*)buf1) + start, end - start,
9175 buf2, len2, PY_SSIZE_T_MAX
9176 );
9177 else
9178 result = ucs1lib_count(
9179 ((Py_UCS1*)buf1) + start, end - start,
9180 buf2, len2, PY_SSIZE_T_MAX
9181 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 break;
9183 case PyUnicode_2BYTE_KIND:
9184 result = ucs2lib_count(
9185 ((Py_UCS2*)buf1) + start, end - start,
9186 buf2, len2, PY_SSIZE_T_MAX
9187 );
9188 break;
9189 case PyUnicode_4BYTE_KIND:
9190 result = ucs4lib_count(
9191 ((Py_UCS4*)buf1) + start, end - start,
9192 buf2, len2, PY_SSIZE_T_MAX
9193 );
9194 break;
9195 default:
9196 assert(0); result = 0;
9197 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009198
9199 Py_DECREF(sub_obj);
9200 Py_DECREF(str_obj);
9201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 if (kind2 != kind)
9203 PyMem_Free(buf2);
9204
Guido van Rossumd57fd912000-03-10 22:53:23 +00009205 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 onError:
9207 Py_DECREF(sub_obj);
9208 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 if (kind2 != kind && buf2)
9210 PyMem_Free(buf2);
9211 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009212}
9213
Alexander Belopolsky40018472011-02-26 01:02:56 +00009214Py_ssize_t
9215PyUnicode_Find(PyObject *str,
9216 PyObject *sub,
9217 Py_ssize_t start,
9218 Py_ssize_t end,
9219 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009220{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009221 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009222
Guido van Rossumd57fd912000-03-10 22:53:23 +00009223 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009224 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009225 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009226 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009227 if (!sub) {
9228 Py_DECREF(str);
9229 return -2;
9230 }
9231 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9232 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009233 Py_DECREF(str);
9234 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009235 }
Tim Petersced69f82003-09-16 20:30:58 +00009236
Victor Stinner794d5672011-10-10 03:21:36 +02009237 result = any_find_slice(direction,
9238 str, sub, start, end
9239 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009240
Guido van Rossumd57fd912000-03-10 22:53:23 +00009241 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009242 Py_DECREF(sub);
9243
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244 return result;
9245}
9246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247Py_ssize_t
9248PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9249 Py_ssize_t start, Py_ssize_t end,
9250 int direction)
9251{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009253 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 if (PyUnicode_READY(str) == -1)
9255 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009256 if (start < 0 || end < 0) {
9257 PyErr_SetString(PyExc_IndexError, "string index out of range");
9258 return -2;
9259 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260 if (end > PyUnicode_GET_LENGTH(str))
9261 end = PyUnicode_GET_LENGTH(str);
9262 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009263 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9264 kind, end-start, ch, direction);
9265 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009266 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009267 else
9268 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269}
9270
Alexander Belopolsky40018472011-02-26 01:02:56 +00009271static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009272tailmatch(PyObject *self,
9273 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009274 Py_ssize_t start,
9275 Py_ssize_t end,
9276 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009277{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009278 int kind_self;
9279 int kind_sub;
9280 void *data_self;
9281 void *data_sub;
9282 Py_ssize_t offset;
9283 Py_ssize_t i;
9284 Py_ssize_t end_sub;
9285
9286 if (PyUnicode_READY(self) == -1 ||
9287 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009288 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289
9290 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291 return 1;
9292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9294 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009296 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 kind_self = PyUnicode_KIND(self);
9299 data_self = PyUnicode_DATA(self);
9300 kind_sub = PyUnicode_KIND(substring);
9301 data_sub = PyUnicode_DATA(substring);
9302 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9303
9304 if (direction > 0)
9305 offset = end;
9306 else
9307 offset = start;
9308
9309 if (PyUnicode_READ(kind_self, data_self, offset) ==
9310 PyUnicode_READ(kind_sub, data_sub, 0) &&
9311 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9312 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9313 /* If both are of the same kind, memcmp is sufficient */
9314 if (kind_self == kind_sub) {
9315 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009316 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317 data_sub,
9318 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009319 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 }
9321 /* otherwise we have to compare each character by first accesing it */
9322 else {
9323 /* We do not need to compare 0 and len(substring)-1 because
9324 the if statement above ensured already that they are equal
9325 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 for (i = 1; i < end_sub; ++i) {
9327 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9328 PyUnicode_READ(kind_sub, data_sub, i))
9329 return 0;
9330 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009331 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333 }
9334
9335 return 0;
9336}
9337
Alexander Belopolsky40018472011-02-26 01:02:56 +00009338Py_ssize_t
9339PyUnicode_Tailmatch(PyObject *str,
9340 PyObject *substr,
9341 Py_ssize_t start,
9342 Py_ssize_t end,
9343 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009345 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009346
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347 str = PyUnicode_FromObject(str);
9348 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009349 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350 substr = PyUnicode_FromObject(substr);
9351 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 Py_DECREF(str);
9353 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354 }
Tim Petersced69f82003-09-16 20:30:58 +00009355
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009356 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009357 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358 Py_DECREF(str);
9359 Py_DECREF(substr);
9360 return result;
9361}
9362
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363/* Apply fixfct filter to the Unicode object self and return a
9364 reference to the modified object */
9365
Alexander Belopolsky40018472011-02-26 01:02:56 +00009366static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009367fixup(PyObject *self,
9368 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 PyObject *u;
9371 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009372 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009374 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009376 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009377 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 /* fix functions return the new maximum character in a string,
9380 if the kind of the resulting unicode object does not change,
9381 everything is fine. Otherwise we need to change the string kind
9382 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009383 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009384
9385 if (maxchar_new == 0) {
9386 /* no changes */;
9387 if (PyUnicode_CheckExact(self)) {
9388 Py_DECREF(u);
9389 Py_INCREF(self);
9390 return self;
9391 }
9392 else
9393 return u;
9394 }
9395
Victor Stinnere6abb482012-05-02 01:15:40 +02009396 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397
Victor Stinnereaab6042011-12-11 22:22:39 +01009398 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009399 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009400
9401 /* In case the maximum character changed, we need to
9402 convert the string to the new category. */
9403 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9404 if (v == NULL) {
9405 Py_DECREF(u);
9406 return NULL;
9407 }
9408 if (maxchar_new > maxchar_old) {
9409 /* If the maxchar increased so that the kind changed, not all
9410 characters are representable anymore and we need to fix the
9411 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009412 _PyUnicode_FastCopyCharacters(v, 0,
9413 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009414 maxchar_old = fixfct(v);
9415 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 }
9417 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009418 _PyUnicode_FastCopyCharacters(v, 0,
9419 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009421 Py_DECREF(u);
9422 assert(_PyUnicode_CheckConsistency(v, 1));
9423 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424}
9425
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009426static PyObject *
9427ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009429 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9430 char *resdata, *data = PyUnicode_DATA(self);
9431 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009432
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009433 res = PyUnicode_New(len, 127);
9434 if (res == NULL)
9435 return NULL;
9436 resdata = PyUnicode_DATA(res);
9437 if (lower)
9438 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009440 _Py_bytes_upper(resdata, data, len);
9441 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442}
9443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009445handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009446{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009447 Py_ssize_t j;
9448 int final_sigma;
9449 Py_UCS4 c;
9450 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009451
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009452 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9453
9454 where ! is a negation and \p{xxx} is a character with property xxx.
9455 */
9456 for (j = i - 1; j >= 0; j--) {
9457 c = PyUnicode_READ(kind, data, j);
9458 if (!_PyUnicode_IsCaseIgnorable(c))
9459 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009461 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9462 if (final_sigma) {
9463 for (j = i + 1; j < length; j++) {
9464 c = PyUnicode_READ(kind, data, j);
9465 if (!_PyUnicode_IsCaseIgnorable(c))
9466 break;
9467 }
9468 final_sigma = j == length || !_PyUnicode_IsCased(c);
9469 }
9470 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009471}
9472
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009473static int
9474lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9475 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009476{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009477 /* Obscure special case. */
9478 if (c == 0x3A3) {
9479 mapped[0] = handle_capital_sigma(kind, data, length, i);
9480 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009482 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483}
9484
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009485static Py_ssize_t
9486do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009488 Py_ssize_t i, k = 0;
9489 int n_res, j;
9490 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009491
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009492 c = PyUnicode_READ(kind, data, 0);
9493 n_res = _PyUnicode_ToUpperFull(c, mapped);
9494 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009495 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009496 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009498 for (i = 1; i < length; i++) {
9499 c = PyUnicode_READ(kind, data, i);
9500 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9501 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009502 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009503 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009504 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009505 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009506 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507}
9508
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009509static Py_ssize_t
9510do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9511 Py_ssize_t i, k = 0;
9512
9513 for (i = 0; i < length; i++) {
9514 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9515 int n_res, j;
9516 if (Py_UNICODE_ISUPPER(c)) {
9517 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9518 }
9519 else if (Py_UNICODE_ISLOWER(c)) {
9520 n_res = _PyUnicode_ToUpperFull(c, mapped);
9521 }
9522 else {
9523 n_res = 1;
9524 mapped[0] = c;
9525 }
9526 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009527 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009528 res[k++] = mapped[j];
9529 }
9530 }
9531 return k;
9532}
9533
9534static Py_ssize_t
9535do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9536 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009538 Py_ssize_t i, k = 0;
9539
9540 for (i = 0; i < length; i++) {
9541 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9542 int n_res, j;
9543 if (lower)
9544 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9545 else
9546 n_res = _PyUnicode_ToUpperFull(c, mapped);
9547 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009548 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009549 res[k++] = mapped[j];
9550 }
9551 }
9552 return k;
9553}
9554
9555static Py_ssize_t
9556do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9557{
9558 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9559}
9560
9561static Py_ssize_t
9562do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9563{
9564 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9565}
9566
Benjamin Petersone51757f2012-01-12 21:10:29 -05009567static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009568do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9569{
9570 Py_ssize_t i, k = 0;
9571
9572 for (i = 0; i < length; i++) {
9573 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9574 Py_UCS4 mapped[3];
9575 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9576 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009577 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009578 res[k++] = mapped[j];
9579 }
9580 }
9581 return k;
9582}
9583
9584static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009585do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9586{
9587 Py_ssize_t i, k = 0;
9588 int previous_is_cased;
9589
9590 previous_is_cased = 0;
9591 for (i = 0; i < length; i++) {
9592 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9593 Py_UCS4 mapped[3];
9594 int n_res, j;
9595
9596 if (previous_is_cased)
9597 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9598 else
9599 n_res = _PyUnicode_ToTitleFull(c, mapped);
9600
9601 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009602 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009603 res[k++] = mapped[j];
9604 }
9605
9606 previous_is_cased = _PyUnicode_IsCased(c);
9607 }
9608 return k;
9609}
9610
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611static PyObject *
9612case_operation(PyObject *self,
9613 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9614{
9615 PyObject *res = NULL;
9616 Py_ssize_t length, newlength = 0;
9617 int kind, outkind;
9618 void *data, *outdata;
9619 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9620
Benjamin Petersoneea48462012-01-16 14:28:50 -05009621 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009622
9623 kind = PyUnicode_KIND(self);
9624 data = PyUnicode_DATA(self);
9625 length = PyUnicode_GET_LENGTH(self);
9626 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9627 if (tmp == NULL)
9628 return PyErr_NoMemory();
9629 newlength = perform(kind, data, length, tmp, &maxchar);
9630 res = PyUnicode_New(newlength, maxchar);
9631 if (res == NULL)
9632 goto leave;
9633 tmpend = tmp + newlength;
9634 outdata = PyUnicode_DATA(res);
9635 outkind = PyUnicode_KIND(res);
9636 switch (outkind) {
9637 case PyUnicode_1BYTE_KIND:
9638 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9639 break;
9640 case PyUnicode_2BYTE_KIND:
9641 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9642 break;
9643 case PyUnicode_4BYTE_KIND:
9644 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9645 break;
9646 default:
9647 assert(0);
9648 break;
9649 }
9650 leave:
9651 PyMem_FREE(tmp);
9652 return res;
9653}
9654
Tim Peters8ce9f162004-08-27 01:49:32 +00009655PyObject *
9656PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009659 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009661 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009662 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9663 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009664 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009666 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009668 int use_memcpy;
9669 unsigned char *res_data = NULL, *sep_data = NULL;
9670 PyObject *last_obj;
9671 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672
Tim Peters05eba1f2004-08-27 21:32:02 +00009673 fseq = PySequence_Fast(seq, "");
9674 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009675 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009676 }
9677
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009678 /* NOTE: the following code can't call back into Python code,
9679 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009680 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009681
Tim Peters05eba1f2004-08-27 21:32:02 +00009682 seqlen = PySequence_Fast_GET_SIZE(fseq);
9683 /* If empty sequence, return u"". */
9684 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009685 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009686 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009687 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009688
Tim Peters05eba1f2004-08-27 21:32:02 +00009689 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009690 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009691 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009692 if (seqlen == 1) {
9693 if (PyUnicode_CheckExact(items[0])) {
9694 res = items[0];
9695 Py_INCREF(res);
9696 Py_DECREF(fseq);
9697 return res;
9698 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009699 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009700 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009701 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009702 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009703 /* Set up sep and seplen */
9704 if (separator == NULL) {
9705 /* fall back to a blank space separator */
9706 sep = PyUnicode_FromOrdinal(' ');
9707 if (!sep)
9708 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009709 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009710 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009711 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009712 else {
9713 if (!PyUnicode_Check(separator)) {
9714 PyErr_Format(PyExc_TypeError,
9715 "separator: expected str instance,"
9716 " %.80s found",
9717 Py_TYPE(separator)->tp_name);
9718 goto onError;
9719 }
9720 if (PyUnicode_READY(separator))
9721 goto onError;
9722 sep = separator;
9723 seplen = PyUnicode_GET_LENGTH(separator);
9724 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9725 /* inc refcount to keep this code path symmetric with the
9726 above case of a blank separator */
9727 Py_INCREF(sep);
9728 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009729 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009730 }
9731
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009732 /* There are at least two things to join, or else we have a subclass
9733 * of str in the sequence.
9734 * Do a pre-pass to figure out the total amount of space we'll
9735 * need (sz), and see whether all argument are strings.
9736 */
9737 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009738#ifdef Py_DEBUG
9739 use_memcpy = 0;
9740#else
9741 use_memcpy = 1;
9742#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009743 for (i = 0; i < seqlen; i++) {
9744 const Py_ssize_t old_sz = sz;
9745 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009746 if (!PyUnicode_Check(item)) {
9747 PyErr_Format(PyExc_TypeError,
9748 "sequence item %zd: expected str instance,"
9749 " %.80s found",
9750 i, Py_TYPE(item)->tp_name);
9751 goto onError;
9752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 if (PyUnicode_READY(item) == -1)
9754 goto onError;
9755 sz += PyUnicode_GET_LENGTH(item);
9756 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009757 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009758 if (i != 0)
9759 sz += seplen;
9760 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9761 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009762 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 goto onError;
9764 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009765 if (use_memcpy && last_obj != NULL) {
9766 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9767 use_memcpy = 0;
9768 }
9769 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009770 }
Tim Petersced69f82003-09-16 20:30:58 +00009771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009772 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009773 if (res == NULL)
9774 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009775
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009776 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009777#ifdef Py_DEBUG
9778 use_memcpy = 0;
9779#else
9780 if (use_memcpy) {
9781 res_data = PyUnicode_1BYTE_DATA(res);
9782 kind = PyUnicode_KIND(res);
9783 if (seplen != 0)
9784 sep_data = PyUnicode_1BYTE_DATA(sep);
9785 }
9786#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009787 if (use_memcpy) {
9788 for (i = 0; i < seqlen; ++i) {
9789 Py_ssize_t itemlen;
9790 item = items[i];
9791
9792 /* Copy item, and maybe the separator. */
9793 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009794 Py_MEMCPY(res_data,
9795 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009796 kind * seplen);
9797 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009798 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009799
9800 itemlen = PyUnicode_GET_LENGTH(item);
9801 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009802 Py_MEMCPY(res_data,
9803 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009804 kind * itemlen);
9805 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009806 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009807 }
9808 assert(res_data == PyUnicode_1BYTE_DATA(res)
9809 + kind * PyUnicode_GET_LENGTH(res));
9810 }
9811 else {
9812 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9813 Py_ssize_t itemlen;
9814 item = items[i];
9815
9816 /* Copy item, and maybe the separator. */
9817 if (i && seplen != 0) {
9818 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9819 res_offset += seplen;
9820 }
9821
9822 itemlen = PyUnicode_GET_LENGTH(item);
9823 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009824 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009825 res_offset += itemlen;
9826 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009827 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009828 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009829 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009830
Tim Peters05eba1f2004-08-27 21:32:02 +00009831 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009833 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009834 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835
Benjamin Peterson29060642009-01-31 22:14:21 +00009836 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009837 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009839 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840 return NULL;
9841}
9842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843#define FILL(kind, data, value, start, length) \
9844 do { \
9845 Py_ssize_t i_ = 0; \
9846 assert(kind != PyUnicode_WCHAR_KIND); \
9847 switch ((kind)) { \
9848 case PyUnicode_1BYTE_KIND: { \
9849 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009850 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 break; \
9852 } \
9853 case PyUnicode_2BYTE_KIND: { \
9854 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9855 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9856 break; \
9857 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009858 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9860 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9861 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009862 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863 } \
9864 } \
9865 } while (0)
9866
Victor Stinnerd3f08822012-05-29 12:57:52 +02009867void
9868_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9869 Py_UCS4 fill_char)
9870{
9871 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9872 const void *data = PyUnicode_DATA(unicode);
9873 assert(PyUnicode_IS_READY(unicode));
9874 assert(unicode_modifiable(unicode));
9875 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9876 assert(start >= 0);
9877 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9878 FILL(kind, data, fill_char, start, length);
9879}
9880
Victor Stinner3fe55312012-01-04 00:33:50 +01009881Py_ssize_t
9882PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9883 Py_UCS4 fill_char)
9884{
9885 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009886
9887 if (!PyUnicode_Check(unicode)) {
9888 PyErr_BadInternalCall();
9889 return -1;
9890 }
9891 if (PyUnicode_READY(unicode) == -1)
9892 return -1;
9893 if (unicode_check_modifiable(unicode))
9894 return -1;
9895
Victor Stinnerd3f08822012-05-29 12:57:52 +02009896 if (start < 0) {
9897 PyErr_SetString(PyExc_IndexError, "string index out of range");
9898 return -1;
9899 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009900 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9901 PyErr_SetString(PyExc_ValueError,
9902 "fill character is bigger than "
9903 "the string maximum character");
9904 return -1;
9905 }
9906
9907 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9908 length = Py_MIN(maxlen, length);
9909 if (length <= 0)
9910 return 0;
9911
Victor Stinnerd3f08822012-05-29 12:57:52 +02009912 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009913 return length;
9914}
9915
Victor Stinner9310abb2011-10-05 00:59:23 +02009916static PyObject *
9917pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009918 Py_ssize_t left,
9919 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009921{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 PyObject *u;
9923 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009924 int kind;
9925 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009926
9927 if (left < 0)
9928 left = 0;
9929 if (right < 0)
9930 right = 0;
9931
Victor Stinnerc4b49542011-12-11 22:44:26 +01009932 if (left == 0 && right == 0)
9933 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9936 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009937 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9938 return NULL;
9939 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009941 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009943 if (!u)
9944 return NULL;
9945
9946 kind = PyUnicode_KIND(u);
9947 data = PyUnicode_DATA(u);
9948 if (left)
9949 FILL(kind, data, fill, 0, left);
9950 if (right)
9951 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009952 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009953 assert(_PyUnicode_CheckConsistency(u, 1));
9954 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009955}
9956
Alexander Belopolsky40018472011-02-26 01:02:56 +00009957PyObject *
9958PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009961
9962 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009963 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009964 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009965 if (PyUnicode_READY(string) == -1) {
9966 Py_DECREF(string);
9967 return NULL;
9968 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009969
Benjamin Petersonead6b532011-12-20 17:23:42 -06009970 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009972 if (PyUnicode_IS_ASCII(string))
9973 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009974 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009975 PyUnicode_GET_LENGTH(string), keepends);
9976 else
9977 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009978 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009979 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009980 break;
9981 case PyUnicode_2BYTE_KIND:
9982 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 PyUnicode_GET_LENGTH(string), keepends);
9985 break;
9986 case PyUnicode_4BYTE_KIND:
9987 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009988 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 PyUnicode_GET_LENGTH(string), keepends);
9990 break;
9991 default:
9992 assert(0);
9993 list = 0;
9994 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995 Py_DECREF(string);
9996 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009997}
9998
Alexander Belopolsky40018472011-02-26 01:02:56 +00009999static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010000split(PyObject *self,
10001 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010002 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 int kind1, kind2, kind;
10005 void *buf1, *buf2;
10006 Py_ssize_t len1, len2;
10007 PyObject* out;
10008
Guido van Rossumd57fd912000-03-10 22:53:23 +000010009 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010010 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 if (PyUnicode_READY(self) == -1)
10013 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010016 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010018 if (PyUnicode_IS_ASCII(self))
10019 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010020 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010021 PyUnicode_GET_LENGTH(self), maxcount
10022 );
10023 else
10024 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010025 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026 PyUnicode_GET_LENGTH(self), maxcount
10027 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 case PyUnicode_2BYTE_KIND:
10029 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010030 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 PyUnicode_GET_LENGTH(self), maxcount
10032 );
10033 case PyUnicode_4BYTE_KIND:
10034 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010035 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 PyUnicode_GET_LENGTH(self), maxcount
10037 );
10038 default:
10039 assert(0);
10040 return NULL;
10041 }
10042
10043 if (PyUnicode_READY(substring) == -1)
10044 return NULL;
10045
10046 kind1 = PyUnicode_KIND(self);
10047 kind2 = PyUnicode_KIND(substring);
10048 kind = kind1 > kind2 ? kind1 : kind2;
10049 buf1 = PyUnicode_DATA(self);
10050 buf2 = PyUnicode_DATA(substring);
10051 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 if (!buf1)
10054 return NULL;
10055 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010056 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 if (!buf2) {
10058 if (kind1 != kind) PyMem_Free(buf1);
10059 return NULL;
10060 }
10061 len1 = PyUnicode_GET_LENGTH(self);
10062 len2 = PyUnicode_GET_LENGTH(substring);
10063
Benjamin Petersonead6b532011-12-20 17:23:42 -060010064 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010066 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10067 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010068 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010069 else
10070 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010071 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 break;
10073 case PyUnicode_2BYTE_KIND:
10074 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010075 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 break;
10077 case PyUnicode_4BYTE_KIND:
10078 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010079 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 break;
10081 default:
10082 out = NULL;
10083 }
10084 if (kind1 != kind)
10085 PyMem_Free(buf1);
10086 if (kind2 != kind)
10087 PyMem_Free(buf2);
10088 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010089}
10090
Alexander Belopolsky40018472011-02-26 01:02:56 +000010091static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010092rsplit(PyObject *self,
10093 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010094 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 int kind1, kind2, kind;
10097 void *buf1, *buf2;
10098 Py_ssize_t len1, len2;
10099 PyObject* out;
10100
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010101 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010102 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 if (PyUnicode_READY(self) == -1)
10105 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010108 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010110 if (PyUnicode_IS_ASCII(self))
10111 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010112 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010113 PyUnicode_GET_LENGTH(self), maxcount
10114 );
10115 else
10116 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010117 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010118 PyUnicode_GET_LENGTH(self), maxcount
10119 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 case PyUnicode_2BYTE_KIND:
10121 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010122 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 PyUnicode_GET_LENGTH(self), maxcount
10124 );
10125 case PyUnicode_4BYTE_KIND:
10126 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 PyUnicode_GET_LENGTH(self), maxcount
10129 );
10130 default:
10131 assert(0);
10132 return NULL;
10133 }
10134
10135 if (PyUnicode_READY(substring) == -1)
10136 return NULL;
10137
10138 kind1 = PyUnicode_KIND(self);
10139 kind2 = PyUnicode_KIND(substring);
10140 kind = kind1 > kind2 ? kind1 : kind2;
10141 buf1 = PyUnicode_DATA(self);
10142 buf2 = PyUnicode_DATA(substring);
10143 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010144 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 if (!buf1)
10146 return NULL;
10147 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010148 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 if (!buf2) {
10150 if (kind1 != kind) PyMem_Free(buf1);
10151 return NULL;
10152 }
10153 len1 = PyUnicode_GET_LENGTH(self);
10154 len2 = PyUnicode_GET_LENGTH(substring);
10155
Benjamin Petersonead6b532011-12-20 17:23:42 -060010156 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010158 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10159 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010160 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010161 else
10162 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010163 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 break;
10165 case PyUnicode_2BYTE_KIND:
10166 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 break;
10169 case PyUnicode_4BYTE_KIND:
10170 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010171 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 break;
10173 default:
10174 out = NULL;
10175 }
10176 if (kind1 != kind)
10177 PyMem_Free(buf1);
10178 if (kind2 != kind)
10179 PyMem_Free(buf2);
10180 return out;
10181}
10182
10183static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010184anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10185 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010187 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10190 return asciilib_find(buf1, len1, buf2, len2, offset);
10191 else
10192 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 case PyUnicode_2BYTE_KIND:
10194 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10195 case PyUnicode_4BYTE_KIND:
10196 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10197 }
10198 assert(0);
10199 return -1;
10200}
10201
10202static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010203anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10204 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010206 switch (kind) {
10207 case PyUnicode_1BYTE_KIND:
10208 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10209 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10210 else
10211 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10212 case PyUnicode_2BYTE_KIND:
10213 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10214 case PyUnicode_4BYTE_KIND:
10215 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10216 }
10217 assert(0);
10218 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010219}
10220
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010221static void
10222replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10223 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10224{
10225 int kind = PyUnicode_KIND(u);
10226 void *data = PyUnicode_DATA(u);
10227 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10228 if (kind == PyUnicode_1BYTE_KIND) {
10229 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10230 (Py_UCS1 *)data + len,
10231 u1, u2, maxcount);
10232 }
10233 else if (kind == PyUnicode_2BYTE_KIND) {
10234 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10235 (Py_UCS2 *)data + len,
10236 u1, u2, maxcount);
10237 }
10238 else {
10239 assert(kind == PyUnicode_4BYTE_KIND);
10240 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10241 (Py_UCS4 *)data + len,
10242 u1, u2, maxcount);
10243 }
10244}
10245
Alexander Belopolsky40018472011-02-26 01:02:56 +000010246static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247replace(PyObject *self, PyObject *str1,
10248 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010249{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 PyObject *u;
10251 char *sbuf = PyUnicode_DATA(self);
10252 char *buf1 = PyUnicode_DATA(str1);
10253 char *buf2 = PyUnicode_DATA(str2);
10254 int srelease = 0, release1 = 0, release2 = 0;
10255 int skind = PyUnicode_KIND(self);
10256 int kind1 = PyUnicode_KIND(str1);
10257 int kind2 = PyUnicode_KIND(str2);
10258 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10259 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10260 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010261 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010262 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010263
10264 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010265 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010267 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268
Victor Stinner59de0ee2011-10-07 10:01:28 +020010269 if (str1 == str2)
10270 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271
Victor Stinner49a0a212011-10-12 23:46:10 +020010272 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010273 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10274 if (maxchar < maxchar_str1)
10275 /* substring too wide to be present */
10276 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010277 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10278 /* Replacing str1 with str2 may cause a maxchar reduction in the
10279 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010280 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010281 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010284 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010286 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010289 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010290 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010291
Victor Stinner69ed0f42013-04-09 21:48:24 +020010292 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010293 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010294 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010295 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010296 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010298 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010300
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010301 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10302 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010303 }
10304 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 int rkind = skind;
10306 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010307 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 if (kind1 < rkind) {
10310 /* widen substring */
10311 buf1 = _PyUnicode_AsKind(str1, rkind);
10312 if (!buf1) goto error;
10313 release1 = 1;
10314 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010315 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010316 if (i < 0)
10317 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 if (rkind > kind2) {
10319 /* widen replacement */
10320 buf2 = _PyUnicode_AsKind(str2, rkind);
10321 if (!buf2) goto error;
10322 release2 = 1;
10323 }
10324 else if (rkind < kind2) {
10325 /* widen self and buf1 */
10326 rkind = kind2;
10327 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010328 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 sbuf = _PyUnicode_AsKind(self, rkind);
10330 if (!sbuf) goto error;
10331 srelease = 1;
10332 buf1 = _PyUnicode_AsKind(str1, rkind);
10333 if (!buf1) goto error;
10334 release1 = 1;
10335 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010336 u = PyUnicode_New(slen, maxchar);
10337 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010339 assert(PyUnicode_KIND(u) == rkind);
10340 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010341
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010342 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010343 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010344 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010346 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010348
10349 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010350 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010351 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010352 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010353 if (i == -1)
10354 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010355 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010357 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010360 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010361 }
10362 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010364 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 int rkind = skind;
10366 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010369 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 buf1 = _PyUnicode_AsKind(str1, rkind);
10371 if (!buf1) goto error;
10372 release1 = 1;
10373 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010374 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010375 if (n == 0)
10376 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010378 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 buf2 = _PyUnicode_AsKind(str2, rkind);
10380 if (!buf2) goto error;
10381 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010384 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 rkind = kind2;
10386 sbuf = _PyUnicode_AsKind(self, rkind);
10387 if (!sbuf) goto error;
10388 srelease = 1;
10389 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010390 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 buf1 = _PyUnicode_AsKind(str1, rkind);
10392 if (!buf1) goto error;
10393 release1 = 1;
10394 }
10395 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10396 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010397 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 PyErr_SetString(PyExc_OverflowError,
10399 "replace string is too long");
10400 goto error;
10401 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010402 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010403 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010404 _Py_INCREF_UNICODE_EMPTY();
10405 if (!unicode_empty)
10406 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010407 u = unicode_empty;
10408 goto done;
10409 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010410 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 PyErr_SetString(PyExc_OverflowError,
10412 "replace string is too long");
10413 goto error;
10414 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010415 u = PyUnicode_New(new_size, maxchar);
10416 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010418 assert(PyUnicode_KIND(u) == rkind);
10419 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 ires = i = 0;
10421 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010422 while (n-- > 0) {
10423 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010424 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010425 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010426 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010427 if (j == -1)
10428 break;
10429 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010430 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010431 memcpy(res + rkind * ires,
10432 sbuf + rkind * i,
10433 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010435 }
10436 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010438 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010440 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010446 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010447 memcpy(res + rkind * ires,
10448 sbuf + rkind * i,
10449 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010450 }
10451 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010452 /* interleave */
10453 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010454 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010456 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010458 if (--n <= 0)
10459 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010460 memcpy(res + rkind * ires,
10461 sbuf + rkind * i,
10462 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 ires++;
10464 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010465 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010466 memcpy(res + rkind * ires,
10467 sbuf + rkind * i,
10468 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010469 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010470 }
10471
10472 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010473 unicode_adjust_maxchar(&u);
10474 if (u == NULL)
10475 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010476 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010477
10478 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 if (srelease)
10480 PyMem_FREE(sbuf);
10481 if (release1)
10482 PyMem_FREE(buf1);
10483 if (release2)
10484 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010485 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487
Benjamin Peterson29060642009-01-31 22:14:21 +000010488 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 if (srelease)
10491 PyMem_FREE(sbuf);
10492 if (release1)
10493 PyMem_FREE(buf1);
10494 if (release2)
10495 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010496 return unicode_result_unchanged(self);
10497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 error:
10499 if (srelease && sbuf)
10500 PyMem_FREE(sbuf);
10501 if (release1 && buf1)
10502 PyMem_FREE(buf1);
10503 if (release2 && buf2)
10504 PyMem_FREE(buf2);
10505 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506}
10507
10508/* --- Unicode Object Methods --------------------------------------------- */
10509
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010510PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010511 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512\n\
10513Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010514characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010515
10516static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010517unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010518{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010519 if (PyUnicode_READY(self) == -1)
10520 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010521 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010522}
10523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010524PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010525 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526\n\
10527Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010528have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529
10530static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010531unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010532{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010533 if (PyUnicode_READY(self) == -1)
10534 return NULL;
10535 if (PyUnicode_GET_LENGTH(self) == 0)
10536 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010537 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010538}
10539
Benjamin Petersond5890c82012-01-14 13:23:30 -050010540PyDoc_STRVAR(casefold__doc__,
10541 "S.casefold() -> str\n\
10542\n\
10543Return a version of S suitable for caseless comparisons.");
10544
10545static PyObject *
10546unicode_casefold(PyObject *self)
10547{
10548 if (PyUnicode_READY(self) == -1)
10549 return NULL;
10550 if (PyUnicode_IS_ASCII(self))
10551 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010552 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010553}
10554
10555
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010556/* Argument converter. Coerces to a single unicode character */
10557
10558static int
10559convert_uc(PyObject *obj, void *addr)
10560{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010562 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010563
Benjamin Peterson14339b62009-01-31 16:36:08 +000010564 uniobj = PyUnicode_FromObject(obj);
10565 if (uniobj == NULL) {
10566 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010567 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010568 return 0;
10569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010571 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010572 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010573 Py_DECREF(uniobj);
10574 return 0;
10575 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010577 Py_DECREF(uniobj);
10578 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010579}
10580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010581PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010582 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010584Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010585done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586
10587static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010588unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010589{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010590 Py_ssize_t marg, left;
10591 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 Py_UCS4 fillchar = ' ';
10593
Victor Stinnere9a29352011-10-01 02:14:59 +020010594 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596
Benjamin Petersonbac79492012-01-14 13:34:47 -050010597 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598 return NULL;
10599
Victor Stinnerc4b49542011-12-11 22:44:26 +010010600 if (PyUnicode_GET_LENGTH(self) >= width)
10601 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602
Victor Stinnerc4b49542011-12-11 22:44:26 +010010603 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604 left = marg / 2 + (marg & width & 1);
10605
Victor Stinner9310abb2011-10-05 00:59:23 +020010606 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607}
10608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609/* This function assumes that str1 and str2 are readied by the caller. */
10610
Marc-André Lemburge5034372000-08-08 08:04:29 +000010611static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010612unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010613{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010614#define COMPARE(TYPE1, TYPE2) \
10615 do { \
10616 TYPE1* p1 = (TYPE1 *)data1; \
10617 TYPE2* p2 = (TYPE2 *)data2; \
10618 TYPE1* end = p1 + len; \
10619 Py_UCS4 c1, c2; \
10620 for (; p1 != end; p1++, p2++) { \
10621 c1 = *p1; \
10622 c2 = *p2; \
10623 if (c1 != c2) \
10624 return (c1 < c2) ? -1 : 1; \
10625 } \
10626 } \
10627 while (0)
10628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 int kind1, kind2;
10630 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010631 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 kind1 = PyUnicode_KIND(str1);
10634 kind2 = PyUnicode_KIND(str2);
10635 data1 = PyUnicode_DATA(str1);
10636 data2 = PyUnicode_DATA(str2);
10637 len1 = PyUnicode_GET_LENGTH(str1);
10638 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010639 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010640
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010641 switch(kind1) {
10642 case PyUnicode_1BYTE_KIND:
10643 {
10644 switch(kind2) {
10645 case PyUnicode_1BYTE_KIND:
10646 {
10647 int cmp = memcmp(data1, data2, len);
10648 /* normalize result of memcmp() into the range [-1; 1] */
10649 if (cmp < 0)
10650 return -1;
10651 if (cmp > 0)
10652 return 1;
10653 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010654 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010655 case PyUnicode_2BYTE_KIND:
10656 COMPARE(Py_UCS1, Py_UCS2);
10657 break;
10658 case PyUnicode_4BYTE_KIND:
10659 COMPARE(Py_UCS1, Py_UCS4);
10660 break;
10661 default:
10662 assert(0);
10663 }
10664 break;
10665 }
10666 case PyUnicode_2BYTE_KIND:
10667 {
10668 switch(kind2) {
10669 case PyUnicode_1BYTE_KIND:
10670 COMPARE(Py_UCS2, Py_UCS1);
10671 break;
10672 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010673 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010674 COMPARE(Py_UCS2, Py_UCS2);
10675 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010676 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010677 case PyUnicode_4BYTE_KIND:
10678 COMPARE(Py_UCS2, Py_UCS4);
10679 break;
10680 default:
10681 assert(0);
10682 }
10683 break;
10684 }
10685 case PyUnicode_4BYTE_KIND:
10686 {
10687 switch(kind2) {
10688 case PyUnicode_1BYTE_KIND:
10689 COMPARE(Py_UCS4, Py_UCS1);
10690 break;
10691 case PyUnicode_2BYTE_KIND:
10692 COMPARE(Py_UCS4, Py_UCS2);
10693 break;
10694 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010695 {
10696#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10697 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10698 /* normalize result of wmemcmp() into the range [-1; 1] */
10699 if (cmp < 0)
10700 return -1;
10701 if (cmp > 0)
10702 return 1;
10703#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010704 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010705#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010706 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010707 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010708 default:
10709 assert(0);
10710 }
10711 break;
10712 }
10713 default:
10714 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010715 }
10716
Victor Stinner770e19e2012-10-04 22:59:45 +020010717 if (len1 == len2)
10718 return 0;
10719 if (len1 < len2)
10720 return -1;
10721 else
10722 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010723
10724#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010725}
10726
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010727Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010728unicode_compare_eq(PyObject *str1, PyObject *str2)
10729{
10730 int kind;
10731 void *data1, *data2;
10732 Py_ssize_t len;
10733 int cmp;
10734
Victor Stinnere5567ad2012-10-23 02:48:49 +020010735 len = PyUnicode_GET_LENGTH(str1);
10736 if (PyUnicode_GET_LENGTH(str2) != len)
10737 return 0;
10738 kind = PyUnicode_KIND(str1);
10739 if (PyUnicode_KIND(str2) != kind)
10740 return 0;
10741 data1 = PyUnicode_DATA(str1);
10742 data2 = PyUnicode_DATA(str2);
10743
10744 cmp = memcmp(data1, data2, len * kind);
10745 return (cmp == 0);
10746}
10747
10748
Alexander Belopolsky40018472011-02-26 01:02:56 +000010749int
10750PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10753 if (PyUnicode_READY(left) == -1 ||
10754 PyUnicode_READY(right) == -1)
10755 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010756
10757 /* a string is equal to itself */
10758 if (left == right)
10759 return 0;
10760
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010761 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010763 PyErr_Format(PyExc_TypeError,
10764 "Can't compare %.100s and %.100s",
10765 left->ob_type->tp_name,
10766 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767 return -1;
10768}
10769
Martin v. Löwis5b222132007-06-10 09:51:05 +000010770int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010771_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10772{
10773 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10774 if (right_str == NULL)
10775 return -1;
10776 return PyUnicode_Compare(left, right_str);
10777}
10778
10779int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010780PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 Py_ssize_t i;
10783 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 Py_UCS4 chr;
10785
Victor Stinner910337b2011-10-03 03:20:16 +020010786 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 if (PyUnicode_READY(uni) == -1)
10788 return -1;
10789 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010790 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010791 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010792 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010793 size_t len, len2 = strlen(str);
10794 int cmp;
10795
10796 len = Py_MIN(len1, len2);
10797 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010798 if (cmp != 0) {
10799 if (cmp < 0)
10800 return -1;
10801 else
10802 return 1;
10803 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010804 if (len1 > len2)
10805 return 1; /* uni is longer */
10806 if (len2 > len1)
10807 return -1; /* str is longer */
10808 return 0;
10809 }
10810 else {
10811 void *data = PyUnicode_DATA(uni);
10812 /* Compare Unicode string and source character set string */
10813 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10814 if (chr != str[i])
10815 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10816 /* This check keeps Python strings that end in '\0' from comparing equal
10817 to C strings identical up to that point. */
10818 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10819 return 1; /* uni is longer */
10820 if (str[i])
10821 return -1; /* str is longer */
10822 return 0;
10823 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010824}
10825
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010826
Benjamin Peterson29060642009-01-31 22:14:21 +000010827#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010828 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010829
Alexander Belopolsky40018472011-02-26 01:02:56 +000010830PyObject *
10831PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010832{
10833 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010834 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010835
Victor Stinnere5567ad2012-10-23 02:48:49 +020010836 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10837 Py_RETURN_NOTIMPLEMENTED;
10838
10839 if (PyUnicode_READY(left) == -1 ||
10840 PyUnicode_READY(right) == -1)
10841 return NULL;
10842
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010843 if (left == right) {
10844 switch (op) {
10845 case Py_EQ:
10846 case Py_LE:
10847 case Py_GE:
10848 /* a string is equal to itself */
10849 v = Py_True;
10850 break;
10851 case Py_NE:
10852 case Py_LT:
10853 case Py_GT:
10854 v = Py_False;
10855 break;
10856 default:
10857 PyErr_BadArgument();
10858 return NULL;
10859 }
10860 }
10861 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010862 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010863 result ^= (op == Py_NE);
10864 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010865 }
10866 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010867 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010868
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010869 /* Convert the return value to a Boolean */
10870 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010871 case Py_LE:
10872 v = TEST_COND(result <= 0);
10873 break;
10874 case Py_GE:
10875 v = TEST_COND(result >= 0);
10876 break;
10877 case Py_LT:
10878 v = TEST_COND(result == -1);
10879 break;
10880 case Py_GT:
10881 v = TEST_COND(result == 1);
10882 break;
10883 default:
10884 PyErr_BadArgument();
10885 return NULL;
10886 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010887 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010888 Py_INCREF(v);
10889 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010890}
10891
Alexander Belopolsky40018472011-02-26 01:02:56 +000010892int
10893PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010894{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010895 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010896 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010897 void *buf1, *buf2;
10898 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010899 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010900
10901 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010902 sub = PyUnicode_FromObject(element);
10903 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010904 PyErr_Format(PyExc_TypeError,
10905 "'in <string>' requires string as left operand, not %s",
10906 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010907 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010908 }
10909
Thomas Wouters477c8d52006-05-27 19:21:47 +000010910 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010911 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010912 Py_DECREF(sub);
10913 return -1;
10914 }
10915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010916 kind1 = PyUnicode_KIND(str);
10917 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 buf1 = PyUnicode_DATA(str);
10919 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010920 if (kind2 != kind1) {
10921 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010922 Py_DECREF(sub);
10923 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010924 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010925 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010926 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010927 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 if (!buf2) {
10929 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010930 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 return -1;
10932 }
10933 len1 = PyUnicode_GET_LENGTH(str);
10934 len2 = PyUnicode_GET_LENGTH(sub);
10935
Victor Stinner77282cb2013-04-14 19:22:47 +020010936 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 case PyUnicode_1BYTE_KIND:
10938 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10939 break;
10940 case PyUnicode_2BYTE_KIND:
10941 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10942 break;
10943 case PyUnicode_4BYTE_KIND:
10944 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10945 break;
10946 default:
10947 result = -1;
10948 assert(0);
10949 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010950
10951 Py_DECREF(str);
10952 Py_DECREF(sub);
10953
Victor Stinner77282cb2013-04-14 19:22:47 +020010954 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010955 PyMem_Free(buf2);
10956
Guido van Rossum403d68b2000-03-13 15:55:09 +000010957 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010958}
10959
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960/* Concat to string or Unicode object giving a new Unicode object. */
10961
Alexander Belopolsky40018472011-02-26 01:02:56 +000010962PyObject *
10963PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010965 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010966 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010967 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968
10969 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010970 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010971 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010972 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010973 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010975 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010976
10977 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010978 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010979 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010980 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010982 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010983 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985 }
10986
Victor Stinner488fa492011-12-12 00:01:39 +010010987 u_len = PyUnicode_GET_LENGTH(u);
10988 v_len = PyUnicode_GET_LENGTH(v);
10989 if (u_len > PY_SSIZE_T_MAX - v_len) {
10990 PyErr_SetString(PyExc_OverflowError,
10991 "strings are too large to concat");
10992 goto onError;
10993 }
10994 new_len = u_len + v_len;
10995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010997 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010998 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011001 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011003 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011004 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11005 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006 Py_DECREF(u);
11007 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011008 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010
Benjamin Peterson29060642009-01-31 22:14:21 +000011011 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012 Py_XDECREF(u);
11013 Py_XDECREF(v);
11014 return NULL;
11015}
11016
Walter Dörwald1ab83302007-05-18 17:15:44 +000011017void
Victor Stinner23e56682011-10-03 03:54:37 +020011018PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011019{
Victor Stinner23e56682011-10-03 03:54:37 +020011020 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011021 Py_UCS4 maxchar, maxchar2;
11022 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011023
11024 if (p_left == NULL) {
11025 if (!PyErr_Occurred())
11026 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011027 return;
11028 }
Victor Stinner23e56682011-10-03 03:54:37 +020011029 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011030 if (right == NULL || left == NULL
11031 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011032 if (!PyErr_Occurred())
11033 PyErr_BadInternalCall();
11034 goto error;
11035 }
11036
Benjamin Petersonbac79492012-01-14 13:34:47 -050011037 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011038 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011039 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011040 goto error;
11041
Victor Stinner488fa492011-12-12 00:01:39 +010011042 /* Shortcuts */
11043 if (left == unicode_empty) {
11044 Py_DECREF(left);
11045 Py_INCREF(right);
11046 *p_left = right;
11047 return;
11048 }
11049 if (right == unicode_empty)
11050 return;
11051
11052 left_len = PyUnicode_GET_LENGTH(left);
11053 right_len = PyUnicode_GET_LENGTH(right);
11054 if (left_len > PY_SSIZE_T_MAX - right_len) {
11055 PyErr_SetString(PyExc_OverflowError,
11056 "strings are too large to concat");
11057 goto error;
11058 }
11059 new_len = left_len + right_len;
11060
11061 if (unicode_modifiable(left)
11062 && PyUnicode_CheckExact(right)
11063 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011064 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11065 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011066 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011067 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011068 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11069 {
11070 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011071 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011072 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011073
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011074 /* copy 'right' into the newly allocated area of 'left' */
11075 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011076 }
Victor Stinner488fa492011-12-12 00:01:39 +010011077 else {
11078 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11079 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011080 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011081
Victor Stinner488fa492011-12-12 00:01:39 +010011082 /* Concat the two Unicode strings */
11083 res = PyUnicode_New(new_len, maxchar);
11084 if (res == NULL)
11085 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011086 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11087 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011088 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011089 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011090 }
11091 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011092 return;
11093
11094error:
Victor Stinner488fa492011-12-12 00:01:39 +010011095 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011096}
11097
11098void
11099PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11100{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011101 PyUnicode_Append(pleft, right);
11102 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011103}
11104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011105PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011106 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011108Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011109string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011110interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111
11112static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011113unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011115 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011116 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011117 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 int kind1, kind2, kind;
11120 void *buf1, *buf2;
11121 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122
Jesus Ceaac451502011-04-20 17:09:23 +020011123 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11124 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011125 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 kind1 = PyUnicode_KIND(self);
11128 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011129 if (kind2 > kind1) {
11130 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011131 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011132 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011133 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 buf1 = PyUnicode_DATA(self);
11135 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011137 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 if (!buf2) {
11139 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 return NULL;
11141 }
11142 len1 = PyUnicode_GET_LENGTH(self);
11143 len2 = PyUnicode_GET_LENGTH(substring);
11144
11145 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011146 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 case PyUnicode_1BYTE_KIND:
11148 iresult = ucs1lib_count(
11149 ((Py_UCS1*)buf1) + start, end - start,
11150 buf2, len2, PY_SSIZE_T_MAX
11151 );
11152 break;
11153 case PyUnicode_2BYTE_KIND:
11154 iresult = ucs2lib_count(
11155 ((Py_UCS2*)buf1) + start, end - start,
11156 buf2, len2, PY_SSIZE_T_MAX
11157 );
11158 break;
11159 case PyUnicode_4BYTE_KIND:
11160 iresult = ucs4lib_count(
11161 ((Py_UCS4*)buf1) + start, end - start,
11162 buf2, len2, PY_SSIZE_T_MAX
11163 );
11164 break;
11165 default:
11166 assert(0); iresult = 0;
11167 }
11168
11169 result = PyLong_FromSsize_t(iresult);
11170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 if (kind2 != kind)
11172 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
11174 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011175
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176 return result;
11177}
11178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011179PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011180 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011182Encode S using the codec registered for encoding. Default encoding\n\
11183is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011184handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011185a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11186'xmlcharrefreplace' as well as any other name registered with\n\
11187codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188
11189static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011190unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011192 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193 char *encoding = NULL;
11194 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011195
Benjamin Peterson308d6372009-09-18 21:42:35 +000011196 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11197 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011199 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011200}
11201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011202PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011203 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204\n\
11205Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011206If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011209unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011211 Py_ssize_t i, j, line_pos, src_len, incr;
11212 Py_UCS4 ch;
11213 PyObject *u;
11214 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011215 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011217 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011218 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
Ezio Melotti745d54d2013-11-16 19:10:57 +020011220 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11221 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011222 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223
Antoine Pitrou22425222011-10-04 19:10:51 +020011224 if (PyUnicode_READY(self) == -1)
11225 return NULL;
11226
Thomas Wouters7e474022000-07-16 12:04:32 +000011227 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011228 src_len = PyUnicode_GET_LENGTH(self);
11229 i = j = line_pos = 0;
11230 kind = PyUnicode_KIND(self);
11231 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011232 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011233 for (; i < src_len; i++) {
11234 ch = PyUnicode_READ(kind, src_data, i);
11235 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011236 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011237 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011238 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011239 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011240 goto overflow;
11241 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011243 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011244 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011246 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011247 goto overflow;
11248 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011250 if (ch == '\n' || ch == '\r')
11251 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011253 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011254 if (!found)
11255 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011256
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011258 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259 if (!u)
11260 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011261 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
Antoine Pitroue71d5742011-10-04 15:55:09 +020011265 for (; i < src_len; i++) {
11266 ch = PyUnicode_READ(kind, src_data, i);
11267 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011269 incr = tabsize - (line_pos % tabsize);
11270 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011271 FILL(kind, dest_data, ' ', j, incr);
11272 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011274 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011276 line_pos++;
11277 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011278 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011279 if (ch == '\n' || ch == '\r')
11280 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011282 }
11283 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011284 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011285
Antoine Pitroue71d5742011-10-04 15:55:09 +020011286 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011287 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11288 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289}
11290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011291PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293\n\
11294Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011295such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296arguments start and end are interpreted as in slice notation.\n\
11297\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011298Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299
11300static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011303 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011304 Py_ssize_t start;
11305 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011306 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307
Jesus Ceaac451502011-04-20 17:09:23 +020011308 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11309 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311
Christian Heimesd47802e2013-06-29 21:33:36 +020011312 if (PyUnicode_READY(self) == -1) {
11313 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011315 }
11316 if (PyUnicode_READY(substring) == -1) {
11317 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320
Victor Stinner7931d9a2011-11-04 00:22:48 +010011321 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322
11323 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 if (result == -2)
11326 return NULL;
11327
Christian Heimes217cfd12007-12-02 14:31:20 +000011328 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329}
11330
11331static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011332unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011334 void *data;
11335 enum PyUnicode_Kind kind;
11336 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011337
11338 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11339 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011341 }
11342 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11343 PyErr_SetString(PyExc_IndexError, "string index out of range");
11344 return NULL;
11345 }
11346 kind = PyUnicode_KIND(self);
11347 data = PyUnicode_DATA(self);
11348 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011349 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350}
11351
Guido van Rossumc2504932007-09-18 19:42:40 +000011352/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011353 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011354static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011355unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356{
Guido van Rossumc2504932007-09-18 19:42:40 +000011357 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011358 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011359
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011360#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011361 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011362#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 if (_PyUnicode_HASH(self) != -1)
11364 return _PyUnicode_HASH(self);
11365 if (PyUnicode_READY(self) == -1)
11366 return -1;
11367 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011368 /*
11369 We make the hash of the empty string be 0, rather than using
11370 (prefix ^ suffix), since this slightly obfuscates the hash secret
11371 */
11372 if (len == 0) {
11373 _PyUnicode_HASH(self) = 0;
11374 return 0;
11375 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011376 x = _Py_HashBytes(PyUnicode_DATA(self),
11377 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011379 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380}
11381
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011382PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011383 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011385Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386
11387static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011390 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011391 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011392 Py_ssize_t start;
11393 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
Jesus Ceaac451502011-04-20 17:09:23 +020011395 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11396 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
Christian Heimesd47a0452013-06-29 21:21:37 +020011399 if (PyUnicode_READY(self) == -1) {
11400 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011402 }
11403 if (PyUnicode_READY(substring) == -1) {
11404 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011406 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011407
Victor Stinner7931d9a2011-11-04 00:22:48 +010011408 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409
11410 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 if (result == -2)
11413 return NULL;
11414
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 if (result < 0) {
11416 PyErr_SetString(PyExc_ValueError, "substring not found");
11417 return NULL;
11418 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011419
Christian Heimes217cfd12007-12-02 14:31:20 +000011420 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421}
11422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011423PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011424 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011426Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011427at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428
11429static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011430unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 Py_ssize_t i, length;
11433 int kind;
11434 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 int cased;
11436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011437 if (PyUnicode_READY(self) == -1)
11438 return NULL;
11439 length = PyUnicode_GET_LENGTH(self);
11440 kind = PyUnicode_KIND(self);
11441 data = PyUnicode_DATA(self);
11442
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (length == 1)
11445 return PyBool_FromLong(
11446 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011448 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011450 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011451
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 for (i = 0; i < length; i++) {
11454 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011455
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11457 return PyBool_FromLong(0);
11458 else if (!cased && Py_UNICODE_ISLOWER(ch))
11459 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011461 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462}
11463
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011464PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011465 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011467Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011468at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
11470static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011471unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 Py_ssize_t i, length;
11474 int kind;
11475 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476 int cased;
11477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 if (PyUnicode_READY(self) == -1)
11479 return NULL;
11480 length = PyUnicode_GET_LENGTH(self);
11481 kind = PyUnicode_KIND(self);
11482 data = PyUnicode_DATA(self);
11483
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 if (length == 1)
11486 return PyBool_FromLong(
11487 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011489 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011491 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011492
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 for (i = 0; i < length; i++) {
11495 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011496
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11498 return PyBool_FromLong(0);
11499 else if (!cased && Py_UNICODE_ISUPPER(ch))
11500 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011502 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503}
11504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011505PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011508Return True if S is a titlecased string and there is at least one\n\
11509character in S, i.e. upper- and titlecase characters may only\n\
11510follow uncased characters and lowercase characters only cased ones.\n\
11511Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512
11513static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011514unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 Py_ssize_t i, length;
11517 int kind;
11518 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519 int cased, previous_is_cased;
11520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 if (PyUnicode_READY(self) == -1)
11522 return NULL;
11523 length = PyUnicode_GET_LENGTH(self);
11524 kind = PyUnicode_KIND(self);
11525 data = PyUnicode_DATA(self);
11526
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011528 if (length == 1) {
11529 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11530 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11531 (Py_UNICODE_ISUPPER(ch) != 0));
11532 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011534 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011536 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011537
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538 cased = 0;
11539 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 for (i = 0; i < length; i++) {
11541 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011542
Benjamin Peterson29060642009-01-31 22:14:21 +000011543 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11544 if (previous_is_cased)
11545 return PyBool_FromLong(0);
11546 previous_is_cased = 1;
11547 cased = 1;
11548 }
11549 else if (Py_UNICODE_ISLOWER(ch)) {
11550 if (!previous_is_cased)
11551 return PyBool_FromLong(0);
11552 previous_is_cased = 1;
11553 cased = 1;
11554 }
11555 else
11556 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011558 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559}
11560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011561PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011564Return True if all characters in S are whitespace\n\
11565and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566
11567static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011568unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 Py_ssize_t i, length;
11571 int kind;
11572 void *data;
11573
11574 if (PyUnicode_READY(self) == -1)
11575 return NULL;
11576 length = PyUnicode_GET_LENGTH(self);
11577 kind = PyUnicode_KIND(self);
11578 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 if (length == 1)
11582 return PyBool_FromLong(
11583 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011585 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011587 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 for (i = 0; i < length; i++) {
11590 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011591 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011594 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595}
11596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011597PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011598 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011599\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011600Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011601and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011602
11603static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011604unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011605{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 Py_ssize_t i, length;
11607 int kind;
11608 void *data;
11609
11610 if (PyUnicode_READY(self) == -1)
11611 return NULL;
11612 length = PyUnicode_GET_LENGTH(self);
11613 kind = PyUnicode_KIND(self);
11614 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011615
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011616 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 if (length == 1)
11618 return PyBool_FromLong(
11619 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011620
11621 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625 for (i = 0; i < length; i++) {
11626 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011627 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011628 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011629 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011630}
11631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011632PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011633 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011634\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011635Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011636and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011637
11638static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011639unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011640{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641 int kind;
11642 void *data;
11643 Py_ssize_t len, i;
11644
11645 if (PyUnicode_READY(self) == -1)
11646 return NULL;
11647
11648 kind = PyUnicode_KIND(self);
11649 data = PyUnicode_DATA(self);
11650 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011651
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (len == 1) {
11654 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11655 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11656 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011657
11658 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011660 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 for (i = 0; i < len; i++) {
11663 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011664 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011666 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011667 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011668}
11669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011670PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011671 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011673Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011674False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675
11676static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011677unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 Py_ssize_t i, length;
11680 int kind;
11681 void *data;
11682
11683 if (PyUnicode_READY(self) == -1)
11684 return NULL;
11685 length = PyUnicode_GET_LENGTH(self);
11686 kind = PyUnicode_KIND(self);
11687 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (length == 1)
11691 return PyBool_FromLong(
11692 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011694 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 for (i = 0; i < length; i++) {
11699 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011702 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011705PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011706 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011708Return True if all characters in S are digits\n\
11709and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
11711static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011712unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 Py_ssize_t i, length;
11715 int kind;
11716 void *data;
11717
11718 if (PyUnicode_READY(self) == -1)
11719 return NULL;
11720 length = PyUnicode_GET_LENGTH(self);
11721 kind = PyUnicode_KIND(self);
11722 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011725 if (length == 1) {
11726 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11727 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11728 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011730 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 for (i = 0; i < length; i++) {
11735 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011736 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011738 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739}
11740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011741PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011742 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011744Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011745False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746
11747static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011748unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011750 Py_ssize_t i, length;
11751 int kind;
11752 void *data;
11753
11754 if (PyUnicode_READY(self) == -1)
11755 return NULL;
11756 length = PyUnicode_GET_LENGTH(self);
11757 kind = PyUnicode_KIND(self);
11758 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761 if (length == 1)
11762 return PyBool_FromLong(
11763 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011765 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011767 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 for (i = 0; i < length; i++) {
11770 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011771 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011773 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774}
11775
Martin v. Löwis47383402007-08-15 07:32:56 +000011776int
11777PyUnicode_IsIdentifier(PyObject *self)
11778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 int kind;
11780 void *data;
11781 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011782 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 if (PyUnicode_READY(self) == -1) {
11785 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787 }
11788
11789 /* Special case for empty strings */
11790 if (PyUnicode_GET_LENGTH(self) == 0)
11791 return 0;
11792 kind = PyUnicode_KIND(self);
11793 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011794
11795 /* PEP 3131 says that the first character must be in
11796 XID_Start and subsequent characters in XID_Continue,
11797 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011798 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011799 letters, digits, underscore). However, given the current
11800 definition of XID_Start and XID_Continue, it is sufficient
11801 to check just for these, except that _ must be allowed
11802 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011804 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011805 return 0;
11806
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011807 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011809 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011810 return 1;
11811}
11812
11813PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011814 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011815\n\
11816Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011817to the language definition.\n\
11818\n\
11819Use keyword.iskeyword() to test for reserved identifiers\n\
11820such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011821
11822static PyObject*
11823unicode_isidentifier(PyObject *self)
11824{
11825 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11826}
11827
Georg Brandl559e5d72008-06-11 18:37:52 +000011828PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011830\n\
11831Return True if all characters in S are considered\n\
11832printable in repr() or S is empty, False otherwise.");
11833
11834static PyObject*
11835unicode_isprintable(PyObject *self)
11836{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 Py_ssize_t i, length;
11838 int kind;
11839 void *data;
11840
11841 if (PyUnicode_READY(self) == -1)
11842 return NULL;
11843 length = PyUnicode_GET_LENGTH(self);
11844 kind = PyUnicode_KIND(self);
11845 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011846
11847 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 if (length == 1)
11849 return PyBool_FromLong(
11850 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011851
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 for (i = 0; i < length; i++) {
11853 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011854 Py_RETURN_FALSE;
11855 }
11856 }
11857 Py_RETURN_TRUE;
11858}
11859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011860PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011861 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862\n\
11863Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011864iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865
11866static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011867unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011869 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870}
11871
Martin v. Löwis18e16552006-02-15 17:27:45 +000011872static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011873unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 if (PyUnicode_READY(self) == -1)
11876 return -1;
11877 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011878}
11879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011880PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011881 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011883Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011884done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
11886static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011887unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011889 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 Py_UCS4 fillchar = ' ';
11891
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011892 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893 return NULL;
11894
Benjamin Petersonbac79492012-01-14 13:34:47 -050011895 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011896 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897
Victor Stinnerc4b49542011-12-11 22:44:26 +010011898 if (PyUnicode_GET_LENGTH(self) >= width)
11899 return unicode_result_unchanged(self);
11900
11901 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902}
11903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011904PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011907Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908
11909static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011910unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011912 if (PyUnicode_READY(self) == -1)
11913 return NULL;
11914 if (PyUnicode_IS_ASCII(self))
11915 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011916 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917}
11918
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011919#define LEFTSTRIP 0
11920#define RIGHTSTRIP 1
11921#define BOTHSTRIP 2
11922
11923/* Arrays indexed by above */
11924static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11925
11926#define STRIPNAME(i) (stripformat[i]+3)
11927
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011928/* externally visible for str.strip(unicode) */
11929PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011930_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 void *data;
11933 int kind;
11934 Py_ssize_t i, j, len;
11935 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011936 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011938 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11939 return NULL;
11940
11941 kind = PyUnicode_KIND(self);
11942 data = PyUnicode_DATA(self);
11943 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011944 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11946 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011947 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011948
Benjamin Peterson14339b62009-01-31 16:36:08 +000011949 i = 0;
11950 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011951 while (i < len) {
11952 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11953 if (!BLOOM(sepmask, ch))
11954 break;
11955 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11956 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011957 i++;
11958 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011959 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011960
Benjamin Peterson14339b62009-01-31 16:36:08 +000011961 j = len;
11962 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011963 j--;
11964 while (j >= i) {
11965 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11966 if (!BLOOM(sepmask, ch))
11967 break;
11968 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11969 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011970 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011971 }
11972
Benjamin Peterson29060642009-01-31 22:14:21 +000011973 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011974 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011975
Victor Stinner7931d9a2011-11-04 00:22:48 +010011976 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977}
11978
11979PyObject*
11980PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11981{
11982 unsigned char *data;
11983 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011984 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985
Victor Stinnerde636f32011-10-01 03:55:54 +020011986 if (PyUnicode_READY(self) == -1)
11987 return NULL;
11988
Victor Stinner684d5fd2012-05-03 02:32:34 +020011989 length = PyUnicode_GET_LENGTH(self);
11990 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011991
Victor Stinner684d5fd2012-05-03 02:32:34 +020011992 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011993 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994
Victor Stinnerde636f32011-10-01 03:55:54 +020011995 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011996 PyErr_SetString(PyExc_IndexError, "string index out of range");
11997 return NULL;
11998 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011999 if (start >= length || end < start)
12000 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012001
Victor Stinner684d5fd2012-05-03 02:32:34 +020012002 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012003 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012004 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012005 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012006 }
12007 else {
12008 kind = PyUnicode_KIND(self);
12009 data = PyUnicode_1BYTE_DATA(self);
12010 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012011 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012012 length);
12013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012015
12016static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012017do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 Py_ssize_t len, i, j;
12020
12021 if (PyUnicode_READY(self) == -1)
12022 return NULL;
12023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012025
Victor Stinnercc7af722013-04-09 22:39:24 +020012026 if (PyUnicode_IS_ASCII(self)) {
12027 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12028
12029 i = 0;
12030 if (striptype != RIGHTSTRIP) {
12031 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012032 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012033 if (!_Py_ascii_whitespace[ch])
12034 break;
12035 i++;
12036 }
12037 }
12038
12039 j = len;
12040 if (striptype != LEFTSTRIP) {
12041 j--;
12042 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012043 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012044 if (!_Py_ascii_whitespace[ch])
12045 break;
12046 j--;
12047 }
12048 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012049 }
12050 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012051 else {
12052 int kind = PyUnicode_KIND(self);
12053 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012054
Victor Stinnercc7af722013-04-09 22:39:24 +020012055 i = 0;
12056 if (striptype != RIGHTSTRIP) {
12057 while (i < len) {
12058 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12059 if (!Py_UNICODE_ISSPACE(ch))
12060 break;
12061 i++;
12062 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012063 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012064
12065 j = len;
12066 if (striptype != LEFTSTRIP) {
12067 j--;
12068 while (j >= i) {
12069 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12070 if (!Py_UNICODE_ISSPACE(ch))
12071 break;
12072 j--;
12073 }
12074 j++;
12075 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012076 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012077
Victor Stinner7931d9a2011-11-04 00:22:48 +010012078 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079}
12080
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012081
12082static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012083do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012084{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012085 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012086
Serhiy Storchakac6792272013-10-19 21:03:34 +030012087 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012088 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012089
Benjamin Peterson14339b62009-01-31 16:36:08 +000012090 if (sep != NULL && sep != Py_None) {
12091 if (PyUnicode_Check(sep))
12092 return _PyUnicode_XStrip(self, striptype, sep);
12093 else {
12094 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012095 "%s arg must be None or str",
12096 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012097 return NULL;
12098 }
12099 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012100
Benjamin Peterson14339b62009-01-31 16:36:08 +000012101 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012102}
12103
12104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012105PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012106 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012107\n\
12108Return a copy of the string S with leading and trailing\n\
12109whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012110If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012111
12112static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012113unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012114{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012115 if (PyTuple_GET_SIZE(args) == 0)
12116 return do_strip(self, BOTHSTRIP); /* Common case */
12117 else
12118 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012119}
12120
12121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012122PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012123 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012124\n\
12125Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012126If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012127
12128static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012129unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012130{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012131 if (PyTuple_GET_SIZE(args) == 0)
12132 return do_strip(self, LEFTSTRIP); /* Common case */
12133 else
12134 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012135}
12136
12137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012138PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012139 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012140\n\
12141Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012142If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012143
12144static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012145unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012146{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012147 if (PyTuple_GET_SIZE(args) == 0)
12148 return do_strip(self, RIGHTSTRIP); /* Common case */
12149 else
12150 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012151}
12152
12153
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012155unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012157 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159
Serhiy Storchaka05997252013-01-26 12:14:02 +020012160 if (len < 1)
12161 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012162
Victor Stinnerc4b49542011-12-11 22:44:26 +010012163 /* no repeat, return original string */
12164 if (len == 1)
12165 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012166
Benjamin Petersonbac79492012-01-14 13:34:47 -050012167 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 return NULL;
12169
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012170 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012171 PyErr_SetString(PyExc_OverflowError,
12172 "repeated string is too long");
12173 return NULL;
12174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012176
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012177 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178 if (!u)
12179 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012180 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 if (PyUnicode_GET_LENGTH(str) == 1) {
12183 const int kind = PyUnicode_KIND(str);
12184 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012185 if (kind == PyUnicode_1BYTE_KIND) {
12186 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012187 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012188 }
12189 else if (kind == PyUnicode_2BYTE_KIND) {
12190 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012191 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012192 ucs2[n] = fill_char;
12193 } else {
12194 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12195 assert(kind == PyUnicode_4BYTE_KIND);
12196 for (n = 0; n < len; ++n)
12197 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012198 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 }
12200 else {
12201 /* number of characters copied this far */
12202 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012203 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 char *to = (char *) PyUnicode_DATA(u);
12205 Py_MEMCPY(to, PyUnicode_DATA(str),
12206 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012207 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 n = (done <= nchars-done) ? done : nchars-done;
12209 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012210 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012211 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212 }
12213
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012214 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012215 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216}
12217
Alexander Belopolsky40018472011-02-26 01:02:56 +000012218PyObject *
12219PyUnicode_Replace(PyObject *obj,
12220 PyObject *subobj,
12221 PyObject *replobj,
12222 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223{
12224 PyObject *self;
12225 PyObject *str1;
12226 PyObject *str2;
12227 PyObject *result;
12228
12229 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012230 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012231 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012233 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012234 Py_DECREF(self);
12235 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236 }
12237 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012238 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012239 Py_DECREF(self);
12240 Py_DECREF(str1);
12241 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012243 if (PyUnicode_READY(self) == -1 ||
12244 PyUnicode_READY(str1) == -1 ||
12245 PyUnicode_READY(str2) == -1)
12246 result = NULL;
12247 else
12248 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249 Py_DECREF(self);
12250 Py_DECREF(str1);
12251 Py_DECREF(str2);
12252 return result;
12253}
12254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012255PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012256 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257\n\
12258Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012259old replaced by new. If the optional argument count is\n\
12260given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261
12262static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 PyObject *str1;
12266 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012267 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268 PyObject *result;
12269
Martin v. Löwis18e16552006-02-15 17:27:45 +000012270 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012272 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012273 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012274 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012275 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276 return NULL;
12277 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012278 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012279 Py_DECREF(str1);
12280 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012281 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012282 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12283 result = NULL;
12284 else
12285 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286
12287 Py_DECREF(str1);
12288 Py_DECREF(str2);
12289 return result;
12290}
12291
Alexander Belopolsky40018472011-02-26 01:02:56 +000012292static PyObject *
12293unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012295 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 Py_ssize_t isize;
12297 Py_ssize_t osize, squote, dquote, i, o;
12298 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012299 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012303 return NULL;
12304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 isize = PyUnicode_GET_LENGTH(unicode);
12306 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 /* Compute length of output, quote characters, and
12309 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012310 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 max = 127;
12312 squote = dquote = 0;
12313 ikind = PyUnicode_KIND(unicode);
12314 for (i = 0; i < isize; i++) {
12315 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12316 switch (ch) {
12317 case '\'': squote++; osize++; break;
12318 case '"': dquote++; osize++; break;
12319 case '\\': case '\t': case '\r': case '\n':
12320 osize += 2; break;
12321 default:
12322 /* Fast-path ASCII */
12323 if (ch < ' ' || ch == 0x7f)
12324 osize += 4; /* \xHH */
12325 else if (ch < 0x7f)
12326 osize++;
12327 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12328 osize++;
12329 max = ch > max ? ch : max;
12330 }
12331 else if (ch < 0x100)
12332 osize += 4; /* \xHH */
12333 else if (ch < 0x10000)
12334 osize += 6; /* \uHHHH */
12335 else
12336 osize += 10; /* \uHHHHHHHH */
12337 }
12338 }
12339
12340 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012341 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012343 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012344 if (dquote)
12345 /* Both squote and dquote present. Use squote,
12346 and escape them */
12347 osize += squote;
12348 else
12349 quote = '"';
12350 }
Victor Stinner55c08782013-04-14 18:45:39 +020012351 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352
12353 repr = PyUnicode_New(osize, max);
12354 if (repr == NULL)
12355 return NULL;
12356 okind = PyUnicode_KIND(repr);
12357 odata = PyUnicode_DATA(repr);
12358
12359 PyUnicode_WRITE(okind, odata, 0, quote);
12360 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012361 if (unchanged) {
12362 _PyUnicode_FastCopyCharacters(repr, 1,
12363 unicode, 0,
12364 isize);
12365 }
12366 else {
12367 for (i = 0, o = 1; i < isize; i++) {
12368 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369
Victor Stinner55c08782013-04-14 18:45:39 +020012370 /* Escape quotes and backslashes */
12371 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012372 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012373 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012374 continue;
12375 }
12376
12377 /* Map special whitespace to '\t', \n', '\r' */
12378 if (ch == '\t') {
12379 PyUnicode_WRITE(okind, odata, o++, '\\');
12380 PyUnicode_WRITE(okind, odata, o++, 't');
12381 }
12382 else if (ch == '\n') {
12383 PyUnicode_WRITE(okind, odata, o++, '\\');
12384 PyUnicode_WRITE(okind, odata, o++, 'n');
12385 }
12386 else if (ch == '\r') {
12387 PyUnicode_WRITE(okind, odata, o++, '\\');
12388 PyUnicode_WRITE(okind, odata, o++, 'r');
12389 }
12390
12391 /* Map non-printable US ASCII to '\xhh' */
12392 else if (ch < ' ' || ch == 0x7F) {
12393 PyUnicode_WRITE(okind, odata, o++, '\\');
12394 PyUnicode_WRITE(okind, odata, o++, 'x');
12395 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12396 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12397 }
12398
12399 /* Copy ASCII characters as-is */
12400 else if (ch < 0x7F) {
12401 PyUnicode_WRITE(okind, odata, o++, ch);
12402 }
12403
12404 /* Non-ASCII characters */
12405 else {
12406 /* Map Unicode whitespace and control characters
12407 (categories Z* and C* except ASCII space)
12408 */
12409 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12410 PyUnicode_WRITE(okind, odata, o++, '\\');
12411 /* Map 8-bit characters to '\xhh' */
12412 if (ch <= 0xff) {
12413 PyUnicode_WRITE(okind, odata, o++, 'x');
12414 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12415 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12416 }
12417 /* Map 16-bit characters to '\uxxxx' */
12418 else if (ch <= 0xffff) {
12419 PyUnicode_WRITE(okind, odata, o++, 'u');
12420 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12421 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12422 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12423 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12424 }
12425 /* Map 21-bit characters to '\U00xxxxxx' */
12426 else {
12427 PyUnicode_WRITE(okind, odata, o++, 'U');
12428 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12429 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12430 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12431 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12432 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12433 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12434 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12435 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12436 }
12437 }
12438 /* Copy characters as-is */
12439 else {
12440 PyUnicode_WRITE(okind, odata, o++, ch);
12441 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012442 }
12443 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012446 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012447 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448}
12449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012450PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012451 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452\n\
12453Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012454such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455arguments start and end are interpreted as in slice notation.\n\
12456\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012457Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458
12459static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012462 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012463 Py_ssize_t start;
12464 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012465 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466
Jesus Ceaac451502011-04-20 17:09:23 +020012467 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12468 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012469 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470
Christian Heimesea71a522013-06-29 21:17:34 +020012471 if (PyUnicode_READY(self) == -1) {
12472 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012474 }
12475 if (PyUnicode_READY(substring) == -1) {
12476 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012479
Victor Stinner7931d9a2011-11-04 00:22:48 +010012480 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481
12482 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012484 if (result == -2)
12485 return NULL;
12486
Christian Heimes217cfd12007-12-02 14:31:20 +000012487 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488}
12489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012490PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012493Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494
12495static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012497{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012498 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012499 Py_ssize_t start;
12500 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012501 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012502
Jesus Ceaac451502011-04-20 17:09:23 +020012503 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12504 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012505 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506
Christian Heimesea71a522013-06-29 21:17:34 +020012507 if (PyUnicode_READY(self) == -1) {
12508 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012509 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012510 }
12511 if (PyUnicode_READY(substring) == -1) {
12512 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515
Victor Stinner7931d9a2011-11-04 00:22:48 +010012516 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517
12518 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012520 if (result == -2)
12521 return NULL;
12522
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523 if (result < 0) {
12524 PyErr_SetString(PyExc_ValueError, "substring not found");
12525 return NULL;
12526 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012527
Christian Heimes217cfd12007-12-02 14:31:20 +000012528 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529}
12530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012531PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012532 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012534Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012535done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536
12537static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012538unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012540 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 Py_UCS4 fillchar = ' ';
12542
Victor Stinnere9a29352011-10-01 02:14:59 +020012543 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012545
Benjamin Petersonbac79492012-01-14 13:34:47 -050012546 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547 return NULL;
12548
Victor Stinnerc4b49542011-12-11 22:44:26 +010012549 if (PyUnicode_GET_LENGTH(self) >= width)
12550 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551
Victor Stinnerc4b49542011-12-11 22:44:26 +010012552 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012553}
12554
Alexander Belopolsky40018472011-02-26 01:02:56 +000012555PyObject *
12556PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557{
12558 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012559
Guido van Rossumd57fd912000-03-10 22:53:23 +000012560 s = PyUnicode_FromObject(s);
12561 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012562 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012563 if (sep != NULL) {
12564 sep = PyUnicode_FromObject(sep);
12565 if (sep == NULL) {
12566 Py_DECREF(s);
12567 return NULL;
12568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012569 }
12570
Victor Stinner9310abb2011-10-05 00:59:23 +020012571 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012572
12573 Py_DECREF(s);
12574 Py_XDECREF(sep);
12575 return result;
12576}
12577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012578PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012579 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580\n\
12581Return a list of the words in S, using sep as the\n\
12582delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012583splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012584whitespace string is a separator and empty strings are\n\
12585removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586
12587static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012588unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012590 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012592 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012594 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12595 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596 return NULL;
12597
12598 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012601 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012603 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604}
12605
Thomas Wouters477c8d52006-05-27 19:21:47 +000012606PyObject *
12607PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12608{
12609 PyObject* str_obj;
12610 PyObject* sep_obj;
12611 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612 int kind1, kind2, kind;
12613 void *buf1 = NULL, *buf2 = NULL;
12614 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012615
12616 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012617 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012618 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012619 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012620 if (!sep_obj) {
12621 Py_DECREF(str_obj);
12622 return NULL;
12623 }
12624 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12625 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012626 Py_DECREF(str_obj);
12627 return NULL;
12628 }
12629
Victor Stinner14f8f022011-10-05 20:58:25 +020012630 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012632 kind = Py_MAX(kind1, kind2);
12633 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012635 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 if (!buf1)
12637 goto onError;
12638 buf2 = PyUnicode_DATA(sep_obj);
12639 if (kind2 != kind)
12640 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12641 if (!buf2)
12642 goto onError;
12643 len1 = PyUnicode_GET_LENGTH(str_obj);
12644 len2 = PyUnicode_GET_LENGTH(sep_obj);
12645
Benjamin Petersonead6b532011-12-20 17:23:42 -060012646 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012648 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12649 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12650 else
12651 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652 break;
12653 case PyUnicode_2BYTE_KIND:
12654 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12655 break;
12656 case PyUnicode_4BYTE_KIND:
12657 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12658 break;
12659 default:
12660 assert(0);
12661 out = 0;
12662 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012663
12664 Py_DECREF(sep_obj);
12665 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 if (kind1 != kind)
12667 PyMem_Free(buf1);
12668 if (kind2 != kind)
12669 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012670
12671 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012672 onError:
12673 Py_DECREF(sep_obj);
12674 Py_DECREF(str_obj);
12675 if (kind1 != kind && buf1)
12676 PyMem_Free(buf1);
12677 if (kind2 != kind && buf2)
12678 PyMem_Free(buf2);
12679 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012680}
12681
12682
12683PyObject *
12684PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12685{
12686 PyObject* str_obj;
12687 PyObject* sep_obj;
12688 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 int kind1, kind2, kind;
12690 void *buf1 = NULL, *buf2 = NULL;
12691 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012692
12693 str_obj = PyUnicode_FromObject(str_in);
12694 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012696 sep_obj = PyUnicode_FromObject(sep_in);
12697 if (!sep_obj) {
12698 Py_DECREF(str_obj);
12699 return NULL;
12700 }
12701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012702 kind1 = PyUnicode_KIND(str_in);
12703 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012704 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705 buf1 = PyUnicode_DATA(str_in);
12706 if (kind1 != kind)
12707 buf1 = _PyUnicode_AsKind(str_in, kind);
12708 if (!buf1)
12709 goto onError;
12710 buf2 = PyUnicode_DATA(sep_obj);
12711 if (kind2 != kind)
12712 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12713 if (!buf2)
12714 goto onError;
12715 len1 = PyUnicode_GET_LENGTH(str_obj);
12716 len2 = PyUnicode_GET_LENGTH(sep_obj);
12717
Benjamin Petersonead6b532011-12-20 17:23:42 -060012718 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012720 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12721 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12722 else
12723 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 break;
12725 case PyUnicode_2BYTE_KIND:
12726 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12727 break;
12728 case PyUnicode_4BYTE_KIND:
12729 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12730 break;
12731 default:
12732 assert(0);
12733 out = 0;
12734 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012735
12736 Py_DECREF(sep_obj);
12737 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 if (kind1 != kind)
12739 PyMem_Free(buf1);
12740 if (kind2 != kind)
12741 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012742
12743 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012744 onError:
12745 Py_DECREF(sep_obj);
12746 Py_DECREF(str_obj);
12747 if (kind1 != kind && buf1)
12748 PyMem_Free(buf1);
12749 if (kind2 != kind && buf2)
12750 PyMem_Free(buf2);
12751 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012752}
12753
12754PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012755 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012756\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012757Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012758the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012759found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012760
12761static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012762unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012763{
Victor Stinner9310abb2011-10-05 00:59:23 +020012764 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012765}
12766
12767PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012768 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012769\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012770Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012771the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012772separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012773
12774static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012775unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012776{
Victor Stinner9310abb2011-10-05 00:59:23 +020012777 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012778}
12779
Alexander Belopolsky40018472011-02-26 01:02:56 +000012780PyObject *
12781PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012782{
12783 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012784
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012785 s = PyUnicode_FromObject(s);
12786 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012787 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012788 if (sep != NULL) {
12789 sep = PyUnicode_FromObject(sep);
12790 if (sep == NULL) {
12791 Py_DECREF(s);
12792 return NULL;
12793 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012794 }
12795
Victor Stinner9310abb2011-10-05 00:59:23 +020012796 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012797
12798 Py_DECREF(s);
12799 Py_XDECREF(sep);
12800 return result;
12801}
12802
12803PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012804 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012805\n\
12806Return a list of the words in S, using sep as the\n\
12807delimiter string, starting at the end of the string and\n\
12808working to the front. If maxsplit is given, at most maxsplit\n\
12809splits are done. If sep is not specified, any whitespace string\n\
12810is a separator.");
12811
12812static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012813unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012814{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012815 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012816 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012817 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012818
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012819 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12820 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012821 return NULL;
12822
12823 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012824 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012825 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012826 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012827 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012828 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012829}
12830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012831PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012832 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833\n\
12834Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012835Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012836is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012837
12838static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012839unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012841 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012842 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012844 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12845 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012846 return NULL;
12847
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012848 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849}
12850
12851static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012852PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012854 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855}
12856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012857PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012858 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859\n\
12860Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012861and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862
12863static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012864unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012866 if (PyUnicode_READY(self) == -1)
12867 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012868 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869}
12870
Larry Hastings61272b72014-01-07 12:41:53 -080012871/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012872
Larry Hastings31826802013-10-19 00:09:25 -070012873@staticmethod
12874str.maketrans as unicode_maketrans
12875
12876 x: object
12877
12878 y: unicode=NULL
12879
12880 z: unicode=NULL
12881
12882 /
12883
12884Return a translation table usable for str.translate().
12885
12886If there is only one argument, it must be a dictionary mapping Unicode
12887ordinals (integers) or characters to Unicode ordinals, strings or None.
12888Character keys will be then converted to ordinals.
12889If there are two arguments, they must be strings of equal length, and
12890in the resulting dictionary, each character in x will be mapped to the
12891character at the same position in y. If there is a third argument, it
12892must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012893[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012894
12895PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012896"maketrans(x, y=None, z=None, /)\n"
12897"--\n"
12898"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012899"Return a translation table usable for str.translate().\n"
12900"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012901"If there is only one argument, it must be a dictionary mapping Unicode\n"
12902"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12903"Character keys will be then converted to ordinals.\n"
12904"If there are two arguments, they must be strings of equal length, and\n"
12905"in the resulting dictionary, each character in x will be mapped to the\n"
12906"character at the same position in y. If there is a third argument, it\n"
12907"must be a string, whose characters will be mapped to None in the result.");
12908
12909#define UNICODE_MAKETRANS_METHODDEF \
12910 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12911
12912static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012913unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012914
12915static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012916unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012917{
Larry Hastings31826802013-10-19 00:09:25 -070012918 PyObject *return_value = NULL;
12919 PyObject *x;
12920 PyObject *y = NULL;
12921 PyObject *z = NULL;
12922
12923 if (!PyArg_ParseTuple(args,
12924 "O|UU:maketrans",
12925 &x, &y, &z))
12926 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012927 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012928
12929exit:
12930 return return_value;
12931}
12932
12933static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012934unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012935/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012936{
Georg Brandlceee0772007-11-27 23:48:05 +000012937 PyObject *new = NULL, *key, *value;
12938 Py_ssize_t i = 0;
12939 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012940
Georg Brandlceee0772007-11-27 23:48:05 +000012941 new = PyDict_New();
12942 if (!new)
12943 return NULL;
12944 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012945 int x_kind, y_kind, z_kind;
12946 void *x_data, *y_data, *z_data;
12947
Georg Brandlceee0772007-11-27 23:48:05 +000012948 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012949 if (!PyUnicode_Check(x)) {
12950 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12951 "be a string if there is a second argument");
12952 goto err;
12953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012955 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12956 "arguments must have equal length");
12957 goto err;
12958 }
12959 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 x_kind = PyUnicode_KIND(x);
12961 y_kind = PyUnicode_KIND(y);
12962 x_data = PyUnicode_DATA(x);
12963 y_data = PyUnicode_DATA(y);
12964 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12965 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012966 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012967 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012968 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012969 if (!value) {
12970 Py_DECREF(key);
12971 goto err;
12972 }
Georg Brandlceee0772007-11-27 23:48:05 +000012973 res = PyDict_SetItem(new, key, value);
12974 Py_DECREF(key);
12975 Py_DECREF(value);
12976 if (res < 0)
12977 goto err;
12978 }
12979 /* create entries for deleting chars in z */
12980 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981 z_kind = PyUnicode_KIND(z);
12982 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012983 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012985 if (!key)
12986 goto err;
12987 res = PyDict_SetItem(new, key, Py_None);
12988 Py_DECREF(key);
12989 if (res < 0)
12990 goto err;
12991 }
12992 }
12993 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 int kind;
12995 void *data;
12996
Georg Brandlceee0772007-11-27 23:48:05 +000012997 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012998 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012999 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13000 "to maketrans it must be a dict");
13001 goto err;
13002 }
13003 /* copy entries into the new dict, converting string keys to int keys */
13004 while (PyDict_Next(x, &i, &key, &value)) {
13005 if (PyUnicode_Check(key)) {
13006 /* convert string keys to integer keys */
13007 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013008 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013009 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13010 "table must be of length 1");
13011 goto err;
13012 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 kind = PyUnicode_KIND(key);
13014 data = PyUnicode_DATA(key);
13015 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013016 if (!newkey)
13017 goto err;
13018 res = PyDict_SetItem(new, newkey, value);
13019 Py_DECREF(newkey);
13020 if (res < 0)
13021 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013022 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013023 /* just keep integer keys */
13024 if (PyDict_SetItem(new, key, value) < 0)
13025 goto err;
13026 } else {
13027 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13028 "be strings or integers");
13029 goto err;
13030 }
13031 }
13032 }
13033 return new;
13034 err:
13035 Py_DECREF(new);
13036 return NULL;
13037}
13038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013039PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013040 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013041\n\
13042Return a copy of the string S, where all characters have been mapped\n\
13043through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013044Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013045Unmapped characters are left untouched. Characters mapped to None\n\
13046are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047
13048static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013049unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013051 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052}
13053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013054PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013057Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058
13059static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013060unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013062 if (PyUnicode_READY(self) == -1)
13063 return NULL;
13064 if (PyUnicode_IS_ASCII(self))
13065 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013066 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067}
13068
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013069PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013070 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013072Pad a numeric string S with zeros on the left, to fill a field\n\
13073of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074
13075static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013076unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013077{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013078 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013079 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013080 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013081 int kind;
13082 void *data;
13083 Py_UCS4 chr;
13084
Martin v. Löwis18e16552006-02-15 17:27:45 +000013085 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013086 return NULL;
13087
Benjamin Petersonbac79492012-01-14 13:34:47 -050013088 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090
Victor Stinnerc4b49542011-12-11 22:44:26 +010013091 if (PyUnicode_GET_LENGTH(self) >= width)
13092 return unicode_result_unchanged(self);
13093
13094 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095
13096 u = pad(self, fill, 0, '0');
13097
Walter Dörwald068325e2002-04-15 13:36:47 +000013098 if (u == NULL)
13099 return NULL;
13100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101 kind = PyUnicode_KIND(u);
13102 data = PyUnicode_DATA(u);
13103 chr = PyUnicode_READ(kind, data, fill);
13104
13105 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 PyUnicode_WRITE(kind, data, 0, chr);
13108 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109 }
13110
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013111 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013112 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114
13115#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013116static PyObject *
13117unicode__decimal2ascii(PyObject *self)
13118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013120}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121#endif
13122
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013123PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013124 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013126Return True if S starts with the specified prefix, False otherwise.\n\
13127With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013128With optional end, stop comparing S at that position.\n\
13129prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130
13131static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013132unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013133 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013134{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013135 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013136 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013137 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013138 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013139 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140
Jesus Ceaac451502011-04-20 17:09:23 +020013141 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013142 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013143 if (PyTuple_Check(subobj)) {
13144 Py_ssize_t i;
13145 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013146 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013147 if (substring == NULL)
13148 return NULL;
13149 result = tailmatch(self, substring, start, end, -1);
13150 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013151 if (result == -1)
13152 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013153 if (result) {
13154 Py_RETURN_TRUE;
13155 }
13156 }
13157 /* nothing matched */
13158 Py_RETURN_FALSE;
13159 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013160 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013161 if (substring == NULL) {
13162 if (PyErr_ExceptionMatches(PyExc_TypeError))
13163 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13164 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013166 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013167 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013169 if (result == -1)
13170 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013171 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172}
13173
13174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013175PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013178Return True if S ends with the specified suffix, False otherwise.\n\
13179With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180With optional end, stop comparing S at that position.\n\
13181suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182
13183static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013184unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013187 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013188 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013189 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013190 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
Jesus Ceaac451502011-04-20 17:09:23 +020013193 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013194 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013195 if (PyTuple_Check(subobj)) {
13196 Py_ssize_t i;
13197 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013200 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013201 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013202 result = tailmatch(self, substring, start, end, +1);
13203 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013204 if (result == -1)
13205 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013206 if (result) {
13207 Py_RETURN_TRUE;
13208 }
13209 }
13210 Py_RETURN_FALSE;
13211 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013212 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013213 if (substring == NULL) {
13214 if (PyErr_ExceptionMatches(PyExc_TypeError))
13215 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13216 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013218 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013219 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013220 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013221 if (result == -1)
13222 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224}
13225
Victor Stinner202fdca2012-05-07 12:47:02 +020013226Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013227_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013228{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013229 if (!writer->readonly)
13230 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13231 else {
13232 /* Copy-on-write mode: set buffer size to 0 so
13233 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13234 * next write. */
13235 writer->size = 0;
13236 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013237 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13238 writer->data = PyUnicode_DATA(writer->buffer);
13239 writer->kind = PyUnicode_KIND(writer->buffer);
13240}
13241
Victor Stinnerd3f08822012-05-29 12:57:52 +020013242void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013243_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013244{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013245 memset(writer, 0, sizeof(*writer));
13246#ifdef Py_DEBUG
13247 writer->kind = 5; /* invalid kind */
13248#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013249 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013250}
13251
Victor Stinnerd3f08822012-05-29 12:57:52 +020013252int
13253_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13254 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013255{
Victor Stinner6989ba02013-11-18 21:08:39 +010013256#ifdef MS_WINDOWS
13257 /* On Windows, overallocate by 50% is the best factor */
13258# define OVERALLOCATE_FACTOR 2
13259#else
13260 /* On Linux, overallocate by 25% is the best factor */
13261# define OVERALLOCATE_FACTOR 4
13262#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013263 Py_ssize_t newlen;
13264 PyObject *newbuffer;
13265
Victor Stinnerd3f08822012-05-29 12:57:52 +020013266 assert(length > 0);
13267
Victor Stinner202fdca2012-05-07 12:47:02 +020013268 if (length > PY_SSIZE_T_MAX - writer->pos) {
13269 PyErr_NoMemory();
13270 return -1;
13271 }
13272 newlen = writer->pos + length;
13273
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013274 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013275
Victor Stinnerd3f08822012-05-29 12:57:52 +020013276 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013277 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013278 if (writer->overallocate
13279 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13280 /* overallocate to limit the number of realloc() */
13281 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013282 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013283 if (newlen < writer->min_length)
13284 newlen = writer->min_length;
13285
Victor Stinnerd3f08822012-05-29 12:57:52 +020013286 writer->buffer = PyUnicode_New(newlen, maxchar);
13287 if (writer->buffer == NULL)
13288 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013289 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013290 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013291 if (writer->overallocate
13292 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13293 /* overallocate to limit the number of realloc() */
13294 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013295 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013296 if (newlen < writer->min_length)
13297 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013298
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013299 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013300 /* resize + widen */
13301 newbuffer = PyUnicode_New(newlen, maxchar);
13302 if (newbuffer == NULL)
13303 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013304 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13305 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013306 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013307 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013308 }
13309 else {
13310 newbuffer = resize_compact(writer->buffer, newlen);
13311 if (newbuffer == NULL)
13312 return -1;
13313 }
13314 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013315 }
13316 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013317 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013318 newbuffer = PyUnicode_New(writer->size, maxchar);
13319 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013320 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13322 writer->buffer, 0, writer->pos);
13323 Py_DECREF(writer->buffer);
13324 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013325 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013326 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013327 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013328
13329#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013330}
13331
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013332Py_LOCAL_INLINE(int)
13333_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013334{
13335 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13336 return -1;
13337 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13338 writer->pos++;
13339 return 0;
13340}
13341
13342int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013343_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13344{
13345 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13346}
13347
13348int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13350{
13351 Py_UCS4 maxchar;
13352 Py_ssize_t len;
13353
13354 if (PyUnicode_READY(str) == -1)
13355 return -1;
13356 len = PyUnicode_GET_LENGTH(str);
13357 if (len == 0)
13358 return 0;
13359 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13360 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013361 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013362 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013363 Py_INCREF(str);
13364 writer->buffer = str;
13365 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013366 writer->pos += len;
13367 return 0;
13368 }
13369 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13370 return -1;
13371 }
13372 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13373 str, 0, len);
13374 writer->pos += len;
13375 return 0;
13376}
13377
Victor Stinnere215d962012-10-06 23:03:36 +020013378int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013379_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13380 Py_ssize_t start, Py_ssize_t end)
13381{
13382 Py_UCS4 maxchar;
13383 Py_ssize_t len;
13384
13385 if (PyUnicode_READY(str) == -1)
13386 return -1;
13387
13388 assert(0 <= start);
13389 assert(end <= PyUnicode_GET_LENGTH(str));
13390 assert(start <= end);
13391
13392 if (end == 0)
13393 return 0;
13394
13395 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13396 return _PyUnicodeWriter_WriteStr(writer, str);
13397
13398 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13399 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13400 else
13401 maxchar = writer->maxchar;
13402 len = end - start;
13403
13404 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13405 return -1;
13406
13407 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13408 str, start, len);
13409 writer->pos += len;
13410 return 0;
13411}
13412
13413int
Victor Stinner4a587072013-11-19 12:54:53 +010013414_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13415 const char *ascii, Py_ssize_t len)
13416{
13417 if (len == -1)
13418 len = strlen(ascii);
13419
13420 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13421
13422 if (writer->buffer == NULL && !writer->overallocate) {
13423 PyObject *str;
13424
13425 str = _PyUnicode_FromASCII(ascii, len);
13426 if (str == NULL)
13427 return -1;
13428
13429 writer->readonly = 1;
13430 writer->buffer = str;
13431 _PyUnicodeWriter_Update(writer);
13432 writer->pos += len;
13433 return 0;
13434 }
13435
13436 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13437 return -1;
13438
13439 switch (writer->kind)
13440 {
13441 case PyUnicode_1BYTE_KIND:
13442 {
13443 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13444 Py_UCS1 *data = writer->data;
13445
13446 Py_MEMCPY(data + writer->pos, str, len);
13447 break;
13448 }
13449 case PyUnicode_2BYTE_KIND:
13450 {
13451 _PyUnicode_CONVERT_BYTES(
13452 Py_UCS1, Py_UCS2,
13453 ascii, ascii + len,
13454 (Py_UCS2 *)writer->data + writer->pos);
13455 break;
13456 }
13457 case PyUnicode_4BYTE_KIND:
13458 {
13459 _PyUnicode_CONVERT_BYTES(
13460 Py_UCS1, Py_UCS4,
13461 ascii, ascii + len,
13462 (Py_UCS4 *)writer->data + writer->pos);
13463 break;
13464 }
13465 default:
13466 assert(0);
13467 }
13468
13469 writer->pos += len;
13470 return 0;
13471}
13472
13473int
13474_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13475 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013476{
13477 Py_UCS4 maxchar;
13478
13479 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13480 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13481 return -1;
13482 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13483 writer->pos += len;
13484 return 0;
13485}
13486
Victor Stinnerd3f08822012-05-29 12:57:52 +020013487PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013488_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013489{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013490 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013491 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013492 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013493 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013494 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013495 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013496 str = writer->buffer;
13497 writer->buffer = NULL;
13498 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13499 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013500 }
13501 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13502 PyObject *newbuffer;
13503 newbuffer = resize_compact(writer->buffer, writer->pos);
13504 if (newbuffer == NULL) {
13505 Py_DECREF(writer->buffer);
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013506 writer->buffer = NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013507 return NULL;
13508 }
13509 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013510 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013511 str = writer->buffer;
13512 writer->buffer = NULL;
13513 assert(_PyUnicode_CheckConsistency(str, 1));
13514 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013515}
13516
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013518_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013519{
13520 Py_CLEAR(writer->buffer);
13521}
13522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013524
13525PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013527\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013528Return a formatted version of S, using substitutions from args and kwargs.\n\
13529The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013530
Eric Smith27bbca62010-11-04 17:06:58 +000013531PyDoc_STRVAR(format_map__doc__,
13532 "S.format_map(mapping) -> str\n\
13533\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013534Return a formatted version of S, using substitutions from mapping.\n\
13535The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013536
Eric Smith4a7d76d2008-05-30 18:10:19 +000013537static PyObject *
13538unicode__format__(PyObject* self, PyObject* args)
13539{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013540 PyObject *format_spec;
13541 _PyUnicodeWriter writer;
13542 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013543
13544 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13545 return NULL;
13546
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 if (PyUnicode_READY(self) == -1)
13548 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013549 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013550 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13551 self, format_spec, 0,
13552 PyUnicode_GET_LENGTH(format_spec));
13553 if (ret == -1) {
13554 _PyUnicodeWriter_Dealloc(&writer);
13555 return NULL;
13556 }
13557 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013558}
13559
Eric Smith8c663262007-08-25 02:26:07 +000013560PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013562\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013563Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013564
13565static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013566unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013567{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013568 Py_ssize_t size;
13569
13570 /* If it's a compact object, account for base structure +
13571 character data. */
13572 if (PyUnicode_IS_COMPACT_ASCII(v))
13573 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13574 else if (PyUnicode_IS_COMPACT(v))
13575 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013576 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013577 else {
13578 /* If it is a two-block object, account for base object, and
13579 for character block if present. */
13580 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013581 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013583 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013584 }
13585 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013586 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013587 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013589 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013590 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013591
13592 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013593}
13594
13595PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013597
13598static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013599unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013600{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013601 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013602 if (!copy)
13603 return NULL;
13604 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013605}
13606
Guido van Rossumd57fd912000-03-10 22:53:23 +000013607static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013608 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013609 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013610 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13611 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013612 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13613 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013614 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013615 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13616 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13617 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013618 {"expandtabs", (PyCFunction) unicode_expandtabs,
13619 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013620 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013621 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013622 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13623 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13624 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013625 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013626 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13627 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13628 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013629 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013630 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013631 {"splitlines", (PyCFunction) unicode_splitlines,
13632 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013633 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013634 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13635 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13636 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13637 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13638 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13639 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13640 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13641 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13642 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13643 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13644 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13645 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13646 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13647 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013648 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013649 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013650 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013651 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013652 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013653 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013654 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013655 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013656#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013657 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013658 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013659#endif
13660
Benjamin Peterson14339b62009-01-31 16:36:08 +000013661 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013662 {NULL, NULL}
13663};
13664
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013665static PyObject *
13666unicode_mod(PyObject *v, PyObject *w)
13667{
Brian Curtindfc80e32011-08-10 20:28:54 -050013668 if (!PyUnicode_Check(v))
13669 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013670 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013671}
13672
13673static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013674 0, /*nb_add*/
13675 0, /*nb_subtract*/
13676 0, /*nb_multiply*/
13677 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013678};
13679
Guido van Rossumd57fd912000-03-10 22:53:23 +000013680static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013681 (lenfunc) unicode_length, /* sq_length */
13682 PyUnicode_Concat, /* sq_concat */
13683 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13684 (ssizeargfunc) unicode_getitem, /* sq_item */
13685 0, /* sq_slice */
13686 0, /* sq_ass_item */
13687 0, /* sq_ass_slice */
13688 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013689};
13690
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013691static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013692unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013693{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013694 if (PyUnicode_READY(self) == -1)
13695 return NULL;
13696
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013697 if (PyIndex_Check(item)) {
13698 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013699 if (i == -1 && PyErr_Occurred())
13700 return NULL;
13701 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013702 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013703 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013704 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013705 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013706 PyObject *result;
13707 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013708 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013709 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013711 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013712 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013713 return NULL;
13714 }
13715
13716 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013717 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013718 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013719 slicelength == PyUnicode_GET_LENGTH(self)) {
13720 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013721 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013722 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013723 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013724 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013725 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013726 src_kind = PyUnicode_KIND(self);
13727 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013728 if (!PyUnicode_IS_ASCII(self)) {
13729 kind_limit = kind_maxchar_limit(src_kind);
13730 max_char = 0;
13731 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13732 ch = PyUnicode_READ(src_kind, src_data, cur);
13733 if (ch > max_char) {
13734 max_char = ch;
13735 if (max_char >= kind_limit)
13736 break;
13737 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013738 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013739 }
Victor Stinner55c99112011-10-13 01:17:06 +020013740 else
13741 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013742 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013743 if (result == NULL)
13744 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013745 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013746 dest_data = PyUnicode_DATA(result);
13747
13748 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013749 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13750 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013751 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013752 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013753 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013754 } else {
13755 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13756 return NULL;
13757 }
13758}
13759
13760static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013761 (lenfunc)unicode_length, /* mp_length */
13762 (binaryfunc)unicode_subscript, /* mp_subscript */
13763 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013764};
13765
Guido van Rossumd57fd912000-03-10 22:53:23 +000013766
Guido van Rossumd57fd912000-03-10 22:53:23 +000013767/* Helpers for PyUnicode_Format() */
13768
Victor Stinnera47082312012-10-04 02:19:54 +020013769struct unicode_formatter_t {
13770 PyObject *args;
13771 int args_owned;
13772 Py_ssize_t arglen, argidx;
13773 PyObject *dict;
13774
13775 enum PyUnicode_Kind fmtkind;
13776 Py_ssize_t fmtcnt, fmtpos;
13777 void *fmtdata;
13778 PyObject *fmtstr;
13779
13780 _PyUnicodeWriter writer;
13781};
13782
13783struct unicode_format_arg_t {
13784 Py_UCS4 ch;
13785 int flags;
13786 Py_ssize_t width;
13787 int prec;
13788 int sign;
13789};
13790
Guido van Rossumd57fd912000-03-10 22:53:23 +000013791static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013792unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013793{
Victor Stinnera47082312012-10-04 02:19:54 +020013794 Py_ssize_t argidx = ctx->argidx;
13795
13796 if (argidx < ctx->arglen) {
13797 ctx->argidx++;
13798 if (ctx->arglen < 0)
13799 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013800 else
Victor Stinnera47082312012-10-04 02:19:54 +020013801 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013802 }
13803 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013804 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013805 return NULL;
13806}
13807
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013808/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013809
Victor Stinnera47082312012-10-04 02:19:54 +020013810/* Format a float into the writer if the writer is not NULL, or into *p_output
13811 otherwise.
13812
13813 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013814static int
Victor Stinnera47082312012-10-04 02:19:54 +020013815formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13816 PyObject **p_output,
13817 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013818{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013819 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013820 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013821 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013822 int prec;
13823 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013824
Guido van Rossumd57fd912000-03-10 22:53:23 +000013825 x = PyFloat_AsDouble(v);
13826 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013827 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013828
Victor Stinnera47082312012-10-04 02:19:54 +020013829 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013831 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013832
Victor Stinnera47082312012-10-04 02:19:54 +020013833 if (arg->flags & F_ALT)
13834 dtoa_flags = Py_DTSF_ALT;
13835 else
13836 dtoa_flags = 0;
13837 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013838 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013839 return -1;
13840 len = strlen(p);
13841 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013842 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013843 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013844 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013845 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013846 }
13847 else
13848 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013849 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013851}
13852
Victor Stinnerd0880d52012-04-27 23:40:13 +020013853/* formatlong() emulates the format codes d, u, o, x and X, and
13854 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13855 * Python's regular ints.
13856 * Return value: a new PyUnicodeObject*, or NULL if error.
13857 * The output string is of the form
13858 * "-"? ("0x" | "0X")? digit+
13859 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13860 * set in flags. The case of hex digits will be correct,
13861 * There will be at least prec digits, zero-filled on the left if
13862 * necessary to get that many.
13863 * val object to be converted
13864 * flags bitmask of format flags; only F_ALT is looked at
13865 * prec minimum number of digits; 0-fill on left if needed
13866 * type a character in [duoxX]; u acts the same as d
13867 *
13868 * CAUTION: o, x and X conversions on regular ints can never
13869 * produce a '-' sign, but can for Python's unbounded ints.
13870 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013871static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013872formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013873{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013874 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013875 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013876 Py_ssize_t i;
13877 int sign; /* 1 if '-', else 0 */
13878 int len; /* number of characters */
13879 Py_ssize_t llen;
13880 int numdigits; /* len == numnondigits + numdigits */
13881 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013882 int prec = arg->prec;
13883 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013884
Victor Stinnerd0880d52012-04-27 23:40:13 +020013885 /* Avoid exceeding SSIZE_T_MAX */
13886 if (prec > INT_MAX-3) {
13887 PyErr_SetString(PyExc_OverflowError,
13888 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013889 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013890 }
13891
13892 assert(PyLong_Check(val));
13893
13894 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013895 default:
13896 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013897 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013898 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013899 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013900 /* int and int subclasses should print numerically when a numeric */
13901 /* format code is used (see issue18780) */
13902 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013903 break;
13904 case 'o':
13905 numnondigits = 2;
13906 result = PyNumber_ToBase(val, 8);
13907 break;
13908 case 'x':
13909 case 'X':
13910 numnondigits = 2;
13911 result = PyNumber_ToBase(val, 16);
13912 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013913 }
13914 if (!result)
13915 return NULL;
13916
13917 assert(unicode_modifiable(result));
13918 assert(PyUnicode_IS_READY(result));
13919 assert(PyUnicode_IS_ASCII(result));
13920
13921 /* To modify the string in-place, there can only be one reference. */
13922 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013923 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013924 PyErr_BadInternalCall();
13925 return NULL;
13926 }
13927 buf = PyUnicode_DATA(result);
13928 llen = PyUnicode_GET_LENGTH(result);
13929 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013930 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013931 PyErr_SetString(PyExc_ValueError,
13932 "string too large in _PyBytes_FormatLong");
13933 return NULL;
13934 }
13935 len = (int)llen;
13936 sign = buf[0] == '-';
13937 numnondigits += sign;
13938 numdigits = len - numnondigits;
13939 assert(numdigits > 0);
13940
13941 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013942 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013943 (type == 'o' || type == 'x' || type == 'X'))) {
13944 assert(buf[sign] == '0');
13945 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13946 buf[sign+1] == 'o');
13947 numnondigits -= 2;
13948 buf += 2;
13949 len -= 2;
13950 if (sign)
13951 buf[0] = '-';
13952 assert(len == numnondigits + numdigits);
13953 assert(numdigits > 0);
13954 }
13955
13956 /* Fill with leading zeroes to meet minimum width. */
13957 if (prec > numdigits) {
13958 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13959 numnondigits + prec);
13960 char *b1;
13961 if (!r1) {
13962 Py_DECREF(result);
13963 return NULL;
13964 }
13965 b1 = PyBytes_AS_STRING(r1);
13966 for (i = 0; i < numnondigits; ++i)
13967 *b1++ = *buf++;
13968 for (i = 0; i < prec - numdigits; i++)
13969 *b1++ = '0';
13970 for (i = 0; i < numdigits; i++)
13971 *b1++ = *buf++;
13972 *b1 = '\0';
13973 Py_DECREF(result);
13974 result = r1;
13975 buf = PyBytes_AS_STRING(result);
13976 len = numnondigits + prec;
13977 }
13978
13979 /* Fix up case for hex conversions. */
13980 if (type == 'X') {
13981 /* Need to convert all lower case letters to upper case.
13982 and need to convert 0x to 0X (and -0x to -0X). */
13983 for (i = 0; i < len; i++)
13984 if (buf[i] >= 'a' && buf[i] <= 'x')
13985 buf[i] -= 'a'-'A';
13986 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013987 if (!PyUnicode_Check(result)
13988 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013989 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013990 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013991 Py_DECREF(result);
13992 result = unicode;
13993 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013994 else if (len != PyUnicode_GET_LENGTH(result)) {
13995 if (PyUnicode_Resize(&result, len) < 0)
13996 Py_CLEAR(result);
13997 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013999}
14000
Ethan Furmandf3ed242014-01-05 06:50:30 -080014001/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014002 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014003 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014004 * -1 and raise an exception on error */
14005static int
Victor Stinnera47082312012-10-04 02:19:54 +020014006mainformatlong(PyObject *v,
14007 struct unicode_format_arg_t *arg,
14008 PyObject **p_output,
14009 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014010{
14011 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014012 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014013
14014 if (!PyNumber_Check(v))
14015 goto wrongtype;
14016
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014017 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014018 /* if not, issue deprecation warning for now */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014019 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014020 if (type == 'o' || type == 'x' || type == 'X') {
14021 iobj = PyNumber_Index(v);
14022 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014023 PyErr_Clear();
14024 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14025 "automatic int conversions have been deprecated",
14026 1)) {
14027 return -1;
14028 }
14029 iobj = PyNumber_Long(v);
14030 if (iobj == NULL ) {
14031 if (PyErr_ExceptionMatches(PyExc_TypeError))
14032 goto wrongtype;
14033 return -1;
14034 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014035 }
14036 }
14037 else {
14038 iobj = PyNumber_Long(v);
14039 if (iobj == NULL ) {
14040 if (PyErr_ExceptionMatches(PyExc_TypeError))
14041 goto wrongtype;
14042 return -1;
14043 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014044 }
14045 assert(PyLong_Check(iobj));
14046 }
14047 else {
14048 iobj = v;
14049 Py_INCREF(iobj);
14050 }
14051
14052 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014053 && arg->width == -1 && arg->prec == -1
14054 && !(arg->flags & (F_SIGN | F_BLANK))
14055 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014056 {
14057 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014058 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014059 int base;
14060
Victor Stinnera47082312012-10-04 02:19:54 +020014061 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014062 {
14063 default:
14064 assert(0 && "'type' not in [diuoxX]");
14065 case 'd':
14066 case 'i':
14067 case 'u':
14068 base = 10;
14069 break;
14070 case 'o':
14071 base = 8;
14072 break;
14073 case 'x':
14074 case 'X':
14075 base = 16;
14076 break;
14077 }
14078
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014079 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14080 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014081 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014082 }
14083 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014084 return 1;
14085 }
14086
Victor Stinnera47082312012-10-04 02:19:54 +020014087 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014088 Py_DECREF(iobj);
14089 if (res == NULL)
14090 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014091 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014092 return 0;
14093
14094wrongtype:
14095 PyErr_Format(PyExc_TypeError,
14096 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014097 "not %.200s",
14098 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014099 return -1;
14100}
14101
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014102static Py_UCS4
14103formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014104{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014105 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014106 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014107 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014108 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014109 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014110 goto onError;
14111 }
14112 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014113 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014114 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014115 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014116 /* if not, issue deprecation warning for now */
Ethan Furmandf3ed242014-01-05 06:50:30 -080014117 if (!PyLong_Check(v)) {
14118 iobj = PyNumber_Index(v);
14119 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014120 PyErr_Clear();
14121 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14122 "automatic int conversions have been deprecated",
14123 1)) {
14124 return -1;
14125 }
14126 iobj = PyNumber_Long(v);
14127 if (iobj == NULL ) {
14128 if (PyErr_ExceptionMatches(PyExc_TypeError))
14129 goto onError;
14130 return -1;
14131 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014132 }
14133 v = iobj;
14134 Py_DECREF(iobj);
14135 }
14136 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014137 x = PyLong_AsLong(v);
14138 if (x == -1 && PyErr_Occurred())
14139 goto onError;
14140
Victor Stinner8faf8212011-12-08 22:14:11 +010014141 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014142 PyErr_SetString(PyExc_OverflowError,
14143 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014144 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014145 }
14146
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014147 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014148 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014149
Benjamin Peterson29060642009-01-31 22:14:21 +000014150 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014151 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014152 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014153 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014154}
14155
Victor Stinnera47082312012-10-04 02:19:54 +020014156/* Parse options of an argument: flags, width, precision.
14157 Handle also "%(name)" syntax.
14158
14159 Return 0 if the argument has been formatted into arg->str.
14160 Return 1 if the argument has been written into ctx->writer,
14161 Raise an exception and return -1 on error. */
14162static int
14163unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14164 struct unicode_format_arg_t *arg)
14165{
14166#define FORMAT_READ(ctx) \
14167 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14168
14169 PyObject *v;
14170
Victor Stinnera47082312012-10-04 02:19:54 +020014171 if (arg->ch == '(') {
14172 /* Get argument value from a dictionary. Example: "%(name)s". */
14173 Py_ssize_t keystart;
14174 Py_ssize_t keylen;
14175 PyObject *key;
14176 int pcount = 1;
14177
14178 if (ctx->dict == NULL) {
14179 PyErr_SetString(PyExc_TypeError,
14180 "format requires a mapping");
14181 return -1;
14182 }
14183 ++ctx->fmtpos;
14184 --ctx->fmtcnt;
14185 keystart = ctx->fmtpos;
14186 /* Skip over balanced parentheses */
14187 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14188 arg->ch = FORMAT_READ(ctx);
14189 if (arg->ch == ')')
14190 --pcount;
14191 else if (arg->ch == '(')
14192 ++pcount;
14193 ctx->fmtpos++;
14194 }
14195 keylen = ctx->fmtpos - keystart - 1;
14196 if (ctx->fmtcnt < 0 || pcount > 0) {
14197 PyErr_SetString(PyExc_ValueError,
14198 "incomplete format key");
14199 return -1;
14200 }
14201 key = PyUnicode_Substring(ctx->fmtstr,
14202 keystart, keystart + keylen);
14203 if (key == NULL)
14204 return -1;
14205 if (ctx->args_owned) {
14206 Py_DECREF(ctx->args);
14207 ctx->args_owned = 0;
14208 }
14209 ctx->args = PyObject_GetItem(ctx->dict, key);
14210 Py_DECREF(key);
14211 if (ctx->args == NULL)
14212 return -1;
14213 ctx->args_owned = 1;
14214 ctx->arglen = -1;
14215 ctx->argidx = -2;
14216 }
14217
14218 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014219 while (--ctx->fmtcnt >= 0) {
14220 arg->ch = FORMAT_READ(ctx);
14221 ctx->fmtpos++;
14222 switch (arg->ch) {
14223 case '-': arg->flags |= F_LJUST; continue;
14224 case '+': arg->flags |= F_SIGN; continue;
14225 case ' ': arg->flags |= F_BLANK; continue;
14226 case '#': arg->flags |= F_ALT; continue;
14227 case '0': arg->flags |= F_ZERO; continue;
14228 }
14229 break;
14230 }
14231
14232 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014233 if (arg->ch == '*') {
14234 v = unicode_format_getnextarg(ctx);
14235 if (v == NULL)
14236 return -1;
14237 if (!PyLong_Check(v)) {
14238 PyErr_SetString(PyExc_TypeError,
14239 "* wants int");
14240 return -1;
14241 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014242 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014243 if (arg->width == -1 && PyErr_Occurred())
14244 return -1;
14245 if (arg->width < 0) {
14246 arg->flags |= F_LJUST;
14247 arg->width = -arg->width;
14248 }
14249 if (--ctx->fmtcnt >= 0) {
14250 arg->ch = FORMAT_READ(ctx);
14251 ctx->fmtpos++;
14252 }
14253 }
14254 else if (arg->ch >= '0' && arg->ch <= '9') {
14255 arg->width = arg->ch - '0';
14256 while (--ctx->fmtcnt >= 0) {
14257 arg->ch = FORMAT_READ(ctx);
14258 ctx->fmtpos++;
14259 if (arg->ch < '0' || arg->ch > '9')
14260 break;
14261 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14262 mixing signed and unsigned comparison. Since arg->ch is between
14263 '0' and '9', casting to int is safe. */
14264 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14265 PyErr_SetString(PyExc_ValueError,
14266 "width too big");
14267 return -1;
14268 }
14269 arg->width = arg->width*10 + (arg->ch - '0');
14270 }
14271 }
14272
14273 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014274 if (arg->ch == '.') {
14275 arg->prec = 0;
14276 if (--ctx->fmtcnt >= 0) {
14277 arg->ch = FORMAT_READ(ctx);
14278 ctx->fmtpos++;
14279 }
14280 if (arg->ch == '*') {
14281 v = unicode_format_getnextarg(ctx);
14282 if (v == NULL)
14283 return -1;
14284 if (!PyLong_Check(v)) {
14285 PyErr_SetString(PyExc_TypeError,
14286 "* wants int");
14287 return -1;
14288 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014289 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014290 if (arg->prec == -1 && PyErr_Occurred())
14291 return -1;
14292 if (arg->prec < 0)
14293 arg->prec = 0;
14294 if (--ctx->fmtcnt >= 0) {
14295 arg->ch = FORMAT_READ(ctx);
14296 ctx->fmtpos++;
14297 }
14298 }
14299 else if (arg->ch >= '0' && arg->ch <= '9') {
14300 arg->prec = arg->ch - '0';
14301 while (--ctx->fmtcnt >= 0) {
14302 arg->ch = FORMAT_READ(ctx);
14303 ctx->fmtpos++;
14304 if (arg->ch < '0' || arg->ch > '9')
14305 break;
14306 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14307 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014308 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014309 return -1;
14310 }
14311 arg->prec = arg->prec*10 + (arg->ch - '0');
14312 }
14313 }
14314 }
14315
14316 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14317 if (ctx->fmtcnt >= 0) {
14318 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14319 if (--ctx->fmtcnt >= 0) {
14320 arg->ch = FORMAT_READ(ctx);
14321 ctx->fmtpos++;
14322 }
14323 }
14324 }
14325 if (ctx->fmtcnt < 0) {
14326 PyErr_SetString(PyExc_ValueError,
14327 "incomplete format");
14328 return -1;
14329 }
14330 return 0;
14331
14332#undef FORMAT_READ
14333}
14334
14335/* Format one argument. Supported conversion specifiers:
14336
14337 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014338 - "i", "d", "u": int or float
14339 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014340 - "e", "E", "f", "F", "g", "G": float
14341 - "c": int or str (1 character)
14342
Victor Stinner8dbd4212012-12-04 09:30:24 +010014343 When possible, the output is written directly into the Unicode writer
14344 (ctx->writer). A string is created when padding is required.
14345
Victor Stinnera47082312012-10-04 02:19:54 +020014346 Return 0 if the argument has been formatted into *p_str,
14347 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014348 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014349static int
14350unicode_format_arg_format(struct unicode_formatter_t *ctx,
14351 struct unicode_format_arg_t *arg,
14352 PyObject **p_str)
14353{
14354 PyObject *v;
14355 _PyUnicodeWriter *writer = &ctx->writer;
14356
14357 if (ctx->fmtcnt == 0)
14358 ctx->writer.overallocate = 0;
14359
14360 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014361 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014362 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014363 return 1;
14364 }
14365
14366 v = unicode_format_getnextarg(ctx);
14367 if (v == NULL)
14368 return -1;
14369
Victor Stinnera47082312012-10-04 02:19:54 +020014370
14371 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014372 case 's':
14373 case 'r':
14374 case 'a':
14375 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14376 /* Fast path */
14377 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14378 return -1;
14379 return 1;
14380 }
14381
14382 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14383 *p_str = v;
14384 Py_INCREF(*p_str);
14385 }
14386 else {
14387 if (arg->ch == 's')
14388 *p_str = PyObject_Str(v);
14389 else if (arg->ch == 'r')
14390 *p_str = PyObject_Repr(v);
14391 else
14392 *p_str = PyObject_ASCII(v);
14393 }
14394 break;
14395
14396 case 'i':
14397 case 'd':
14398 case 'u':
14399 case 'o':
14400 case 'x':
14401 case 'X':
14402 {
14403 int ret = mainformatlong(v, arg, p_str, writer);
14404 if (ret != 0)
14405 return ret;
14406 arg->sign = 1;
14407 break;
14408 }
14409
14410 case 'e':
14411 case 'E':
14412 case 'f':
14413 case 'F':
14414 case 'g':
14415 case 'G':
14416 if (arg->width == -1 && arg->prec == -1
14417 && !(arg->flags & (F_SIGN | F_BLANK)))
14418 {
14419 /* Fast path */
14420 if (formatfloat(v, arg, NULL, writer) == -1)
14421 return -1;
14422 return 1;
14423 }
14424
14425 arg->sign = 1;
14426 if (formatfloat(v, arg, p_str, NULL) == -1)
14427 return -1;
14428 break;
14429
14430 case 'c':
14431 {
14432 Py_UCS4 ch = formatchar(v);
14433 if (ch == (Py_UCS4) -1)
14434 return -1;
14435 if (arg->width == -1 && arg->prec == -1) {
14436 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014437 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014438 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014439 return 1;
14440 }
14441 *p_str = PyUnicode_FromOrdinal(ch);
14442 break;
14443 }
14444
14445 default:
14446 PyErr_Format(PyExc_ValueError,
14447 "unsupported format character '%c' (0x%x) "
14448 "at index %zd",
14449 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14450 (int)arg->ch,
14451 ctx->fmtpos - 1);
14452 return -1;
14453 }
14454 if (*p_str == NULL)
14455 return -1;
14456 assert (PyUnicode_Check(*p_str));
14457 return 0;
14458}
14459
14460static int
14461unicode_format_arg_output(struct unicode_formatter_t *ctx,
14462 struct unicode_format_arg_t *arg,
14463 PyObject *str)
14464{
14465 Py_ssize_t len;
14466 enum PyUnicode_Kind kind;
14467 void *pbuf;
14468 Py_ssize_t pindex;
14469 Py_UCS4 signchar;
14470 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014471 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014472 Py_ssize_t sublen;
14473 _PyUnicodeWriter *writer = &ctx->writer;
14474 Py_UCS4 fill;
14475
14476 fill = ' ';
14477 if (arg->sign && arg->flags & F_ZERO)
14478 fill = '0';
14479
14480 if (PyUnicode_READY(str) == -1)
14481 return -1;
14482
14483 len = PyUnicode_GET_LENGTH(str);
14484 if ((arg->width == -1 || arg->width <= len)
14485 && (arg->prec == -1 || arg->prec >= len)
14486 && !(arg->flags & (F_SIGN | F_BLANK)))
14487 {
14488 /* Fast path */
14489 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14490 return -1;
14491 return 0;
14492 }
14493
14494 /* Truncate the string for "s", "r" and "a" formats
14495 if the precision is set */
14496 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14497 if (arg->prec >= 0 && len > arg->prec)
14498 len = arg->prec;
14499 }
14500
14501 /* Adjust sign and width */
14502 kind = PyUnicode_KIND(str);
14503 pbuf = PyUnicode_DATA(str);
14504 pindex = 0;
14505 signchar = '\0';
14506 if (arg->sign) {
14507 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14508 if (ch == '-' || ch == '+') {
14509 signchar = ch;
14510 len--;
14511 pindex++;
14512 }
14513 else if (arg->flags & F_SIGN)
14514 signchar = '+';
14515 else if (arg->flags & F_BLANK)
14516 signchar = ' ';
14517 else
14518 arg->sign = 0;
14519 }
14520 if (arg->width < len)
14521 arg->width = len;
14522
14523 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014524 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014525 if (!(arg->flags & F_LJUST)) {
14526 if (arg->sign) {
14527 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014528 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014529 }
14530 else {
14531 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014532 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014533 }
14534 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014535 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14536 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014537 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014538 }
14539
Victor Stinnera47082312012-10-04 02:19:54 +020014540 buflen = arg->width;
14541 if (arg->sign && len == arg->width)
14542 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014543 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014544 return -1;
14545
14546 /* Write the sign if needed */
14547 if (arg->sign) {
14548 if (fill != ' ') {
14549 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14550 writer->pos += 1;
14551 }
14552 if (arg->width > len)
14553 arg->width--;
14554 }
14555
14556 /* Write the numeric prefix for "x", "X" and "o" formats
14557 if the alternate form is used.
14558 For example, write "0x" for the "%#x" format. */
14559 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14560 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14561 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14562 if (fill != ' ') {
14563 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14564 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14565 writer->pos += 2;
14566 pindex += 2;
14567 }
14568 arg->width -= 2;
14569 if (arg->width < 0)
14570 arg->width = 0;
14571 len -= 2;
14572 }
14573
14574 /* Pad left with the fill character if needed */
14575 if (arg->width > len && !(arg->flags & F_LJUST)) {
14576 sublen = arg->width - len;
14577 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14578 writer->pos += sublen;
14579 arg->width = len;
14580 }
14581
14582 /* If padding with spaces: write sign if needed and/or numeric prefix if
14583 the alternate form is used */
14584 if (fill == ' ') {
14585 if (arg->sign) {
14586 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14587 writer->pos += 1;
14588 }
14589 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14590 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14591 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14592 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14593 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14594 writer->pos += 2;
14595 pindex += 2;
14596 }
14597 }
14598
14599 /* Write characters */
14600 if (len) {
14601 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14602 str, pindex, len);
14603 writer->pos += len;
14604 }
14605
14606 /* Pad right with the fill character if needed */
14607 if (arg->width > len) {
14608 sublen = arg->width - len;
14609 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14610 writer->pos += sublen;
14611 }
14612 return 0;
14613}
14614
14615/* Helper of PyUnicode_Format(): format one arg.
14616 Return 0 on success, raise an exception and return -1 on error. */
14617static int
14618unicode_format_arg(struct unicode_formatter_t *ctx)
14619{
14620 struct unicode_format_arg_t arg;
14621 PyObject *str;
14622 int ret;
14623
Victor Stinner8dbd4212012-12-04 09:30:24 +010014624 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14625 arg.flags = 0;
14626 arg.width = -1;
14627 arg.prec = -1;
14628 arg.sign = 0;
14629 str = NULL;
14630
Victor Stinnera47082312012-10-04 02:19:54 +020014631 ret = unicode_format_arg_parse(ctx, &arg);
14632 if (ret == -1)
14633 return -1;
14634
14635 ret = unicode_format_arg_format(ctx, &arg, &str);
14636 if (ret == -1)
14637 return -1;
14638
14639 if (ret != 1) {
14640 ret = unicode_format_arg_output(ctx, &arg, str);
14641 Py_DECREF(str);
14642 if (ret == -1)
14643 return -1;
14644 }
14645
14646 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14647 PyErr_SetString(PyExc_TypeError,
14648 "not all arguments converted during string formatting");
14649 return -1;
14650 }
14651 return 0;
14652}
14653
Alexander Belopolsky40018472011-02-26 01:02:56 +000014654PyObject *
14655PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014656{
Victor Stinnera47082312012-10-04 02:19:54 +020014657 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014658
Guido van Rossumd57fd912000-03-10 22:53:23 +000014659 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014660 PyErr_BadInternalCall();
14661 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014662 }
Victor Stinnera47082312012-10-04 02:19:54 +020014663
14664 ctx.fmtstr = PyUnicode_FromObject(format);
14665 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014666 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014667 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14668 Py_DECREF(ctx.fmtstr);
14669 return NULL;
14670 }
14671 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14672 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14673 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14674 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014675
Victor Stinner8f674cc2013-04-17 23:02:17 +020014676 _PyUnicodeWriter_Init(&ctx.writer);
14677 ctx.writer.min_length = ctx.fmtcnt + 100;
14678 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014679
Guido van Rossumd57fd912000-03-10 22:53:23 +000014680 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014681 ctx.arglen = PyTuple_Size(args);
14682 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014683 }
14684 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014685 ctx.arglen = -1;
14686 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014687 }
Victor Stinnera47082312012-10-04 02:19:54 +020014688 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014689 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014690 ctx.dict = args;
14691 else
14692 ctx.dict = NULL;
14693 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014694
Victor Stinnera47082312012-10-04 02:19:54 +020014695 while (--ctx.fmtcnt >= 0) {
14696 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014697 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014698
14699 nonfmtpos = ctx.fmtpos++;
14700 while (ctx.fmtcnt >= 0 &&
14701 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14702 ctx.fmtpos++;
14703 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014704 }
Victor Stinnera47082312012-10-04 02:19:54 +020014705 if (ctx.fmtcnt < 0) {
14706 ctx.fmtpos--;
14707 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014708 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014709
Victor Stinnercfc4c132013-04-03 01:48:39 +020014710 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14711 nonfmtpos, ctx.fmtpos) < 0)
14712 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014713 }
14714 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014715 ctx.fmtpos++;
14716 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014717 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014718 }
14719 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014720
Victor Stinnera47082312012-10-04 02:19:54 +020014721 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014722 PyErr_SetString(PyExc_TypeError,
14723 "not all arguments converted during string formatting");
14724 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014725 }
14726
Victor Stinnera47082312012-10-04 02:19:54 +020014727 if (ctx.args_owned) {
14728 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014729 }
Victor Stinnera47082312012-10-04 02:19:54 +020014730 Py_DECREF(ctx.fmtstr);
14731 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014732
Benjamin Peterson29060642009-01-31 22:14:21 +000014733 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014734 Py_DECREF(ctx.fmtstr);
14735 _PyUnicodeWriter_Dealloc(&ctx.writer);
14736 if (ctx.args_owned) {
14737 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014738 }
14739 return NULL;
14740}
14741
Jeremy Hylton938ace62002-07-17 16:30:39 +000014742static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014743unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14744
Tim Peters6d6c1a32001-08-02 04:15:00 +000014745static PyObject *
14746unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14747{
Benjamin Peterson29060642009-01-31 22:14:21 +000014748 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014749 static char *kwlist[] = {"object", "encoding", "errors", 0};
14750 char *encoding = NULL;
14751 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014752
Benjamin Peterson14339b62009-01-31 16:36:08 +000014753 if (type != &PyUnicode_Type)
14754 return unicode_subtype_new(type, args, kwds);
14755 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014756 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014757 return NULL;
14758 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014759 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014760 if (encoding == NULL && errors == NULL)
14761 return PyObject_Str(x);
14762 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014763 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014764}
14765
Guido van Rossume023fe02001-08-30 03:12:59 +000014766static PyObject *
14767unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14768{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014769 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014770 Py_ssize_t length, char_size;
14771 int share_wstr, share_utf8;
14772 unsigned int kind;
14773 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014774
Benjamin Peterson14339b62009-01-31 16:36:08 +000014775 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014776
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014777 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014778 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014779 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014780 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014781 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014782 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014783 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014784 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014785
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014786 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014787 if (self == NULL) {
14788 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014789 return NULL;
14790 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014791 kind = PyUnicode_KIND(unicode);
14792 length = PyUnicode_GET_LENGTH(unicode);
14793
14794 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014795#ifdef Py_DEBUG
14796 _PyUnicode_HASH(self) = -1;
14797#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014798 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014799#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014800 _PyUnicode_STATE(self).interned = 0;
14801 _PyUnicode_STATE(self).kind = kind;
14802 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014803 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014804 _PyUnicode_STATE(self).ready = 1;
14805 _PyUnicode_WSTR(self) = NULL;
14806 _PyUnicode_UTF8_LENGTH(self) = 0;
14807 _PyUnicode_UTF8(self) = NULL;
14808 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014809 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014810
14811 share_utf8 = 0;
14812 share_wstr = 0;
14813 if (kind == PyUnicode_1BYTE_KIND) {
14814 char_size = 1;
14815 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14816 share_utf8 = 1;
14817 }
14818 else if (kind == PyUnicode_2BYTE_KIND) {
14819 char_size = 2;
14820 if (sizeof(wchar_t) == 2)
14821 share_wstr = 1;
14822 }
14823 else {
14824 assert(kind == PyUnicode_4BYTE_KIND);
14825 char_size = 4;
14826 if (sizeof(wchar_t) == 4)
14827 share_wstr = 1;
14828 }
14829
14830 /* Ensure we won't overflow the length. */
14831 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14832 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014833 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014834 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014835 data = PyObject_MALLOC((length + 1) * char_size);
14836 if (data == NULL) {
14837 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014838 goto onError;
14839 }
14840
Victor Stinnerc3c74152011-10-02 20:39:55 +020014841 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014842 if (share_utf8) {
14843 _PyUnicode_UTF8_LENGTH(self) = length;
14844 _PyUnicode_UTF8(self) = data;
14845 }
14846 if (share_wstr) {
14847 _PyUnicode_WSTR_LENGTH(self) = length;
14848 _PyUnicode_WSTR(self) = (wchar_t *)data;
14849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014850
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014851 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014852 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014853 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014854#ifdef Py_DEBUG
14855 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14856#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014857 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014858 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014859
14860onError:
14861 Py_DECREF(unicode);
14862 Py_DECREF(self);
14863 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014864}
14865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014866PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014867"str(object='') -> str\n\
14868str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014869\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014870Create a new string object from the given object. If encoding or\n\
14871errors is specified, then the object must expose a data buffer\n\
14872that will be decoded using the given encoding and error handler.\n\
14873Otherwise, returns the result of object.__str__() (if defined)\n\
14874or repr(object).\n\
14875encoding defaults to sys.getdefaultencoding().\n\
14876errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014877
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014878static PyObject *unicode_iter(PyObject *seq);
14879
Guido van Rossumd57fd912000-03-10 22:53:23 +000014880PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014881 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014882 "str", /* tp_name */
14883 sizeof(PyUnicodeObject), /* tp_size */
14884 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014885 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014886 (destructor)unicode_dealloc, /* tp_dealloc */
14887 0, /* tp_print */
14888 0, /* tp_getattr */
14889 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014890 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014891 unicode_repr, /* tp_repr */
14892 &unicode_as_number, /* tp_as_number */
14893 &unicode_as_sequence, /* tp_as_sequence */
14894 &unicode_as_mapping, /* tp_as_mapping */
14895 (hashfunc) unicode_hash, /* tp_hash*/
14896 0, /* tp_call*/
14897 (reprfunc) unicode_str, /* tp_str */
14898 PyObject_GenericGetAttr, /* tp_getattro */
14899 0, /* tp_setattro */
14900 0, /* tp_as_buffer */
14901 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014902 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014903 unicode_doc, /* tp_doc */
14904 0, /* tp_traverse */
14905 0, /* tp_clear */
14906 PyUnicode_RichCompare, /* tp_richcompare */
14907 0, /* tp_weaklistoffset */
14908 unicode_iter, /* tp_iter */
14909 0, /* tp_iternext */
14910 unicode_methods, /* tp_methods */
14911 0, /* tp_members */
14912 0, /* tp_getset */
14913 &PyBaseObject_Type, /* tp_base */
14914 0, /* tp_dict */
14915 0, /* tp_descr_get */
14916 0, /* tp_descr_set */
14917 0, /* tp_dictoffset */
14918 0, /* tp_init */
14919 0, /* tp_alloc */
14920 unicode_new, /* tp_new */
14921 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014922};
14923
14924/* Initialize the Unicode implementation */
14925
Victor Stinner3a50e702011-10-18 21:21:00 +020014926int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014927{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014928 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014929 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014930 0x000A, /* LINE FEED */
14931 0x000D, /* CARRIAGE RETURN */
14932 0x001C, /* FILE SEPARATOR */
14933 0x001D, /* GROUP SEPARATOR */
14934 0x001E, /* RECORD SEPARATOR */
14935 0x0085, /* NEXT LINE */
14936 0x2028, /* LINE SEPARATOR */
14937 0x2029, /* PARAGRAPH SEPARATOR */
14938 };
14939
Fred Drakee4315f52000-05-09 19:53:39 +000014940 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014941 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014942 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014943 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014944 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014945
Guido van Rossumcacfc072002-05-24 19:01:59 +000014946 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014947 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014948
14949 /* initialize the linebreak bloom filter */
14950 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014951 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014952 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014953
Christian Heimes26532f72013-07-20 14:57:16 +020014954 if (PyType_Ready(&EncodingMapType) < 0)
14955 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014956
Benjamin Petersonc4311282012-10-30 23:21:10 -040014957 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14958 Py_FatalError("Can't initialize field name iterator type");
14959
14960 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14961 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014962
Victor Stinner3a50e702011-10-18 21:21:00 +020014963#ifdef HAVE_MBCS
14964 winver.dwOSVersionInfoSize = sizeof(winver);
14965 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14966 PyErr_SetFromWindowsErr(0);
14967 return -1;
14968 }
14969#endif
14970 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014971}
14972
14973/* Finalize the Unicode implementation */
14974
Christian Heimesa156e092008-02-16 07:38:31 +000014975int
14976PyUnicode_ClearFreeList(void)
14977{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014978 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014979}
14980
Guido van Rossumd57fd912000-03-10 22:53:23 +000014981void
Thomas Wouters78890102000-07-22 19:25:51 +000014982_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014983{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014984 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014985
Serhiy Storchaka05997252013-01-26 12:14:02 +020014986 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014987
Serhiy Storchaka05997252013-01-26 12:14:02 +020014988 for (i = 0; i < 256; i++)
14989 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014990 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014991 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014992}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014993
Walter Dörwald16807132007-05-25 13:52:07 +000014994void
14995PyUnicode_InternInPlace(PyObject **p)
14996{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014997 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014998 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014999#ifdef Py_DEBUG
15000 assert(s != NULL);
15001 assert(_PyUnicode_CHECK(s));
15002#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015003 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015004 return;
15005#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015006 /* If it's a subclass, we don't really know what putting
15007 it in the interned dict might do. */
15008 if (!PyUnicode_CheckExact(s))
15009 return;
15010 if (PyUnicode_CHECK_INTERNED(s))
15011 return;
15012 if (interned == NULL) {
15013 interned = PyDict_New();
15014 if (interned == NULL) {
15015 PyErr_Clear(); /* Don't leave an exception */
15016 return;
15017 }
15018 }
15019 /* It might be that the GetItem call fails even
15020 though the key is present in the dictionary,
15021 namely when this happens during a stack overflow. */
15022 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015023 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015024 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015025
Victor Stinnerf0335102013-04-14 19:13:03 +020015026 if (t) {
15027 Py_INCREF(t);
15028 Py_DECREF(*p);
15029 *p = t;
15030 return;
15031 }
Walter Dörwald16807132007-05-25 13:52:07 +000015032
Benjamin Peterson14339b62009-01-31 16:36:08 +000015033 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015034 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015035 PyErr_Clear();
15036 PyThreadState_GET()->recursion_critical = 0;
15037 return;
15038 }
15039 PyThreadState_GET()->recursion_critical = 0;
15040 /* The two references in interned are not counted by refcnt.
15041 The deallocator will take care of this */
15042 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015043 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015044}
15045
15046void
15047PyUnicode_InternImmortal(PyObject **p)
15048{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015049 PyUnicode_InternInPlace(p);
15050 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015051 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015052 Py_INCREF(*p);
15053 }
Walter Dörwald16807132007-05-25 13:52:07 +000015054}
15055
15056PyObject *
15057PyUnicode_InternFromString(const char *cp)
15058{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015059 PyObject *s = PyUnicode_FromString(cp);
15060 if (s == NULL)
15061 return NULL;
15062 PyUnicode_InternInPlace(&s);
15063 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015064}
15065
Alexander Belopolsky40018472011-02-26 01:02:56 +000015066void
15067_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015068{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015069 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015070 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 Py_ssize_t i, n;
15072 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015073
Benjamin Peterson14339b62009-01-31 16:36:08 +000015074 if (interned == NULL || !PyDict_Check(interned))
15075 return;
15076 keys = PyDict_Keys(interned);
15077 if (keys == NULL || !PyList_Check(keys)) {
15078 PyErr_Clear();
15079 return;
15080 }
Walter Dörwald16807132007-05-25 13:52:07 +000015081
Benjamin Peterson14339b62009-01-31 16:36:08 +000015082 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15083 detector, interned unicode strings are not forcibly deallocated;
15084 rather, we give them their stolen references back, and then clear
15085 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015086
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 n = PyList_GET_SIZE(keys);
15088 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015089 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015091 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015092 if (PyUnicode_READY(s) == -1) {
15093 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015094 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015095 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015096 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015097 case SSTATE_NOT_INTERNED:
15098 /* XXX Shouldn't happen */
15099 break;
15100 case SSTATE_INTERNED_IMMORTAL:
15101 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015102 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 break;
15104 case SSTATE_INTERNED_MORTAL:
15105 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015106 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 break;
15108 default:
15109 Py_FatalError("Inconsistent interned string state.");
15110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015111 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 }
15113 fprintf(stderr, "total size of all interned strings: "
15114 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15115 "mortal/immortal\n", mortal_size, immortal_size);
15116 Py_DECREF(keys);
15117 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015118 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015119}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015120
15121
15122/********************* Unicode Iterator **************************/
15123
15124typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015125 PyObject_HEAD
15126 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015127 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015128} unicodeiterobject;
15129
15130static void
15131unicodeiter_dealloc(unicodeiterobject *it)
15132{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015133 _PyObject_GC_UNTRACK(it);
15134 Py_XDECREF(it->it_seq);
15135 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015136}
15137
15138static int
15139unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15140{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 Py_VISIT(it->it_seq);
15142 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015143}
15144
15145static PyObject *
15146unicodeiter_next(unicodeiterobject *it)
15147{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015148 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015149
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 assert(it != NULL);
15151 seq = it->it_seq;
15152 if (seq == NULL)
15153 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015154 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015156 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15157 int kind = PyUnicode_KIND(seq);
15158 void *data = PyUnicode_DATA(seq);
15159 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15160 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 if (item != NULL)
15162 ++it->it_index;
15163 return item;
15164 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015165
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 Py_DECREF(seq);
15167 it->it_seq = NULL;
15168 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015169}
15170
15171static PyObject *
15172unicodeiter_len(unicodeiterobject *it)
15173{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015174 Py_ssize_t len = 0;
15175 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015176 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015178}
15179
15180PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15181
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015182static PyObject *
15183unicodeiter_reduce(unicodeiterobject *it)
15184{
15185 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015186 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015187 it->it_seq, it->it_index);
15188 } else {
15189 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15190 if (u == NULL)
15191 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015192 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015193 }
15194}
15195
15196PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15197
15198static PyObject *
15199unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15200{
15201 Py_ssize_t index = PyLong_AsSsize_t(state);
15202 if (index == -1 && PyErr_Occurred())
15203 return NULL;
15204 if (index < 0)
15205 index = 0;
15206 it->it_index = index;
15207 Py_RETURN_NONE;
15208}
15209
15210PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15211
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015212static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015213 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015214 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015215 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15216 reduce_doc},
15217 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15218 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015219 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015220};
15221
15222PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015223 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15224 "str_iterator", /* tp_name */
15225 sizeof(unicodeiterobject), /* tp_basicsize */
15226 0, /* tp_itemsize */
15227 /* methods */
15228 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15229 0, /* tp_print */
15230 0, /* tp_getattr */
15231 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015232 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015233 0, /* tp_repr */
15234 0, /* tp_as_number */
15235 0, /* tp_as_sequence */
15236 0, /* tp_as_mapping */
15237 0, /* tp_hash */
15238 0, /* tp_call */
15239 0, /* tp_str */
15240 PyObject_GenericGetAttr, /* tp_getattro */
15241 0, /* tp_setattro */
15242 0, /* tp_as_buffer */
15243 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15244 0, /* tp_doc */
15245 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15246 0, /* tp_clear */
15247 0, /* tp_richcompare */
15248 0, /* tp_weaklistoffset */
15249 PyObject_SelfIter, /* tp_iter */
15250 (iternextfunc)unicodeiter_next, /* tp_iternext */
15251 unicodeiter_methods, /* tp_methods */
15252 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015253};
15254
15255static PyObject *
15256unicode_iter(PyObject *seq)
15257{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015258 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015259
Benjamin Peterson14339b62009-01-31 16:36:08 +000015260 if (!PyUnicode_Check(seq)) {
15261 PyErr_BadInternalCall();
15262 return NULL;
15263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015264 if (PyUnicode_READY(seq) == -1)
15265 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015266 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15267 if (it == NULL)
15268 return NULL;
15269 it->it_index = 0;
15270 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015271 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015272 _PyObject_GC_TRACK(it);
15273 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015274}
15275
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015276
15277size_t
15278Py_UNICODE_strlen(const Py_UNICODE *u)
15279{
15280 int res = 0;
15281 while(*u++)
15282 res++;
15283 return res;
15284}
15285
15286Py_UNICODE*
15287Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15288{
15289 Py_UNICODE *u = s1;
15290 while ((*u++ = *s2++));
15291 return s1;
15292}
15293
15294Py_UNICODE*
15295Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15296{
15297 Py_UNICODE *u = s1;
15298 while ((*u++ = *s2++))
15299 if (n-- == 0)
15300 break;
15301 return s1;
15302}
15303
15304Py_UNICODE*
15305Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15306{
15307 Py_UNICODE *u1 = s1;
15308 u1 += Py_UNICODE_strlen(u1);
15309 Py_UNICODE_strcpy(u1, s2);
15310 return s1;
15311}
15312
15313int
15314Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15315{
15316 while (*s1 && *s2 && *s1 == *s2)
15317 s1++, s2++;
15318 if (*s1 && *s2)
15319 return (*s1 < *s2) ? -1 : +1;
15320 if (*s1)
15321 return 1;
15322 if (*s2)
15323 return -1;
15324 return 0;
15325}
15326
15327int
15328Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15329{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015330 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015331 for (; n != 0; n--) {
15332 u1 = *s1;
15333 u2 = *s2;
15334 if (u1 != u2)
15335 return (u1 < u2) ? -1 : +1;
15336 if (u1 == '\0')
15337 return 0;
15338 s1++;
15339 s2++;
15340 }
15341 return 0;
15342}
15343
15344Py_UNICODE*
15345Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15346{
15347 const Py_UNICODE *p;
15348 for (p = s; *p; p++)
15349 if (*p == c)
15350 return (Py_UNICODE*)p;
15351 return NULL;
15352}
15353
15354Py_UNICODE*
15355Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15356{
15357 const Py_UNICODE *p;
15358 p = s + Py_UNICODE_strlen(s);
15359 while (p != s) {
15360 p--;
15361 if (*p == c)
15362 return (Py_UNICODE*)p;
15363 }
15364 return NULL;
15365}
Victor Stinner331ea922010-08-10 16:37:20 +000015366
Victor Stinner71133ff2010-09-01 23:43:53 +000015367Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015368PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015369{
Victor Stinner577db2c2011-10-11 22:12:48 +020015370 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015371 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015373 if (!PyUnicode_Check(unicode)) {
15374 PyErr_BadArgument();
15375 return NULL;
15376 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015377 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015378 if (u == NULL)
15379 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015380 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015381 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015382 PyErr_NoMemory();
15383 return NULL;
15384 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015385 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015386 size *= sizeof(Py_UNICODE);
15387 copy = PyMem_Malloc(size);
15388 if (copy == NULL) {
15389 PyErr_NoMemory();
15390 return NULL;
15391 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015392 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015393 return copy;
15394}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015395
Georg Brandl66c221e2010-10-14 07:04:07 +000015396/* A _string module, to export formatter_parser and formatter_field_name_split
15397 to the string.Formatter class implemented in Python. */
15398
15399static PyMethodDef _string_methods[] = {
15400 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15401 METH_O, PyDoc_STR("split the argument as a field name")},
15402 {"formatter_parser", (PyCFunction) formatter_parser,
15403 METH_O, PyDoc_STR("parse the argument as a format string")},
15404 {NULL, NULL}
15405};
15406
15407static struct PyModuleDef _string_module = {
15408 PyModuleDef_HEAD_INIT,
15409 "_string",
15410 PyDoc_STR("string helper module"),
15411 0,
15412 _string_methods,
15413 NULL,
15414 NULL,
15415 NULL,
15416 NULL
15417};
15418
15419PyMODINIT_FUNC
15420PyInit__string(void)
15421{
15422 return PyModule_Create(&_string_module);
15423}
15424
15425
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015426#ifdef __cplusplus
15427}
15428#endif