blob: f59af0a2d0c83971232e244e8db0bc435003e0ba [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
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300730 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100731 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 */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700819 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200820 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. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700891 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000892 return (PyUnicodeObject *)PyErr_NoMemory();
893 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894 if (length < 0) {
895 PyErr_SetString(PyExc_SystemError,
896 "Negative size passed to _PyUnicode_New");
897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000898 }
899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
901 if (unicode == NULL)
902 return NULL;
903 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100904
905 _PyUnicode_WSTR_LENGTH(unicode) = length;
906 _PyUnicode_HASH(unicode) = -1;
907 _PyUnicode_STATE(unicode).interned = 0;
908 _PyUnicode_STATE(unicode).kind = 0;
909 _PyUnicode_STATE(unicode).compact = 0;
910 _PyUnicode_STATE(unicode).ready = 0;
911 _PyUnicode_STATE(unicode).ascii = 0;
912 _PyUnicode_DATA_ANY(unicode) = NULL;
913 _PyUnicode_LENGTH(unicode) = 0;
914 _PyUnicode_UTF8(unicode) = NULL;
915 _PyUnicode_UTF8_LENGTH(unicode) = 0;
916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
918 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100919 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000920 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100921 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000922 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
Jeremy Hyltond8082792003-09-16 19:41:39 +0000924 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000925 * the caller fails before initializing str -- unicode_resize()
926 * reads str[0], and the Keep-Alive optimization can keep memory
927 * allocated for str alive across a call to unicode_dealloc(unicode).
928 * We don't want unicode_resize to read uninitialized memory in
929 * that case.
930 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 _PyUnicode_WSTR(unicode)[0] = 0;
932 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100933
Victor Stinner7931d9a2011-11-04 00:22:48 +0100934 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000935 return unicode;
936}
937
Victor Stinnerf42dc442011-10-02 23:33:16 +0200938static const char*
939unicode_kind_name(PyObject *unicode)
940{
Victor Stinner42dfd712011-10-03 14:41:45 +0200941 /* don't check consistency: unicode_kind_name() is called from
942 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 if (!PyUnicode_IS_COMPACT(unicode))
944 {
945 if (!PyUnicode_IS_READY(unicode))
946 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600947 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 {
949 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200951 return "legacy ascii";
952 else
953 return "legacy latin1";
954 case PyUnicode_2BYTE_KIND:
955 return "legacy UCS2";
956 case PyUnicode_4BYTE_KIND:
957 return "legacy UCS4";
958 default:
959 return "<legacy invalid kind>";
960 }
961 }
962 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600963 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200965 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200966 return "ascii";
967 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200972 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200973 default:
974 return "<invalid compact kind>";
975 }
976}
977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979/* Functions wrapping macros for use in debugger */
980char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200981 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982}
983
984void *_PyUnicode_compact_data(void *unicode) {
985 return _PyUnicode_COMPACT_DATA(unicode);
986}
987void *_PyUnicode_data(void *unicode){
988 printf("obj %p\n", unicode);
989 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
990 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
991 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
992 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
993 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
994 return PyUnicode_DATA(unicode);
995}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200996
997void
998_PyUnicode_Dump(PyObject *op)
999{
1000 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1002 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1003 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001004
Victor Stinnera849a4b2011-10-03 12:12:11 +02001005 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 {
1007 if (ascii->state.ascii)
1008 data = (ascii + 1);
1009 else
1010 data = (compact + 1);
1011 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001012 else
1013 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001014 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1015 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001016
Victor Stinnera849a4b2011-10-03 12:12:11 +02001017 if (ascii->wstr == data)
1018 printf("shared ");
1019 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001020
Victor Stinnera3b334d2011-10-03 13:53:37 +02001021 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001022 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001023 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1024 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001025 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1026 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001027 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001028 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001029}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030#endif
1031
1032PyObject *
1033PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1034{
1035 PyObject *obj;
1036 PyCompactUnicodeObject *unicode;
1037 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001038 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001039 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 Py_ssize_t char_size;
1041 Py_ssize_t struct_size;
1042
1043 /* Optimization for empty strings */
1044 if (size == 0 && unicode_empty != NULL) {
1045 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001046 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 }
1048
Victor Stinner9e9d6892011-10-04 01:02:02 +02001049 is_ascii = 0;
1050 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051 struct_size = sizeof(PyCompactUnicodeObject);
1052 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001053 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 char_size = 1;
1055 is_ascii = 1;
1056 struct_size = sizeof(PyASCIIObject);
1057 }
1058 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001059 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 char_size = 1;
1061 }
1062 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001063 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 char_size = 2;
1065 if (sizeof(wchar_t) == 2)
1066 is_sharing = 1;
1067 }
1068 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001069 if (maxchar > MAX_UNICODE) {
1070 PyErr_SetString(PyExc_SystemError,
1071 "invalid maximum character passed to PyUnicode_New");
1072 return NULL;
1073 }
Victor Stinner8f825062012-04-27 13:55:39 +02001074 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075 char_size = 4;
1076 if (sizeof(wchar_t) == 4)
1077 is_sharing = 1;
1078 }
1079
1080 /* Ensure we won't overflow the size. */
1081 if (size < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to PyUnicode_New");
1084 return NULL;
1085 }
1086 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1087 return PyErr_NoMemory();
1088
1089 /* Duplicated allocation code from _PyObject_New() instead of a call to
1090 * PyObject_New() so we are able to allocate space for the object and
1091 * it's data buffer.
1092 */
1093 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1094 if (obj == NULL)
1095 return PyErr_NoMemory();
1096 obj = PyObject_INIT(obj, &PyUnicode_Type);
1097 if (obj == NULL)
1098 return NULL;
1099
1100 unicode = (PyCompactUnicodeObject *)obj;
1101 if (is_ascii)
1102 data = ((PyASCIIObject*)obj) + 1;
1103 else
1104 data = unicode + 1;
1105 _PyUnicode_LENGTH(unicode) = size;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001108 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109 _PyUnicode_STATE(unicode).compact = 1;
1110 _PyUnicode_STATE(unicode).ready = 1;
1111 _PyUnicode_STATE(unicode).ascii = is_ascii;
1112 if (is_ascii) {
1113 ((char*)data)[size] = 0;
1114 _PyUnicode_WSTR(unicode) = NULL;
1115 }
Victor Stinner8f825062012-04-27 13:55:39 +02001116 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 ((char*)data)[size] = 0;
1118 _PyUnicode_WSTR(unicode) = NULL;
1119 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001121 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 else {
1124 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001125 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001126 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001127 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001128 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129 ((Py_UCS4*)data)[size] = 0;
1130 if (is_sharing) {
1131 _PyUnicode_WSTR_LENGTH(unicode) = size;
1132 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1133 }
1134 else {
1135 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1136 _PyUnicode_WSTR(unicode) = NULL;
1137 }
1138 }
Victor Stinner8f825062012-04-27 13:55:39 +02001139#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001140 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001141#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001142 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 return obj;
1144}
1145
1146#if SIZEOF_WCHAR_T == 2
1147/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1148 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001149 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
1151 This function assumes that unicode can hold one more code point than wstr
1152 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001153static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001154unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001155 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
1157 const wchar_t *iter;
1158 Py_UCS4 *ucs4_out;
1159
Victor Stinner910337b2011-10-03 03:20:16 +02001160 assert(unicode != NULL);
1161 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001162 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1163 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1164
1165 for (iter = begin; iter < end; ) {
1166 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1167 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001168 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1169 && (iter+1) < end
1170 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001171 {
Victor Stinner551ac952011-11-29 22:58:13 +01001172 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 iter += 2;
1174 }
1175 else {
1176 *ucs4_out++ = *iter;
1177 iter++;
1178 }
1179 }
1180 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1181 _PyUnicode_GET_LENGTH(unicode)));
1182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001183}
1184#endif
1185
Victor Stinnercd9950f2011-10-02 00:34:53 +02001186static int
Victor Stinner488fa492011-12-12 00:01:39 +01001187unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001188{
Victor Stinner488fa492011-12-12 00:01:39 +01001189 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001190 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001191 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001192 return -1;
1193 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001194 return 0;
1195}
1196
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001197static int
1198_copy_characters(PyObject *to, Py_ssize_t to_start,
1199 PyObject *from, Py_ssize_t from_start,
1200 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001202 unsigned int from_kind, to_kind;
1203 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204
Victor Stinneree4544c2012-05-09 22:24:08 +02001205 assert(0 <= how_many);
1206 assert(0 <= from_start);
1207 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001208 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001209 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001210 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211
Victor Stinnerd3f08822012-05-29 12:57:52 +02001212 assert(PyUnicode_Check(to));
1213 assert(PyUnicode_IS_READY(to));
1214 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1215
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001216 if (how_many == 0)
1217 return 0;
1218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001222 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223
Victor Stinnerf1852262012-06-16 16:38:26 +02001224#ifdef Py_DEBUG
1225 if (!check_maxchar
1226 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1227 {
1228 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1229 Py_UCS4 ch;
1230 Py_ssize_t i;
1231 for (i=0; i < how_many; i++) {
1232 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1233 assert(ch <= to_maxchar);
1234 }
1235 }
1236#endif
1237
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001238 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001239 if (check_maxchar
1240 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1241 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001242 /* Writing Latin-1 characters into an ASCII string requires to
1243 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001244 Py_UCS4 max_char;
1245 max_char = ucs1lib_find_max_char(from_data,
1246 (Py_UCS1*)from_data + how_many);
1247 if (max_char >= 128)
1248 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001249 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001250 Py_MEMCPY((char*)to_data + to_kind * to_start,
1251 (char*)from_data + from_kind * from_start,
1252 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001253 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001254 else if (from_kind == PyUnicode_1BYTE_KIND
1255 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001256 {
1257 _PyUnicode_CONVERT_BYTES(
1258 Py_UCS1, Py_UCS2,
1259 PyUnicode_1BYTE_DATA(from) + from_start,
1260 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1261 PyUnicode_2BYTE_DATA(to) + to_start
1262 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001263 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001264 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001265 && to_kind == PyUnicode_4BYTE_KIND)
1266 {
1267 _PyUnicode_CONVERT_BYTES(
1268 Py_UCS1, Py_UCS4,
1269 PyUnicode_1BYTE_DATA(from) + from_start,
1270 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1271 PyUnicode_4BYTE_DATA(to) + to_start
1272 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001273 }
1274 else if (from_kind == PyUnicode_2BYTE_KIND
1275 && to_kind == PyUnicode_4BYTE_KIND)
1276 {
1277 _PyUnicode_CONVERT_BYTES(
1278 Py_UCS2, Py_UCS4,
1279 PyUnicode_2BYTE_DATA(from) + from_start,
1280 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1281 PyUnicode_4BYTE_DATA(to) + to_start
1282 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001283 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001284 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001285 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1286
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001287 if (!check_maxchar) {
1288 if (from_kind == PyUnicode_2BYTE_KIND
1289 && to_kind == PyUnicode_1BYTE_KIND)
1290 {
1291 _PyUnicode_CONVERT_BYTES(
1292 Py_UCS2, Py_UCS1,
1293 PyUnicode_2BYTE_DATA(from) + from_start,
1294 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1295 PyUnicode_1BYTE_DATA(to) + to_start
1296 );
1297 }
1298 else if (from_kind == PyUnicode_4BYTE_KIND
1299 && to_kind == PyUnicode_1BYTE_KIND)
1300 {
1301 _PyUnicode_CONVERT_BYTES(
1302 Py_UCS4, Py_UCS1,
1303 PyUnicode_4BYTE_DATA(from) + from_start,
1304 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1305 PyUnicode_1BYTE_DATA(to) + to_start
1306 );
1307 }
1308 else if (from_kind == PyUnicode_4BYTE_KIND
1309 && to_kind == PyUnicode_2BYTE_KIND)
1310 {
1311 _PyUnicode_CONVERT_BYTES(
1312 Py_UCS4, Py_UCS2,
1313 PyUnicode_4BYTE_DATA(from) + from_start,
1314 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1315 PyUnicode_2BYTE_DATA(to) + to_start
1316 );
1317 }
1318 else {
1319 assert(0);
1320 return -1;
1321 }
1322 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001323 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001325 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001326 Py_ssize_t i;
1327
Victor Stinnera0702ab2011-09-29 14:14:38 +02001328 for (i=0; i < how_many; i++) {
1329 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001330 if (ch > to_maxchar)
1331 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001332 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1333 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001334 }
1335 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001336 return 0;
1337}
1338
Victor Stinnerd3f08822012-05-29 12:57:52 +02001339void
1340_PyUnicode_FastCopyCharacters(
1341 PyObject *to, Py_ssize_t to_start,
1342 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001343{
1344 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1345}
1346
1347Py_ssize_t
1348PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1349 PyObject *from, Py_ssize_t from_start,
1350 Py_ssize_t how_many)
1351{
1352 int err;
1353
1354 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1355 PyErr_BadInternalCall();
1356 return -1;
1357 }
1358
Benjamin Petersonbac79492012-01-14 13:34:47 -05001359 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001360 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001361 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001362 return -1;
1363
Victor Stinnerd3f08822012-05-29 12:57:52 +02001364 if (from_start < 0) {
1365 PyErr_SetString(PyExc_IndexError, "string index out of range");
1366 return -1;
1367 }
1368 if (to_start < 0) {
1369 PyErr_SetString(PyExc_IndexError, "string index out of range");
1370 return -1;
1371 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001372 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1373 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1374 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001375 "Cannot write %zi characters at %zi "
1376 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377 how_many, to_start, PyUnicode_GET_LENGTH(to));
1378 return -1;
1379 }
1380
1381 if (how_many == 0)
1382 return 0;
1383
Victor Stinner488fa492011-12-12 00:01:39 +01001384 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385 return -1;
1386
1387 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1388 if (err) {
1389 PyErr_Format(PyExc_SystemError,
1390 "Cannot copy %s characters "
1391 "into a string of %s characters",
1392 unicode_kind_name(from),
1393 unicode_kind_name(to));
1394 return -1;
1395 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001396 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397}
1398
Victor Stinner17222162011-09-28 22:15:37 +02001399/* Find the maximum code point and count the number of surrogate pairs so a
1400 correct string length can be computed before converting a string to UCS4.
1401 This function counts single surrogates as a character and not as a pair.
1402
1403 Return 0 on success, or -1 on error. */
1404static int
1405find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1406 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407{
1408 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001409 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerc53be962011-10-02 21:33:54 +02001411 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 *num_surrogates = 0;
1413 *maxchar = 0;
1414
1415 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001417 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1418 && (iter+1) < end
1419 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1420 {
1421 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1422 ++(*num_surrogates);
1423 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 }
1425 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001427 {
1428 ch = *iter;
1429 iter++;
1430 }
1431 if (ch > *maxchar) {
1432 *maxchar = ch;
1433 if (*maxchar > MAX_UNICODE) {
1434 PyErr_Format(PyExc_ValueError,
1435 "character U+%x is not in range [U+0000; U+10ffff]",
1436 ch);
1437 return -1;
1438 }
1439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
1441 return 0;
1442}
1443
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001444int
1445_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446{
1447 wchar_t *end;
1448 Py_UCS4 maxchar = 0;
1449 Py_ssize_t num_surrogates;
1450#if SIZEOF_WCHAR_T == 2
1451 Py_ssize_t length_wo_surrogates;
1452#endif
1453
Georg Brandl7597add2011-10-05 16:36:47 +02001454 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001455 strings were created using _PyObject_New() and where no canonical
1456 representation (the str field) has been set yet aka strings
1457 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001458 assert(_PyUnicode_CHECK(unicode));
1459 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001461 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001462 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001463 /* Actually, it should neither be interned nor be anything else: */
1464 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001467 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001468 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470
1471 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001472 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1473 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 PyErr_NoMemory();
1475 return -1;
1476 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001477 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 _PyUnicode_WSTR(unicode), end,
1479 PyUnicode_1BYTE_DATA(unicode));
1480 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1481 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1482 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1483 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001484 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001485 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001486 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 }
1488 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001489 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001490 _PyUnicode_UTF8(unicode) = NULL;
1491 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 }
1493 PyObject_FREE(_PyUnicode_WSTR(unicode));
1494 _PyUnicode_WSTR(unicode) = NULL;
1495 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1496 }
1497 /* In this case we might have to convert down from 4-byte native
1498 wchar_t to 2-byte unicode. */
1499 else if (maxchar < 65536) {
1500 assert(num_surrogates == 0 &&
1501 "FindMaxCharAndNumSurrogatePairs() messed up");
1502
Victor Stinner506f5922011-09-28 22:34:18 +02001503#if SIZEOF_WCHAR_T == 2
1504 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001505 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001506 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1507 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1508 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001509 _PyUnicode_UTF8(unicode) = NULL;
1510 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001511#else
1512 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001513 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001514 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001515 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001516 PyErr_NoMemory();
1517 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001518 }
Victor Stinner506f5922011-09-28 22:34:18 +02001519 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1520 _PyUnicode_WSTR(unicode), end,
1521 PyUnicode_2BYTE_DATA(unicode));
1522 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1523 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1524 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001525 _PyUnicode_UTF8(unicode) = NULL;
1526 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001527 PyObject_FREE(_PyUnicode_WSTR(unicode));
1528 _PyUnicode_WSTR(unicode) = NULL;
1529 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1530#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001531 }
1532 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1533 else {
1534#if SIZEOF_WCHAR_T == 2
1535 /* in case the native representation is 2-bytes, we need to allocate a
1536 new normalized 4-byte version. */
1537 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001538 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1539 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyErr_NoMemory();
1541 return -1;
1542 }
1543 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1544 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001545 _PyUnicode_UTF8(unicode) = NULL;
1546 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001547 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1548 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001549 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 PyObject_FREE(_PyUnicode_WSTR(unicode));
1551 _PyUnicode_WSTR(unicode) = NULL;
1552 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1553#else
1554 assert(num_surrogates == 0);
1555
Victor Stinnerc3c74152011-10-02 20:39:55 +02001556 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001558 _PyUnicode_UTF8(unicode) = NULL;
1559 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1561#endif
1562 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1563 }
1564 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 return 0;
1567}
1568
Alexander Belopolsky40018472011-02-26 01:02:56 +00001569static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001570unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571{
Walter Dörwald16807132007-05-25 13:52:07 +00001572 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 case SSTATE_NOT_INTERNED:
1574 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001575
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 case SSTATE_INTERNED_MORTAL:
1577 /* revive dead object temporarily for DelItem */
1578 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001579 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 Py_FatalError(
1581 "deletion of interned string failed");
1582 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001583
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 case SSTATE_INTERNED_IMMORTAL:
1585 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001586
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 default:
1588 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001589 }
1590
Victor Stinner03490912011-10-03 23:45:12 +02001591 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001593 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001594 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001595 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1596 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001598 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001599}
1600
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001601#ifdef Py_DEBUG
1602static int
1603unicode_is_singleton(PyObject *unicode)
1604{
1605 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1606 if (unicode == unicode_empty)
1607 return 1;
1608 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1609 {
1610 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1611 if (ch < 256 && unicode_latin1[ch] == unicode)
1612 return 1;
1613 }
1614 return 0;
1615}
1616#endif
1617
Alexander Belopolsky40018472011-02-26 01:02:56 +00001618static int
Victor Stinner488fa492011-12-12 00:01:39 +01001619unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001620{
Victor Stinner488fa492011-12-12 00:01:39 +01001621 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001622 if (Py_REFCNT(unicode) != 1)
1623 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001624 if (_PyUnicode_HASH(unicode) != -1)
1625 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 if (PyUnicode_CHECK_INTERNED(unicode))
1627 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001628 if (!PyUnicode_CheckExact(unicode))
1629 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001630#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001631 /* singleton refcount is greater than 1 */
1632 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001633#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634 return 1;
1635}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636
Victor Stinnerfe226c02011-10-03 03:52:20 +02001637static int
1638unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1639{
1640 PyObject *unicode;
1641 Py_ssize_t old_length;
1642
1643 assert(p_unicode != NULL);
1644 unicode = *p_unicode;
1645
1646 assert(unicode != NULL);
1647 assert(PyUnicode_Check(unicode));
1648 assert(0 <= length);
1649
Victor Stinner910337b2011-10-03 03:20:16 +02001650 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001651 old_length = PyUnicode_WSTR_LENGTH(unicode);
1652 else
1653 old_length = PyUnicode_GET_LENGTH(unicode);
1654 if (old_length == length)
1655 return 0;
1656
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001657 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001658 _Py_INCREF_UNICODE_EMPTY();
1659 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001660 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 Py_DECREF(*p_unicode);
1662 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001663 return 0;
1664 }
1665
Victor Stinner488fa492011-12-12 00:01:39 +01001666 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001667 PyObject *copy = resize_copy(unicode, length);
1668 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 Py_DECREF(*p_unicode);
1671 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001672 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673 }
1674
Victor Stinnerfe226c02011-10-03 03:52:20 +02001675 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001676 PyObject *new_unicode = resize_compact(unicode, length);
1677 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001679 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001680 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001681 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001682 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001683}
1684
Alexander Belopolsky40018472011-02-26 01:02:56 +00001685int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001687{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001688 PyObject *unicode;
1689 if (p_unicode == NULL) {
1690 PyErr_BadInternalCall();
1691 return -1;
1692 }
1693 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001694 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695 {
1696 PyErr_BadInternalCall();
1697 return -1;
1698 }
1699 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001700}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001701
Victor Stinnerc5166102012-02-22 13:55:02 +01001702/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001703
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001704 WARNING: The function doesn't copy the terminating null character and
1705 doesn't check the maximum character (may write a latin1 character in an
1706 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001707static void
1708unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1709 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001710{
1711 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1712 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001713 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001714
1715 switch (kind) {
1716 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001717 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001718#ifdef Py_DEBUG
1719 if (PyUnicode_IS_ASCII(unicode)) {
1720 Py_UCS4 maxchar = ucs1lib_find_max_char(
1721 (const Py_UCS1*)str,
1722 (const Py_UCS1*)str + len);
1723 assert(maxchar < 128);
1724 }
1725#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001726 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001727 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 }
1729 case PyUnicode_2BYTE_KIND: {
1730 Py_UCS2 *start = (Py_UCS2 *)data + index;
1731 Py_UCS2 *ucs2 = start;
1732 assert(index <= PyUnicode_GET_LENGTH(unicode));
1733
Victor Stinner184252a2012-06-16 02:57:41 +02001734 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 *ucs2 = (Py_UCS2)*str;
1736
1737 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001738 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 }
1740 default: {
1741 Py_UCS4 *start = (Py_UCS4 *)data + index;
1742 Py_UCS4 *ucs4 = start;
1743 assert(kind == PyUnicode_4BYTE_KIND);
1744 assert(index <= PyUnicode_GET_LENGTH(unicode));
1745
Victor Stinner184252a2012-06-16 02:57:41 +02001746 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001747 *ucs4 = (Py_UCS4)*str;
1748
1749 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 }
1751 }
1752}
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754static PyObject*
1755get_latin1_char(unsigned char ch)
1756{
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001759 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 if (!unicode)
1761 return NULL;
1762 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001763 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 unicode_latin1[ch] = unicode;
1765 }
1766 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001767 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768}
1769
Victor Stinner985a82a2014-01-03 12:53:47 +01001770static PyObject*
1771unicode_char(Py_UCS4 ch)
1772{
1773 PyObject *unicode;
1774
1775 assert(ch <= MAX_UNICODE);
1776
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001777 if (ch < 256)
1778 return get_latin1_char(ch);
1779
Victor Stinner985a82a2014-01-03 12:53:47 +01001780 unicode = PyUnicode_New(1, ch);
1781 if (unicode == NULL)
1782 return NULL;
1783 switch (PyUnicode_KIND(unicode)) {
1784 case PyUnicode_1BYTE_KIND:
1785 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1786 break;
1787 case PyUnicode_2BYTE_KIND:
1788 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1789 break;
1790 default:
1791 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1792 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1793 }
1794 assert(_PyUnicode_CheckConsistency(unicode, 1));
1795 return unicode;
1796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001800{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001801 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 Py_UCS4 maxchar = 0;
1803 Py_ssize_t num_surrogates;
1804
1805 if (u == NULL)
1806 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808 /* If the Unicode data is known at construction time, we can apply
1809 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001812 if (size == 0)
1813 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 /* Single character Unicode objects in the Latin-1 range are
1816 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001817 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 return get_latin1_char((unsigned char)*u);
1819
1820 /* If not empty and not single character, copy the Unicode data
1821 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001822 if (find_maxchar_surrogates(u, u + size,
1823 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 return NULL;
1825
Victor Stinner8faf8212011-12-08 22:14:11 +01001826 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001827 if (!unicode)
1828 return NULL;
1829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 switch (PyUnicode_KIND(unicode)) {
1831 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001832 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1834 break;
1835 case PyUnicode_2BYTE_KIND:
1836#if Py_UNICODE_SIZE == 2
1837 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1838#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001839 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1841#endif
1842 break;
1843 case PyUnicode_4BYTE_KIND:
1844#if SIZEOF_WCHAR_T == 2
1845 /* This is the only case which has to process surrogates, thus
1846 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001847 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848#else
1849 assert(num_surrogates == 0);
1850 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1851#endif
1852 break;
1853 default:
1854 assert(0 && "Impossible state");
1855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001856
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001857 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001858}
1859
Alexander Belopolsky40018472011-02-26 01:02:56 +00001860PyObject *
1861PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001862{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001863 if (size < 0) {
1864 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001866 return NULL;
1867 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001868 if (u != NULL)
1869 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1870 else
1871 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874PyObject *
1875PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001876{
1877 size_t size = strlen(u);
1878 if (size > PY_SSIZE_T_MAX) {
1879 PyErr_SetString(PyExc_OverflowError, "input too long");
1880 return NULL;
1881 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001882 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883}
1884
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001885PyObject *
1886_PyUnicode_FromId(_Py_Identifier *id)
1887{
1888 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001889 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1890 strlen(id->string),
1891 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001892 if (!id->object)
1893 return NULL;
1894 PyUnicode_InternInPlace(&id->object);
1895 assert(!id->next);
1896 id->next = static_strings;
1897 static_strings = id;
1898 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001899 return id->object;
1900}
1901
1902void
1903_PyUnicode_ClearStaticStrings()
1904{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001905 _Py_Identifier *tmp, *s = static_strings;
1906 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001907 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001908 tmp = s->next;
1909 s->next = NULL;
1910 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001911 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001913}
1914
Benjamin Peterson0df54292012-03-26 14:50:32 -04001915/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917PyObject*
1918_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001919{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001921 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001922 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001923#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001924 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001925#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001926 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001927 }
Victor Stinner785938e2011-12-11 20:09:03 +01001928 unicode = PyUnicode_New(size, 127);
1929 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001930 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001931 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1932 assert(_PyUnicode_CheckConsistency(unicode, 1));
1933 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001934}
1935
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001936static Py_UCS4
1937kind_maxchar_limit(unsigned int kind)
1938{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001939 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001940 case PyUnicode_1BYTE_KIND:
1941 return 0x80;
1942 case PyUnicode_2BYTE_KIND:
1943 return 0x100;
1944 case PyUnicode_4BYTE_KIND:
1945 return 0x10000;
1946 default:
1947 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001948 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001949 }
1950}
1951
Victor Stinnere6abb482012-05-02 01:15:40 +02001952Py_LOCAL_INLINE(Py_UCS4)
1953align_maxchar(Py_UCS4 maxchar)
1954{
1955 if (maxchar <= 127)
1956 return 127;
1957 else if (maxchar <= 255)
1958 return 255;
1959 else if (maxchar <= 65535)
1960 return 65535;
1961 else
1962 return MAX_UNICODE;
1963}
1964
Victor Stinner702c7342011-10-05 13:50:52 +02001965static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001966_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001970
Serhiy Storchaka678db842013-01-26 12:16:36 +02001971 if (size == 0)
1972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001974 if (size == 1)
1975 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001978 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 if (!res)
1980 return NULL;
1981 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001982 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001984}
1985
Victor Stinnere57b1c02011-09-28 22:20:48 +02001986static PyObject*
1987_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988{
1989 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001990 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001991
Serhiy Storchaka678db842013-01-26 12:16:36 +02001992 if (size == 0)
1993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001995 if (size == 1)
1996 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001998 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001999 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 if (!res)
2001 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002004 else {
2005 _PyUnicode_CONVERT_BYTES(
2006 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2007 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002008 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 return res;
2010}
2011
Victor Stinnere57b1c02011-09-28 22:20:48 +02002012static PyObject*
2013_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014{
2015 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002016 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017
Serhiy Storchaka678db842013-01-26 12:16:36 +02002018 if (size == 0)
2019 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002020 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002021 if (size == 1)
2022 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002024 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002025 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 if (!res)
2027 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002028 if (max_char < 256)
2029 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2030 PyUnicode_1BYTE_DATA(res));
2031 else if (max_char < 0x10000)
2032 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2033 PyUnicode_2BYTE_DATA(res));
2034 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002036 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 return res;
2038}
2039
2040PyObject*
2041PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2042{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002043 if (size < 0) {
2044 PyErr_SetString(PyExc_ValueError, "size must be positive");
2045 return NULL;
2046 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002047 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002049 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002051 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002053 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002055 PyErr_SetString(PyExc_SystemError, "invalid kind");
2056 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058}
2059
Victor Stinnerece58de2012-04-23 23:36:38 +02002060Py_UCS4
2061_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2062{
2063 enum PyUnicode_Kind kind;
2064 void *startptr, *endptr;
2065
2066 assert(PyUnicode_IS_READY(unicode));
2067 assert(0 <= start);
2068 assert(end <= PyUnicode_GET_LENGTH(unicode));
2069 assert(start <= end);
2070
2071 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2072 return PyUnicode_MAX_CHAR_VALUE(unicode);
2073
2074 if (start == end)
2075 return 127;
2076
Victor Stinner94d558b2012-04-27 22:26:58 +02002077 if (PyUnicode_IS_ASCII(unicode))
2078 return 127;
2079
Victor Stinnerece58de2012-04-23 23:36:38 +02002080 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002081 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002082 endptr = (char *)startptr + end * kind;
2083 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 switch(kind) {
2085 case PyUnicode_1BYTE_KIND:
2086 return ucs1lib_find_max_char(startptr, endptr);
2087 case PyUnicode_2BYTE_KIND:
2088 return ucs2lib_find_max_char(startptr, endptr);
2089 case PyUnicode_4BYTE_KIND:
2090 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002091 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002092 assert(0);
2093 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002094 }
2095}
2096
Victor Stinner25a4b292011-10-06 12:31:55 +02002097/* Ensure that a string uses the most efficient storage, if it is not the
2098 case: create a new string with of the right kind. Write NULL into *p_unicode
2099 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002100static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002101unicode_adjust_maxchar(PyObject **p_unicode)
2102{
2103 PyObject *unicode, *copy;
2104 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002105 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002106 unsigned int kind;
2107
2108 assert(p_unicode != NULL);
2109 unicode = *p_unicode;
2110 assert(PyUnicode_IS_READY(unicode));
2111 if (PyUnicode_IS_ASCII(unicode))
2112 return;
2113
2114 len = PyUnicode_GET_LENGTH(unicode);
2115 kind = PyUnicode_KIND(unicode);
2116 if (kind == PyUnicode_1BYTE_KIND) {
2117 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002118 max_char = ucs1lib_find_max_char(u, u + len);
2119 if (max_char >= 128)
2120 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002121 }
2122 else if (kind == PyUnicode_2BYTE_KIND) {
2123 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002124 max_char = ucs2lib_find_max_char(u, u + len);
2125 if (max_char >= 256)
2126 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 }
2128 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002129 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002131 max_char = ucs4lib_find_max_char(u, u + len);
2132 if (max_char >= 0x10000)
2133 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002135 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002136 if (copy != NULL)
2137 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 Py_DECREF(unicode);
2139 *p_unicode = copy;
2140}
2141
Victor Stinner034f6cf2011-09-30 02:26:44 +02002142PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002143_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002144{
Victor Stinner87af4f22011-11-21 23:03:47 +01002145 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002147
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148 if (!PyUnicode_Check(unicode)) {
2149 PyErr_BadInternalCall();
2150 return NULL;
2151 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002152 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002154
Victor Stinner87af4f22011-11-21 23:03:47 +01002155 length = PyUnicode_GET_LENGTH(unicode);
2156 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157 if (!copy)
2158 return NULL;
2159 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2160
Victor Stinner87af4f22011-11-21 23:03:47 +01002161 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2162 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002163 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002164 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002165}
2166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002167
Victor Stinnerbc603d12011-10-02 01:00:40 +02002168/* Widen Unicode objects to larger buffers. Don't write terminating null
2169 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170
2171void*
2172_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2173{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 Py_ssize_t len;
2175 void *result;
2176 unsigned int skind;
2177
Benjamin Petersonbac79492012-01-14 13:34:47 -05002178 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002179 return NULL;
2180
2181 len = PyUnicode_GET_LENGTH(s);
2182 skind = PyUnicode_KIND(s);
2183 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002184 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 return NULL;
2186 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002187 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002188 case PyUnicode_2BYTE_KIND:
2189 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2190 if (!result)
2191 return PyErr_NoMemory();
2192 assert(skind == PyUnicode_1BYTE_KIND);
2193 _PyUnicode_CONVERT_BYTES(
2194 Py_UCS1, Py_UCS2,
2195 PyUnicode_1BYTE_DATA(s),
2196 PyUnicode_1BYTE_DATA(s) + len,
2197 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 case PyUnicode_4BYTE_KIND:
2200 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2201 if (!result)
2202 return PyErr_NoMemory();
2203 if (skind == PyUnicode_2BYTE_KIND) {
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS2, Py_UCS4,
2206 PyUnicode_2BYTE_DATA(s),
2207 PyUnicode_2BYTE_DATA(s) + len,
2208 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 else {
2211 assert(skind == PyUnicode_1BYTE_KIND);
2212 _PyUnicode_CONVERT_BYTES(
2213 Py_UCS1, Py_UCS4,
2214 PyUnicode_1BYTE_DATA(s),
2215 PyUnicode_1BYTE_DATA(s) + len,
2216 result);
2217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 default:
2220 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 }
Victor Stinner01698042011-10-04 00:04:26 +02002222 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 return NULL;
2224}
2225
2226static Py_UCS4*
2227as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
2230 int kind;
2231 void *data;
2232 Py_ssize_t len, targetlen;
2233 if (PyUnicode_READY(string) == -1)
2234 return NULL;
2235 kind = PyUnicode_KIND(string);
2236 data = PyUnicode_DATA(string);
2237 len = PyUnicode_GET_LENGTH(string);
2238 targetlen = len;
2239 if (copy_null)
2240 targetlen++;
2241 if (!target) {
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07002242 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UCS4) < targetlen) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2247 if (!target) {
2248 PyErr_NoMemory();
2249 return NULL;
2250 }
2251 }
2252 else {
2253 if (targetsize < targetlen) {
2254 PyErr_Format(PyExc_SystemError,
2255 "string is longer than the buffer");
2256 if (copy_null && 0 < targetsize)
2257 target[0] = 0;
2258 return NULL;
2259 }
2260 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002261 if (kind == PyUnicode_1BYTE_KIND) {
2262 Py_UCS1 *start = (Py_UCS1 *) data;
2263 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002265 else if (kind == PyUnicode_2BYTE_KIND) {
2266 Py_UCS2 *start = (Py_UCS2 *) data;
2267 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2268 }
2269 else {
2270 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 if (copy_null)
2274 target[len] = 0;
2275 return target;
2276}
2277
2278Py_UCS4*
2279PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2280 int copy_null)
2281{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002282 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002283 PyErr_BadInternalCall();
2284 return NULL;
2285 }
2286 return as_ucs4(string, target, targetsize, copy_null);
2287}
2288
2289Py_UCS4*
2290PyUnicode_AsUCS4Copy(PyObject *string)
2291{
2292 return as_ucs4(string, NULL, 0, 1);
2293}
2294
2295#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002296
Alexander Belopolsky40018472011-02-26 01:02:56 +00002297PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002298PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002299{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002301 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002302 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002303 PyErr_BadInternalCall();
2304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002305 }
2306
Martin v. Löwis790465f2008-04-05 20:41:37 +00002307 if (size == -1) {
2308 size = wcslen(w);
2309 }
2310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002311 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002312}
2313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002314#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002315
Victor Stinner15a11362012-10-06 23:48:20 +02002316/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002317 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2318 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2319#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002320
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002321static int
2322unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2323 Py_ssize_t width, Py_ssize_t precision)
2324{
2325 Py_ssize_t length, fill, arglen;
2326 Py_UCS4 maxchar;
2327
2328 if (PyUnicode_READY(str) == -1)
2329 return -1;
2330
2331 length = PyUnicode_GET_LENGTH(str);
2332 if ((precision == -1 || precision >= length)
2333 && width <= length)
2334 return _PyUnicodeWriter_WriteStr(writer, str);
2335
2336 if (precision != -1)
2337 length = Py_MIN(precision, length);
2338
2339 arglen = Py_MAX(length, width);
2340 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2341 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2342 else
2343 maxchar = writer->maxchar;
2344
2345 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2346 return -1;
2347
2348 if (width > length) {
2349 fill = width - length;
2350 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2351 return -1;
2352 writer->pos += fill;
2353 }
2354
2355 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2356 str, 0, length);
2357 writer->pos += length;
2358 return 0;
2359}
2360
2361static int
2362unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2363 Py_ssize_t width, Py_ssize_t precision)
2364{
2365 /* UTF-8 */
2366 Py_ssize_t length;
2367 PyObject *unicode;
2368 int res;
2369
2370 length = strlen(str);
2371 if (precision != -1)
2372 length = Py_MIN(length, precision);
2373 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2374 if (unicode == NULL)
2375 return -1;
2376
2377 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2378 Py_DECREF(unicode);
2379 return res;
2380}
2381
Victor Stinner96865452011-03-01 23:44:09 +00002382static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002383unicode_fromformat_arg(_PyUnicodeWriter *writer,
2384 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002385{
Victor Stinnere215d962012-10-06 23:03:36 +02002386 const char *p;
2387 Py_ssize_t len;
2388 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002389 Py_ssize_t width;
2390 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002391 int longflag;
2392 int longlongflag;
2393 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002394 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002395
2396 p = f;
2397 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002398 zeropad = 0;
2399 if (*f == '0') {
2400 zeropad = 1;
2401 f++;
2402 }
Victor Stinner96865452011-03-01 23:44:09 +00002403
2404 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002405 width = -1;
2406 if (Py_ISDIGIT((unsigned)*f)) {
2407 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002408 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002409 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002410 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002411 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002412 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002413 return NULL;
2414 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002415 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002416 f++;
2417 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002418 }
2419 precision = -1;
2420 if (*f == '.') {
2421 f++;
2422 if (Py_ISDIGIT((unsigned)*f)) {
2423 precision = (*f - '0');
2424 f++;
2425 while (Py_ISDIGIT((unsigned)*f)) {
2426 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2427 PyErr_SetString(PyExc_ValueError,
2428 "precision too big");
2429 return NULL;
2430 }
2431 precision = (precision * 10) + (*f - '0');
2432 f++;
2433 }
2434 }
Victor Stinner96865452011-03-01 23:44:09 +00002435 if (*f == '%') {
2436 /* "%.3%s" => f points to "3" */
2437 f--;
2438 }
2439 }
2440 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002441 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002442 f--;
2443 }
Victor Stinner96865452011-03-01 23:44:09 +00002444
2445 /* Handle %ld, %lu, %lld and %llu. */
2446 longflag = 0;
2447 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002448 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002449 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002450 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002451 longflag = 1;
2452 ++f;
2453 }
2454#ifdef HAVE_LONG_LONG
2455 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002456 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002457 longlongflag = 1;
2458 f += 2;
2459 }
2460#endif
2461 }
2462 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002463 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002464 size_tflag = 1;
2465 ++f;
2466 }
Victor Stinnere215d962012-10-06 23:03:36 +02002467
2468 if (f[1] == '\0')
2469 writer->overallocate = 0;
2470
2471 switch (*f) {
2472 case 'c':
2473 {
2474 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002475 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002476 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002477 "character argument not in range(0x110000)");
2478 return NULL;
2479 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002480 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002481 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002482 break;
2483 }
2484
2485 case 'i':
2486 case 'd':
2487 case 'u':
2488 case 'x':
2489 {
2490 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002491 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002492 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002493
2494 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002495 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002496 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002497 va_arg(*vargs, unsigned long));
2498#ifdef HAVE_LONG_LONG
2499 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002500 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002501 va_arg(*vargs, unsigned PY_LONG_LONG));
2502#endif
2503 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002504 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002505 va_arg(*vargs, size_t));
2506 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002507 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002508 va_arg(*vargs, unsigned int));
2509 }
2510 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002511 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002512 }
2513 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002514 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002515 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002516 va_arg(*vargs, long));
2517#ifdef HAVE_LONG_LONG
2518 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002519 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002520 va_arg(*vargs, PY_LONG_LONG));
2521#endif
2522 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002523 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002524 va_arg(*vargs, Py_ssize_t));
2525 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002526 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002527 va_arg(*vargs, int));
2528 }
2529 assert(len >= 0);
2530
Victor Stinnere215d962012-10-06 23:03:36 +02002531 if (precision < len)
2532 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002533
2534 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002535 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2536 return NULL;
2537
Victor Stinnere215d962012-10-06 23:03:36 +02002538 if (width > precision) {
2539 Py_UCS4 fillchar;
2540 fill = width - precision;
2541 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002542 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2543 return NULL;
2544 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002545 }
Victor Stinner15a11362012-10-06 23:48:20 +02002546 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002547 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002548 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2549 return NULL;
2550 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002551 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002552
Victor Stinner4a587072013-11-19 12:54:53 +01002553 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2554 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002555 break;
2556 }
2557
2558 case 'p':
2559 {
2560 char number[MAX_LONG_LONG_CHARS];
2561
2562 len = sprintf(number, "%p", va_arg(*vargs, void*));
2563 assert(len >= 0);
2564
2565 /* %p is ill-defined: ensure leading 0x. */
2566 if (number[1] == 'X')
2567 number[1] = 'x';
2568 else if (number[1] != 'x') {
2569 memmove(number + 2, number,
2570 strlen(number) + 1);
2571 number[0] = '0';
2572 number[1] = 'x';
2573 len += 2;
2574 }
2575
Victor Stinner4a587072013-11-19 12:54:53 +01002576 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002577 return NULL;
2578 break;
2579 }
2580
2581 case 's':
2582 {
2583 /* UTF-8 */
2584 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002585 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002586 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002587 break;
2588 }
2589
2590 case 'U':
2591 {
2592 PyObject *obj = va_arg(*vargs, PyObject *);
2593 assert(obj && _PyUnicode_CHECK(obj));
2594
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002596 return NULL;
2597 break;
2598 }
2599
2600 case 'V':
2601 {
2602 PyObject *obj = va_arg(*vargs, PyObject *);
2603 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002604 if (obj) {
2605 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002606 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002607 return NULL;
2608 }
2609 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002610 assert(str != NULL);
2611 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002612 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002613 }
2614 break;
2615 }
2616
2617 case 'S':
2618 {
2619 PyObject *obj = va_arg(*vargs, PyObject *);
2620 PyObject *str;
2621 assert(obj);
2622 str = PyObject_Str(obj);
2623 if (!str)
2624 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002625 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002626 Py_DECREF(str);
2627 return NULL;
2628 }
2629 Py_DECREF(str);
2630 break;
2631 }
2632
2633 case 'R':
2634 {
2635 PyObject *obj = va_arg(*vargs, PyObject *);
2636 PyObject *repr;
2637 assert(obj);
2638 repr = PyObject_Repr(obj);
2639 if (!repr)
2640 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002642 Py_DECREF(repr);
2643 return NULL;
2644 }
2645 Py_DECREF(repr);
2646 break;
2647 }
2648
2649 case 'A':
2650 {
2651 PyObject *obj = va_arg(*vargs, PyObject *);
2652 PyObject *ascii;
2653 assert(obj);
2654 ascii = PyObject_ASCII(obj);
2655 if (!ascii)
2656 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002657 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002658 Py_DECREF(ascii);
2659 return NULL;
2660 }
2661 Py_DECREF(ascii);
2662 break;
2663 }
2664
2665 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002666 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002667 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002668 break;
2669
2670 default:
2671 /* if we stumble upon an unknown formatting code, copy the rest
2672 of the format string to the output string. (we cannot just
2673 skip the code, since there's no way to know what's in the
2674 argument list) */
2675 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002676 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002677 return NULL;
2678 f = p+len;
2679 return f;
2680 }
2681
2682 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002683 return f;
2684}
2685
Walter Dörwaldd2034312007-05-18 16:29:38 +00002686PyObject *
2687PyUnicode_FromFormatV(const char *format, va_list vargs)
2688{
Victor Stinnere215d962012-10-06 23:03:36 +02002689 va_list vargs2;
2690 const char *f;
2691 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002692
Victor Stinner8f674cc2013-04-17 23:02:17 +02002693 _PyUnicodeWriter_Init(&writer);
2694 writer.min_length = strlen(format) + 100;
2695 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002696
2697 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2698 Copy it to be able to pass a reference to a subfunction. */
2699 Py_VA_COPY(vargs2, vargs);
2700
2701 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002703 f = unicode_fromformat_arg(&writer, f, &vargs2);
2704 if (f == NULL)
2705 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002707 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002708 const char *p;
2709 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002710
Victor Stinnere215d962012-10-06 23:03:36 +02002711 p = f;
2712 do
2713 {
2714 if ((unsigned char)*p > 127) {
2715 PyErr_Format(PyExc_ValueError,
2716 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2717 "string, got a non-ASCII byte: 0x%02x",
2718 (unsigned char)*p);
2719 return NULL;
2720 }
2721 p++;
2722 }
2723 while (*p != '\0' && *p != '%');
2724 len = p - f;
2725
2726 if (*p == '\0')
2727 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002728
2729 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002730 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002731
2732 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002733 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002734 }
Victor Stinnere215d962012-10-06 23:03:36 +02002735 return _PyUnicodeWriter_Finish(&writer);
2736
2737 fail:
2738 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002739 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002740}
2741
Walter Dörwaldd2034312007-05-18 16:29:38 +00002742PyObject *
2743PyUnicode_FromFormat(const char *format, ...)
2744{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 PyObject* ret;
2746 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002747
2748#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002749 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002750#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002751 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002752#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002753 ret = PyUnicode_FromFormatV(format, vargs);
2754 va_end(vargs);
2755 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002756}
2757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002758#ifdef HAVE_WCHAR_H
2759
Victor Stinner5593d8a2010-10-02 11:11:27 +00002760/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2761 convert a Unicode object to a wide character string.
2762
Victor Stinnerd88d9832011-09-06 02:00:05 +02002763 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002764 character) required to convert the unicode object. Ignore size argument.
2765
Victor Stinnerd88d9832011-09-06 02:00:05 +02002766 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002767 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002768 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002769static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002770unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002771 wchar_t *w,
2772 Py_ssize_t size)
2773{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002774 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002775 const wchar_t *wstr;
2776
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002777 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002778 if (wstr == NULL)
2779 return -1;
2780
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002782 if (size > res)
2783 size = res + 1;
2784 else
2785 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002787 return res;
2788 }
2789 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002791}
2792
2793Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002794PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002795 wchar_t *w,
2796 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002797{
2798 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002799 PyErr_BadInternalCall();
2800 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002801 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002802 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002803}
2804
Victor Stinner137c34c2010-09-29 10:25:54 +00002805wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002806PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002807 Py_ssize_t *size)
2808{
2809 wchar_t* buffer;
2810 Py_ssize_t buflen;
2811
2812 if (unicode == NULL) {
2813 PyErr_BadInternalCall();
2814 return NULL;
2815 }
2816
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002817 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002818 if (buflen == -1)
2819 return NULL;
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07002820 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002821 PyErr_NoMemory();
2822 return NULL;
2823 }
2824
Victor Stinner137c34c2010-09-29 10:25:54 +00002825 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2826 if (buffer == NULL) {
2827 PyErr_NoMemory();
2828 return NULL;
2829 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002830 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002831 if (buflen == -1) {
2832 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002833 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002834 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002835 if (size != NULL)
2836 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 return buffer;
2838}
2839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002840#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002841
Alexander Belopolsky40018472011-02-26 01:02:56 +00002842PyObject *
2843PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002844{
Victor Stinner8faf8212011-12-08 22:14:11 +01002845 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002846 PyErr_SetString(PyExc_ValueError,
2847 "chr() arg not in range(0x110000)");
2848 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002849 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002850
Victor Stinner985a82a2014-01-03 12:53:47 +01002851 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002852}
2853
Alexander Belopolsky40018472011-02-26 01:02:56 +00002854PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002855PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002856{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002857 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002858 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002859 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002860 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002861 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002862 Py_INCREF(obj);
2863 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002864 }
2865 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002866 /* For a Unicode subtype that's not a Unicode object,
2867 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002868 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002869 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002870 PyErr_Format(PyExc_TypeError,
2871 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002872 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002873 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002874}
2875
Alexander Belopolsky40018472011-02-26 01:02:56 +00002876PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002877PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002878 const char *encoding,
2879 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002880{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002881 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002882 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002883
Guido van Rossumd57fd912000-03-10 22:53:23 +00002884 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 PyErr_BadInternalCall();
2886 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002887 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002888
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002889 /* Decoding bytes objects is the most common case and should be fast */
2890 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002891 if (PyBytes_GET_SIZE(obj) == 0)
2892 _Py_RETURN_UNICODE_EMPTY();
2893 v = PyUnicode_Decode(
2894 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2895 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002896 return v;
2897 }
2898
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002899 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002900 PyErr_SetString(PyExc_TypeError,
2901 "decoding str is not supported");
2902 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002903 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002904
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002905 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2906 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2907 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002908 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002909 Py_TYPE(obj)->tp_name);
2910 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002911 }
Tim Petersced69f82003-09-16 20:30:58 +00002912
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002913 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002914 PyBuffer_Release(&buffer);
2915 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002916 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002917
Serhiy Storchaka05997252013-01-26 12:14:02 +02002918 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002919 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002920 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921}
2922
Victor Stinner600d3be2010-06-10 12:00:55 +00002923/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002924 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2925 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002926int
2927_Py_normalize_encoding(const char *encoding,
2928 char *lower,
2929 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002930{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002931 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002932 char *l;
2933 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002934
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002935 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002936 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002937 if (lower_len < 6)
2938 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002939 strcpy(lower, "utf-8");
2940 return 1;
2941 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002942 e = encoding;
2943 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002944 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002945 while (*e) {
2946 if (l == l_end)
2947 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002948 if (Py_ISUPPER(*e)) {
2949 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002950 }
2951 else if (*e == '_') {
2952 *l++ = '-';
2953 e++;
2954 }
2955 else {
2956 *l++ = *e++;
2957 }
2958 }
2959 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002960 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002961}
2962
Alexander Belopolsky40018472011-02-26 01:02:56 +00002963PyObject *
2964PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002965 Py_ssize_t size,
2966 const char *encoding,
2967 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002968{
2969 PyObject *buffer = NULL, *unicode;
2970 Py_buffer info;
2971 char lower[11]; /* Enough for any encoding shortcut */
2972
Fred Drakee4315f52000-05-09 19:53:39 +00002973 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002974 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002975 if ((strcmp(lower, "utf-8") == 0) ||
2976 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002977 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002978 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002979 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01002980 (strcmp(lower, "iso-8859-1") == 0) ||
2981 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002982 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002983#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002984 else if (strcmp(lower, "mbcs") == 0)
2985 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002986#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002987 else if (strcmp(lower, "ascii") == 0)
2988 return PyUnicode_DecodeASCII(s, size, errors);
2989 else if (strcmp(lower, "utf-16") == 0)
2990 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2991 else if (strcmp(lower, "utf-32") == 0)
2992 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2993 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002994
2995 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002996 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002997 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002998 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002999 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003000 if (buffer == NULL)
3001 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003002 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003003 if (unicode == NULL)
3004 goto onError;
3005 if (!PyUnicode_Check(unicode)) {
3006 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003007 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3008 "use codecs.decode() to decode to arbitrary types",
3009 encoding,
3010 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003011 Py_DECREF(unicode);
3012 goto onError;
3013 }
3014 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003015 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003016
Benjamin Peterson29060642009-01-31 22:14:21 +00003017 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003018 Py_XDECREF(buffer);
3019 return NULL;
3020}
3021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
3023PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003024 const char *encoding,
3025 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003026{
3027 PyObject *v;
3028
3029 if (!PyUnicode_Check(unicode)) {
3030 PyErr_BadArgument();
3031 goto onError;
3032 }
3033
3034 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003035 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003036
3037 /* Decode via the codec registry */
3038 v = PyCodec_Decode(unicode, encoding, errors);
3039 if (v == NULL)
3040 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003041 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003042
Benjamin Peterson29060642009-01-31 22:14:21 +00003043 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003044 return NULL;
3045}
3046
Alexander Belopolsky40018472011-02-26 01:02:56 +00003047PyObject *
3048PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003049 const char *encoding,
3050 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003051{
3052 PyObject *v;
3053
3054 if (!PyUnicode_Check(unicode)) {
3055 PyErr_BadArgument();
3056 goto onError;
3057 }
3058
3059 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003060 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003061
3062 /* Decode via the codec registry */
3063 v = PyCodec_Decode(unicode, encoding, errors);
3064 if (v == NULL)
3065 goto onError;
3066 if (!PyUnicode_Check(v)) {
3067 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003068 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3069 "use codecs.decode() to decode to arbitrary types",
3070 encoding,
3071 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003072 Py_DECREF(v);
3073 goto onError;
3074 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003075 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003076
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003078 return NULL;
3079}
3080
Alexander Belopolsky40018472011-02-26 01:02:56 +00003081PyObject *
3082PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003083 Py_ssize_t size,
3084 const char *encoding,
3085 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086{
3087 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003088
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089 unicode = PyUnicode_FromUnicode(s, size);
3090 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003091 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003092 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3093 Py_DECREF(unicode);
3094 return v;
3095}
3096
Alexander Belopolsky40018472011-02-26 01:02:56 +00003097PyObject *
3098PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003099 const char *encoding,
3100 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003101{
3102 PyObject *v;
3103
3104 if (!PyUnicode_Check(unicode)) {
3105 PyErr_BadArgument();
3106 goto onError;
3107 }
3108
3109 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003110 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003111
3112 /* Encode via the codec registry */
3113 v = PyCodec_Encode(unicode, encoding, errors);
3114 if (v == NULL)
3115 goto onError;
3116 return v;
3117
Benjamin Peterson29060642009-01-31 22:14:21 +00003118 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003119 return NULL;
3120}
3121
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003122static size_t
3123wcstombs_errorpos(const wchar_t *wstr)
3124{
3125 size_t len;
3126#if SIZEOF_WCHAR_T == 2
3127 wchar_t buf[3];
3128#else
3129 wchar_t buf[2];
3130#endif
3131 char outbuf[MB_LEN_MAX];
3132 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003133
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003134#if SIZEOF_WCHAR_T == 2
3135 buf[2] = 0;
3136#else
3137 buf[1] = 0;
3138#endif
3139 start = wstr;
3140 while (*wstr != L'\0')
3141 {
3142 previous = wstr;
3143#if SIZEOF_WCHAR_T == 2
3144 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3145 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3146 {
3147 buf[0] = wstr[0];
3148 buf[1] = wstr[1];
3149 wstr += 2;
3150 }
3151 else {
3152 buf[0] = *wstr;
3153 buf[1] = 0;
3154 wstr++;
3155 }
3156#else
3157 buf[0] = *wstr;
3158 wstr++;
3159#endif
3160 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003161 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003162 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003163 }
3164
3165 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003166 return 0;
3167}
3168
Victor Stinner1b579672011-12-17 05:47:23 +01003169static int
3170locale_error_handler(const char *errors, int *surrogateescape)
3171{
3172 if (errors == NULL) {
3173 *surrogateescape = 0;
3174 return 0;
3175 }
3176
3177 if (strcmp(errors, "strict") == 0) {
3178 *surrogateescape = 0;
3179 return 0;
3180 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003181 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003182 *surrogateescape = 1;
3183 return 0;
3184 }
3185 PyErr_Format(PyExc_ValueError,
3186 "only 'strict' and 'surrogateescape' error handlers "
3187 "are supported, not '%s'",
3188 errors);
3189 return -1;
3190}
3191
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003192PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003193PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003194{
3195 Py_ssize_t wlen, wlen2;
3196 wchar_t *wstr;
3197 PyObject *bytes = NULL;
3198 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003199 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003200 PyObject *exc;
3201 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003202 int surrogateescape;
3203
3204 if (locale_error_handler(errors, &surrogateescape) < 0)
3205 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003206
3207 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3208 if (wstr == NULL)
3209 return NULL;
3210
3211 wlen2 = wcslen(wstr);
3212 if (wlen2 != wlen) {
3213 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003214 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003215 return NULL;
3216 }
3217
3218 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003219 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003220 char *str;
3221
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003222 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223 if (str == NULL) {
3224 if (error_pos == (size_t)-1) {
3225 PyErr_NoMemory();
3226 PyMem_Free(wstr);
3227 return NULL;
3228 }
3229 else {
3230 goto encode_error;
3231 }
3232 }
3233 PyMem_Free(wstr);
3234
3235 bytes = PyBytes_FromString(str);
3236 PyMem_Free(str);
3237 }
3238 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003239 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003240 size_t len, len2;
3241
3242 len = wcstombs(NULL, wstr, 0);
3243 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003244 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003245 goto encode_error;
3246 }
3247
3248 bytes = PyBytes_FromStringAndSize(NULL, len);
3249 if (bytes == NULL) {
3250 PyMem_Free(wstr);
3251 return NULL;
3252 }
3253
3254 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3255 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003256 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003257 goto encode_error;
3258 }
3259 PyMem_Free(wstr);
3260 }
3261 return bytes;
3262
3263encode_error:
3264 errmsg = strerror(errno);
3265 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003266
3267 if (error_pos == (size_t)-1)
3268 error_pos = wcstombs_errorpos(wstr);
3269
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003270 PyMem_Free(wstr);
3271 Py_XDECREF(bytes);
3272
Victor Stinner2f197072011-12-17 07:08:30 +01003273 if (errmsg != NULL) {
3274 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003275 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003276 if (wstr != NULL) {
3277 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003278 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003279 } else
3280 errmsg = NULL;
3281 }
3282 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003283 reason = PyUnicode_FromString(
3284 "wcstombs() encountered an unencodable "
3285 "wide character");
3286 if (reason == NULL)
3287 return NULL;
3288
3289 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3290 "locale", unicode,
3291 (Py_ssize_t)error_pos,
3292 (Py_ssize_t)(error_pos+1),
3293 reason);
3294 Py_DECREF(reason);
3295 if (exc != NULL) {
3296 PyCodec_StrictErrors(exc);
3297 Py_XDECREF(exc);
3298 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003299 return NULL;
3300}
3301
Victor Stinnerad158722010-10-27 00:25:46 +00003302PyObject *
3303PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003304{
Victor Stinner99b95382011-07-04 14:23:54 +02003305#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003306 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003307#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003308 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003309#else
Victor Stinner793b5312011-04-27 00:24:21 +02003310 PyInterpreterState *interp = PyThreadState_GET()->interp;
3311 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3312 cannot use it to encode and decode filenames before it is loaded. Load
3313 the Python codec requires to encode at least its own filename. Use the C
3314 version of the locale codec until the codec registry is initialized and
3315 the Python codec is loaded.
3316
3317 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3318 cannot only rely on it: check also interp->fscodec_initialized for
3319 subinterpreters. */
3320 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003321 return PyUnicode_AsEncodedString(unicode,
3322 Py_FileSystemDefaultEncoding,
3323 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003324 }
3325 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003326 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003327 }
Victor Stinnerad158722010-10-27 00:25:46 +00003328#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003329}
3330
Alexander Belopolsky40018472011-02-26 01:02:56 +00003331PyObject *
3332PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003333 const char *encoding,
3334 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003335{
3336 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003337 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003338
Guido van Rossumd57fd912000-03-10 22:53:23 +00003339 if (!PyUnicode_Check(unicode)) {
3340 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003341 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003342 }
Fred Drakee4315f52000-05-09 19:53:39 +00003343
Fred Drakee4315f52000-05-09 19:53:39 +00003344 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003345 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003346 if ((strcmp(lower, "utf-8") == 0) ||
3347 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003348 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003349 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003350 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003351 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003353 }
Victor Stinner37296e82010-06-10 13:36:23 +00003354 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003355 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003356 (strcmp(lower, "iso-8859-1") == 0) ||
3357 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003358 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003359#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003360 else if (strcmp(lower, "mbcs") == 0)
3361 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003362#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003363 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003364 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003365 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003366
3367 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003368 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003369 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003370 return NULL;
3371
3372 /* The normal path */
3373 if (PyBytes_Check(v))
3374 return v;
3375
3376 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003377 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003378 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003379 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003380
3381 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003382 "encoder %s returned bytearray instead of bytes; "
3383 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003384 encoding);
3385 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003386 Py_DECREF(v);
3387 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003388 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003389
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003390 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3391 Py_DECREF(v);
3392 return b;
3393 }
3394
3395 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003396 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3397 "use codecs.encode() to encode to arbitrary types",
3398 encoding,
3399 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003400 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003401 return NULL;
3402}
3403
Alexander Belopolsky40018472011-02-26 01:02:56 +00003404PyObject *
3405PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003406 const char *encoding,
3407 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003408{
3409 PyObject *v;
3410
3411 if (!PyUnicode_Check(unicode)) {
3412 PyErr_BadArgument();
3413 goto onError;
3414 }
3415
3416 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003417 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003418
3419 /* Encode via the codec registry */
3420 v = PyCodec_Encode(unicode, encoding, errors);
3421 if (v == NULL)
3422 goto onError;
3423 if (!PyUnicode_Check(v)) {
3424 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003425 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3426 "use codecs.encode() to encode to arbitrary types",
3427 encoding,
3428 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003429 Py_DECREF(v);
3430 goto onError;
3431 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003432 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003433
Benjamin Peterson29060642009-01-31 22:14:21 +00003434 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003435 return NULL;
3436}
3437
Victor Stinner2f197072011-12-17 07:08:30 +01003438static size_t
3439mbstowcs_errorpos(const char *str, size_t len)
3440{
3441#ifdef HAVE_MBRTOWC
3442 const char *start = str;
3443 mbstate_t mbs;
3444 size_t converted;
3445 wchar_t ch;
3446
3447 memset(&mbs, 0, sizeof mbs);
3448 while (len)
3449 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003450 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003451 if (converted == 0)
3452 /* Reached end of string */
3453 break;
3454 if (converted == (size_t)-1 || converted == (size_t)-2) {
3455 /* Conversion error or incomplete character */
3456 return str - start;
3457 }
3458 else {
3459 str += converted;
3460 len -= converted;
3461 }
3462 }
3463 /* failed to find the undecodable byte sequence */
3464 return 0;
3465#endif
3466 return 0;
3467}
3468
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003469PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003470PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003471 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003472{
3473 wchar_t smallbuf[256];
3474 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3475 wchar_t *wstr;
3476 size_t wlen, wlen2;
3477 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003478 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003479 size_t error_pos;
3480 char *errmsg;
3481 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003482
3483 if (locale_error_handler(errors, &surrogateescape) < 0)
3484 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003485
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003486 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3487 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003488 return NULL;
3489 }
3490
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003491 if (surrogateescape) {
3492 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003493 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003494 if (wstr == NULL) {
3495 if (wlen == (size_t)-1)
3496 PyErr_NoMemory();
3497 else
3498 PyErr_SetFromErrno(PyExc_OSError);
3499 return NULL;
3500 }
3501
3502 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003503 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003504 }
3505 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003506 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003507#ifndef HAVE_BROKEN_MBSTOWCS
3508 wlen = mbstowcs(NULL, str, 0);
3509#else
3510 wlen = len;
3511#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003512 if (wlen == (size_t)-1)
3513 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003514 if (wlen+1 <= smallbuf_len) {
3515 wstr = smallbuf;
3516 }
3517 else {
3518 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3519 return PyErr_NoMemory();
3520
3521 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3522 if (!wstr)
3523 return PyErr_NoMemory();
3524 }
3525
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003526 wlen2 = mbstowcs(wstr, str, wlen+1);
3527 if (wlen2 == (size_t)-1) {
3528 if (wstr != smallbuf)
3529 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003530 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003531 }
3532#ifdef HAVE_BROKEN_MBSTOWCS
3533 assert(wlen2 == wlen);
3534#endif
3535 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3536 if (wstr != smallbuf)
3537 PyMem_Free(wstr);
3538 }
3539 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003540
3541decode_error:
3542 errmsg = strerror(errno);
3543 assert(errmsg != NULL);
3544
3545 error_pos = mbstowcs_errorpos(str, len);
3546 if (errmsg != NULL) {
3547 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003548 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003549 if (wstr != NULL) {
3550 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003551 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003552 } else
3553 errmsg = NULL;
3554 }
3555 if (errmsg == NULL)
3556 reason = PyUnicode_FromString(
3557 "mbstowcs() encountered an invalid multibyte sequence");
3558 if (reason == NULL)
3559 return NULL;
3560
3561 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3562 "locale", str, len,
3563 (Py_ssize_t)error_pos,
3564 (Py_ssize_t)(error_pos+1),
3565 reason);
3566 Py_DECREF(reason);
3567 if (exc != NULL) {
3568 PyCodec_StrictErrors(exc);
3569 Py_XDECREF(exc);
3570 }
3571 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003572}
3573
3574PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003575PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003576{
3577 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003578 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003579}
3580
3581
3582PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003583PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003584 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003585 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3586}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003587
Christian Heimes5894ba72007-11-04 11:43:14 +00003588PyObject*
3589PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3590{
Victor Stinner99b95382011-07-04 14:23:54 +02003591#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003592 return PyUnicode_DecodeMBCS(s, size, NULL);
3593#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003594 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003595#else
Victor Stinner793b5312011-04-27 00:24:21 +02003596 PyInterpreterState *interp = PyThreadState_GET()->interp;
3597 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3598 cannot use it to encode and decode filenames before it is loaded. Load
3599 the Python codec requires to encode at least its own filename. Use the C
3600 version of the locale codec until the codec registry is initialized and
3601 the Python codec is loaded.
3602
3603 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3604 cannot only rely on it: check also interp->fscodec_initialized for
3605 subinterpreters. */
3606 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003607 return PyUnicode_Decode(s, size,
3608 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003609 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003610 }
3611 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003612 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003613 }
Victor Stinnerad158722010-10-27 00:25:46 +00003614#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003615}
3616
Martin v. Löwis011e8422009-05-05 04:43:17 +00003617
3618int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003619_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003620{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003621 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003622
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003623 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003624 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003625 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3626 PyUnicode_GET_LENGTH(str), '\0', 1);
3627 if (pos == -1)
3628 return 0;
3629 else
3630 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003631}
3632
Antoine Pitrou13348842012-01-29 18:36:34 +01003633int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003634PyUnicode_FSConverter(PyObject* arg, void* addr)
3635{
3636 PyObject *output = NULL;
3637 Py_ssize_t size;
3638 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003639 if (arg == NULL) {
3640 Py_DECREF(*(PyObject**)addr);
3641 return 1;
3642 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003643 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003644 output = arg;
3645 Py_INCREF(output);
3646 }
3647 else {
3648 arg = PyUnicode_FromObject(arg);
3649 if (!arg)
3650 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003651 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652 Py_DECREF(arg);
3653 if (!output)
3654 return 0;
3655 if (!PyBytes_Check(output)) {
3656 Py_DECREF(output);
3657 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3658 return 0;
3659 }
3660 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003661 size = PyBytes_GET_SIZE(output);
3662 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003663 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003664 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003665 Py_DECREF(output);
3666 return 0;
3667 }
3668 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003669 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003670}
3671
3672
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003673int
3674PyUnicode_FSDecoder(PyObject* arg, void* addr)
3675{
3676 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003677 if (arg == NULL) {
3678 Py_DECREF(*(PyObject**)addr);
3679 return 1;
3680 }
3681 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003682 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003683 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003684 output = arg;
3685 Py_INCREF(output);
3686 }
3687 else {
3688 arg = PyBytes_FromObject(arg);
3689 if (!arg)
3690 return 0;
3691 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3692 PyBytes_GET_SIZE(arg));
3693 Py_DECREF(arg);
3694 if (!output)
3695 return 0;
3696 if (!PyUnicode_Check(output)) {
3697 Py_DECREF(output);
3698 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3699 return 0;
3700 }
3701 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003702 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003703 Py_DECREF(output);
3704 return 0;
3705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003706 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003707 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003708 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003709 Py_DECREF(output);
3710 return 0;
3711 }
3712 *(PyObject**)addr = output;
3713 return Py_CLEANUP_SUPPORTED;
3714}
3715
3716
Martin v. Löwis5b222132007-06-10 09:51:05 +00003717char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003718PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003719{
Christian Heimesf3863112007-11-22 07:46:41 +00003720 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003721
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003722 if (!PyUnicode_Check(unicode)) {
3723 PyErr_BadArgument();
3724 return NULL;
3725 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003726 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003727 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003728
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003729 if (PyUnicode_UTF8(unicode) == NULL) {
3730 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003731 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3732 if (bytes == NULL)
3733 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003734 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3735 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003736 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003737 Py_DECREF(bytes);
3738 return NULL;
3739 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003740 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3741 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3742 PyBytes_AS_STRING(bytes),
3743 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003744 Py_DECREF(bytes);
3745 }
3746
3747 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003748 *psize = PyUnicode_UTF8_LENGTH(unicode);
3749 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003750}
3751
3752char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003753PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003755 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3756}
3757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003758Py_UNICODE *
3759PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761 const unsigned char *one_byte;
3762#if SIZEOF_WCHAR_T == 4
3763 const Py_UCS2 *two_bytes;
3764#else
3765 const Py_UCS4 *four_bytes;
3766 const Py_UCS4 *ucs4_end;
3767 Py_ssize_t num_surrogates;
3768#endif
3769 wchar_t *w;
3770 wchar_t *wchar_end;
3771
3772 if (!PyUnicode_Check(unicode)) {
3773 PyErr_BadArgument();
3774 return NULL;
3775 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003778 assert(_PyUnicode_KIND(unicode) != 0);
3779 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003781 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003782#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003783 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3784 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785 num_surrogates = 0;
3786
3787 for (; four_bytes < ucs4_end; ++four_bytes) {
3788 if (*four_bytes > 0xFFFF)
3789 ++num_surrogates;
3790 }
3791
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003792 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3793 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3794 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795 PyErr_NoMemory();
3796 return NULL;
3797 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003798 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003799
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003800 w = _PyUnicode_WSTR(unicode);
3801 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3802 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003803 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3804 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003805 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003806 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003807 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3808 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003809 }
3810 else
3811 *w = *four_bytes;
3812
3813 if (w > wchar_end) {
3814 assert(0 && "Miscalculated string end");
3815 }
3816 }
3817 *w = 0;
3818#else
3819 /* sizeof(wchar_t) == 4 */
3820 Py_FatalError("Impossible unicode object state, wstr and str "
3821 "should share memory already.");
3822 return NULL;
3823#endif
3824 }
3825 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003826 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3827 (_PyUnicode_LENGTH(unicode) + 1));
3828 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829 PyErr_NoMemory();
3830 return NULL;
3831 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003832 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3833 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3834 w = _PyUnicode_WSTR(unicode);
3835 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003837 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3838 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 for (; w < wchar_end; ++one_byte, ++w)
3840 *w = *one_byte;
3841 /* null-terminate the wstr */
3842 *w = 0;
3843 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003844 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003846 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003847 for (; w < wchar_end; ++two_bytes, ++w)
3848 *w = *two_bytes;
3849 /* null-terminate the wstr */
3850 *w = 0;
3851#else
3852 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003853 PyObject_FREE(_PyUnicode_WSTR(unicode));
3854 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 Py_FatalError("Impossible unicode object state, wstr "
3856 "and str should share memory already.");
3857 return NULL;
3858#endif
3859 }
3860 else {
3861 assert(0 && "This should never happen.");
3862 }
3863 }
3864 }
3865 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003866 *size = PyUnicode_WSTR_LENGTH(unicode);
3867 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003868}
3869
Alexander Belopolsky40018472011-02-26 01:02:56 +00003870Py_UNICODE *
3871PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003872{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003873 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003874}
3875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003876
Alexander Belopolsky40018472011-02-26 01:02:56 +00003877Py_ssize_t
3878PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003879{
3880 if (!PyUnicode_Check(unicode)) {
3881 PyErr_BadArgument();
3882 goto onError;
3883 }
3884 return PyUnicode_GET_SIZE(unicode);
3885
Benjamin Peterson29060642009-01-31 22:14:21 +00003886 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003887 return -1;
3888}
3889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890Py_ssize_t
3891PyUnicode_GetLength(PyObject *unicode)
3892{
Victor Stinner07621332012-06-16 04:53:46 +02003893 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003894 PyErr_BadArgument();
3895 return -1;
3896 }
Victor Stinner07621332012-06-16 04:53:46 +02003897 if (PyUnicode_READY(unicode) == -1)
3898 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899 return PyUnicode_GET_LENGTH(unicode);
3900}
3901
3902Py_UCS4
3903PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3904{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003905 void *data;
3906 int kind;
3907
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003908 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3909 PyErr_BadArgument();
3910 return (Py_UCS4)-1;
3911 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003912 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003913 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003914 return (Py_UCS4)-1;
3915 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003916 data = PyUnicode_DATA(unicode);
3917 kind = PyUnicode_KIND(unicode);
3918 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003919}
3920
3921int
3922PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3923{
3924 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003925 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 return -1;
3927 }
Victor Stinner488fa492011-12-12 00:01:39 +01003928 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003929 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003930 PyErr_SetString(PyExc_IndexError, "string index out of range");
3931 return -1;
3932 }
Victor Stinner488fa492011-12-12 00:01:39 +01003933 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003934 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003935 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3936 PyErr_SetString(PyExc_ValueError, "character out of range");
3937 return -1;
3938 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003939 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3940 index, ch);
3941 return 0;
3942}
3943
Alexander Belopolsky40018472011-02-26 01:02:56 +00003944const char *
3945PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003946{
Victor Stinner42cb4622010-09-01 19:39:01 +00003947 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003948}
3949
Victor Stinner554f3f02010-06-16 23:33:54 +00003950/* create or adjust a UnicodeDecodeError */
3951static void
3952make_decode_exception(PyObject **exceptionObject,
3953 const char *encoding,
3954 const char *input, Py_ssize_t length,
3955 Py_ssize_t startpos, Py_ssize_t endpos,
3956 const char *reason)
3957{
3958 if (*exceptionObject == NULL) {
3959 *exceptionObject = PyUnicodeDecodeError_Create(
3960 encoding, input, length, startpos, endpos, reason);
3961 }
3962 else {
3963 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3964 goto onError;
3965 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3966 goto onError;
3967 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3968 goto onError;
3969 }
3970 return;
3971
3972onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003973 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003974}
3975
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003976#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003977/* error handling callback helper:
3978 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003979 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003980 and adjust various state variables.
3981 return 0 on success, -1 on error
3982*/
3983
Alexander Belopolsky40018472011-02-26 01:02:56 +00003984static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003985unicode_decode_call_errorhandler_wchar(
3986 const char *errors, PyObject **errorHandler,
3987 const char *encoding, const char *reason,
3988 const char **input, const char **inend, Py_ssize_t *startinpos,
3989 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3990 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003991{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003992 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003993
3994 PyObject *restuple = NULL;
3995 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003996 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003997 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003998 Py_ssize_t requiredsize;
3999 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004000 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004001 wchar_t *repwstr;
4002 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004003
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004004 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4005 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004006
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004007 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004008 *errorHandler = PyCodec_LookupError(errors);
4009 if (*errorHandler == NULL)
4010 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004011 }
4012
Victor Stinner554f3f02010-06-16 23:33:54 +00004013 make_decode_exception(exceptionObject,
4014 encoding,
4015 *input, *inend - *input,
4016 *startinpos, *endinpos,
4017 reason);
4018 if (*exceptionObject == NULL)
4019 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004020
4021 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4022 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004023 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004024 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004025 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004026 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027 }
4028 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004030
4031 /* Copy back the bytes variables, which might have been modified by the
4032 callback */
4033 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4034 if (!inputobj)
4035 goto onError;
4036 if (!PyBytes_Check(inputobj)) {
4037 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4038 }
4039 *input = PyBytes_AS_STRING(inputobj);
4040 insize = PyBytes_GET_SIZE(inputobj);
4041 *inend = *input + insize;
4042 /* we can DECREF safely, as the exception has another reference,
4043 so the object won't go away. */
4044 Py_DECREF(inputobj);
4045
4046 if (newpos<0)
4047 newpos = insize+newpos;
4048 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004049 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004050 goto onError;
4051 }
4052
4053 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4054 if (repwstr == NULL)
4055 goto onError;
4056 /* need more space? (at least enough for what we
4057 have+the replacement+the rest of the string (starting
4058 at the new input position), so we won't have to check space
4059 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004060 requiredsize = *outpos;
4061 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4062 goto overflow;
4063 requiredsize += repwlen;
4064 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4065 goto overflow;
4066 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004067 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004068 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004069 requiredsize = 2*outsize;
4070 if (unicode_resize(output, requiredsize) < 0)
4071 goto onError;
4072 }
4073 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4074 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004075 *endinpos = newpos;
4076 *inptr = *input + newpos;
4077
4078 /* we made it! */
4079 Py_XDECREF(restuple);
4080 return 0;
4081
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004082 overflow:
4083 PyErr_SetString(PyExc_OverflowError,
4084 "decoded result is too long for a Python string");
4085
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 onError:
4087 Py_XDECREF(restuple);
4088 return -1;
4089}
4090#endif /* HAVE_MBCS */
4091
4092static int
4093unicode_decode_call_errorhandler_writer(
4094 const char *errors, PyObject **errorHandler,
4095 const char *encoding, const char *reason,
4096 const char **input, const char **inend, Py_ssize_t *startinpos,
4097 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4098 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4099{
4100 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4101
4102 PyObject *restuple = NULL;
4103 PyObject *repunicode = NULL;
4104 Py_ssize_t insize;
4105 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004106 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004107 PyObject *inputobj = NULL;
4108
4109 if (*errorHandler == NULL) {
4110 *errorHandler = PyCodec_LookupError(errors);
4111 if (*errorHandler == NULL)
4112 goto onError;
4113 }
4114
4115 make_decode_exception(exceptionObject,
4116 encoding,
4117 *input, *inend - *input,
4118 *startinpos, *endinpos,
4119 reason);
4120 if (*exceptionObject == NULL)
4121 goto onError;
4122
4123 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4124 if (restuple == NULL)
4125 goto onError;
4126 if (!PyTuple_Check(restuple)) {
4127 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4128 goto onError;
4129 }
4130 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004131 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004132
4133 /* Copy back the bytes variables, which might have been modified by the
4134 callback */
4135 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4136 if (!inputobj)
4137 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004138 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004139 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004141 *input = PyBytes_AS_STRING(inputobj);
4142 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004143 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004144 /* we can DECREF safely, as the exception has another reference,
4145 so the object won't go away. */
4146 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004147
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004148 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004149 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004150 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004151 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004152 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004153 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004154
Victor Stinner8f674cc2013-04-17 23:02:17 +02004155 if (PyUnicode_READY(repunicode) < 0)
4156 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004157 replen = PyUnicode_GET_LENGTH(repunicode);
4158 writer->min_length += replen;
4159 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004160 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004161 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004162 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004163
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004164 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004165 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004166
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004167 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004168 Py_XDECREF(restuple);
4169 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004170
Benjamin Peterson29060642009-01-31 22:14:21 +00004171 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004173 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004174}
4175
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004176/* --- UTF-7 Codec -------------------------------------------------------- */
4177
Antoine Pitrou244651a2009-05-04 18:56:13 +00004178/* See RFC2152 for details. We encode conservatively and decode liberally. */
4179
4180/* Three simple macros defining base-64. */
4181
4182/* Is c a base-64 character? */
4183
4184#define IS_BASE64(c) \
4185 (((c) >= 'A' && (c) <= 'Z') || \
4186 ((c) >= 'a' && (c) <= 'z') || \
4187 ((c) >= '0' && (c) <= '9') || \
4188 (c) == '+' || (c) == '/')
4189
4190/* given that c is a base-64 character, what is its base-64 value? */
4191
4192#define FROM_BASE64(c) \
4193 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4194 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4195 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4196 (c) == '+' ? 62 : 63)
4197
4198/* What is the base-64 character of the bottom 6 bits of n? */
4199
4200#define TO_BASE64(n) \
4201 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4202
4203/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4204 * decoded as itself. We are permissive on decoding; the only ASCII
4205 * byte not decoding to itself is the + which begins a base64
4206 * string. */
4207
4208#define DECODE_DIRECT(c) \
4209 ((c) <= 127 && (c) != '+')
4210
4211/* The UTF-7 encoder treats ASCII characters differently according to
4212 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4213 * the above). See RFC2152. This array identifies these different
4214 * sets:
4215 * 0 : "Set D"
4216 * alphanumeric and '(),-./:?
4217 * 1 : "Set O"
4218 * !"#$%&*;<=>@[]^_`{|}
4219 * 2 : "whitespace"
4220 * ht nl cr sp
4221 * 3 : special (must be base64 encoded)
4222 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4223 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004224
Tim Petersced69f82003-09-16 20:30:58 +00004225static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004226char utf7_category[128] = {
4227/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4228 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4229/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4230 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4231/* sp ! " # $ % & ' ( ) * + , - . / */
4232 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4233/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4234 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4235/* @ A B C D E F G H I J K L M N O */
4236 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4237/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4238 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4239/* ` a b c d e f g h i j k l m n o */
4240 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4241/* p q r s t u v w x y z { | } ~ del */
4242 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004243};
4244
Antoine Pitrou244651a2009-05-04 18:56:13 +00004245/* ENCODE_DIRECT: this character should be encoded as itself. The
4246 * answer depends on whether we are encoding set O as itself, and also
4247 * on whether we are encoding whitespace as itself. RFC2152 makes it
4248 * clear that the answers to these questions vary between
4249 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004250
Antoine Pitrou244651a2009-05-04 18:56:13 +00004251#define ENCODE_DIRECT(c, directO, directWS) \
4252 ((c) < 128 && (c) > 0 && \
4253 ((utf7_category[(c)] == 0) || \
4254 (directWS && (utf7_category[(c)] == 2)) || \
4255 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004256
Alexander Belopolsky40018472011-02-26 01:02:56 +00004257PyObject *
4258PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004259 Py_ssize_t size,
4260 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004261{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004262 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4263}
4264
Antoine Pitrou244651a2009-05-04 18:56:13 +00004265/* The decoder. The only state we preserve is our read position,
4266 * i.e. how many characters we have consumed. So if we end in the
4267 * middle of a shift sequence we have to back off the read position
4268 * and the output to the beginning of the sequence, otherwise we lose
4269 * all the shift state (seen bits, number of bits seen, high
4270 * surrogate). */
4271
Alexander Belopolsky40018472011-02-26 01:02:56 +00004272PyObject *
4273PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004274 Py_ssize_t size,
4275 const char *errors,
4276 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004277{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004278 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004279 Py_ssize_t startinpos;
4280 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004282 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283 const char *errmsg = "";
4284 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004285 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286 unsigned int base64bits = 0;
4287 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004288 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004289 PyObject *errorHandler = NULL;
4290 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004291
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004292 if (size == 0) {
4293 if (consumed)
4294 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004295 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004296 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004297
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004298 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004299 _PyUnicodeWriter_Init(&writer);
4300 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004301
4302 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004303 e = s + size;
4304
4305 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004306 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004307 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004308 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004309
Antoine Pitrou244651a2009-05-04 18:56:13 +00004310 if (inShift) { /* in a base-64 section */
4311 if (IS_BASE64(ch)) { /* consume a base-64 character */
4312 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4313 base64bits += 6;
4314 s++;
4315 if (base64bits >= 16) {
4316 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004317 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004318 base64bits -= 16;
4319 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004320 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 if (surrogate) {
4322 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004323 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4324 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004325 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004326 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004328 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 }
4330 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004331 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004332 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004334 }
4335 }
Victor Stinner551ac952011-11-29 22:58:13 +01004336 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 /* first surrogate */
4338 surrogate = outCh;
4339 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004340 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004341 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343 }
4344 }
4345 }
4346 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347 inShift = 0;
4348 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004350 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004351 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004352 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004353 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 if (base64bits > 0) { /* left-over bits */
4355 if (base64bits >= 6) {
4356 /* We've seen at least one base-64 character */
4357 errmsg = "partial character in shift sequence";
4358 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 else {
4361 /* Some bits remain; they should be zero */
4362 if (base64buffer != 0) {
4363 errmsg = "non-zero padding bits in shift sequence";
4364 goto utf7Error;
4365 }
4366 }
4367 }
4368 if (ch != '-') {
4369 /* '-' is absorbed; other terminating
4370 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004371 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004372 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004373 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 }
4375 }
4376 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004377 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378 s++; /* consume '+' */
4379 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004381 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004382 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 }
4384 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004386 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004387 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004388 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389 }
4390 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004392 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004393 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004394 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004396 else {
4397 startinpos = s-starts;
4398 s++;
4399 errmsg = "unexpected special character";
4400 goto utf7Error;
4401 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004404 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004405 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004406 errors, &errorHandler,
4407 "utf7", errmsg,
4408 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004409 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004410 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 }
4412
Antoine Pitrou244651a2009-05-04 18:56:13 +00004413 /* end of string */
4414
4415 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4416 /* if we're in an inconsistent state, that's an error */
4417 if (surrogate ||
4418 (base64bits >= 6) ||
4419 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004422 errors, &errorHandler,
4423 "utf7", "unterminated shift sequence",
4424 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004425 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004426 goto onError;
4427 if (s < e)
4428 goto restart;
4429 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431
4432 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004433 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004435 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004436 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004437 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004438 writer.kind, writer.data, shiftOutStart);
4439 Py_XDECREF(errorHandler);
4440 Py_XDECREF(exc);
4441 _PyUnicodeWriter_Dealloc(&writer);
4442 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004443 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004444 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 }
4446 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004447 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004448 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004449 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004451 Py_XDECREF(errorHandler);
4452 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004453 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004454
Benjamin Peterson29060642009-01-31 22:14:21 +00004455 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004456 Py_XDECREF(errorHandler);
4457 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004458 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004459 return NULL;
4460}
4461
4462
Alexander Belopolsky40018472011-02-26 01:02:56 +00004463PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004464_PyUnicode_EncodeUTF7(PyObject *str,
4465 int base64SetO,
4466 int base64WhiteSpace,
4467 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004468{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004469 int kind;
4470 void *data;
4471 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004472 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004473 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004474 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 unsigned int base64bits = 0;
4476 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477 char * out;
4478 char * start;
4479
Benjamin Petersonbac79492012-01-14 13:34:47 -05004480 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004481 return NULL;
4482 kind = PyUnicode_KIND(str);
4483 data = PyUnicode_DATA(str);
4484 len = PyUnicode_GET_LENGTH(str);
4485
4486 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004487 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004489 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004490 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004491 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004492 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004493 if (v == NULL)
4494 return NULL;
4495
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004496 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004497 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004498 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 if (inShift) {
4501 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4502 /* shifting out */
4503 if (base64bits) { /* output remaining bits */
4504 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4505 base64buffer = 0;
4506 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004507 }
4508 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509 /* Characters not in the BASE64 set implicitly unshift the sequence
4510 so no '-' is required, except if the character is itself a '-' */
4511 if (IS_BASE64(ch) || ch == '-') {
4512 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004513 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004514 *out++ = (char) ch;
4515 }
4516 else {
4517 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004518 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520 else { /* not in a shift sequence */
4521 if (ch == '+') {
4522 *out++ = '+';
4523 *out++ = '-';
4524 }
4525 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4526 *out++ = (char) ch;
4527 }
4528 else {
4529 *out++ = '+';
4530 inShift = 1;
4531 goto encode_char;
4532 }
4533 }
4534 continue;
4535encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004537 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004538
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 /* code first surrogate */
4540 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004541 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 while (base64bits >= 6) {
4543 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4544 base64bits -= 6;
4545 }
4546 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004547 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 base64bits += 16;
4550 base64buffer = (base64buffer << 16) | ch;
4551 while (base64bits >= 6) {
4552 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4553 base64bits -= 6;
4554 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004555 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556 if (base64bits)
4557 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4558 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004560 if (_PyBytes_Resize(&v, out - start) < 0)
4561 return NULL;
4562 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004563}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004564PyObject *
4565PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4566 Py_ssize_t size,
4567 int base64SetO,
4568 int base64WhiteSpace,
4569 const char *errors)
4570{
4571 PyObject *result;
4572 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4573 if (tmp == NULL)
4574 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004575 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004576 base64WhiteSpace, errors);
4577 Py_DECREF(tmp);
4578 return result;
4579}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004580
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581#undef IS_BASE64
4582#undef FROM_BASE64
4583#undef TO_BASE64
4584#undef DECODE_DIRECT
4585#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004586
Guido van Rossumd57fd912000-03-10 22:53:23 +00004587/* --- UTF-8 Codec -------------------------------------------------------- */
4588
Alexander Belopolsky40018472011-02-26 01:02:56 +00004589PyObject *
4590PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004591 Py_ssize_t size,
4592 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004593{
Walter Dörwald69652032004-09-07 20:24:22 +00004594 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4595}
4596
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004597#include "stringlib/asciilib.h"
4598#include "stringlib/codecs.h"
4599#include "stringlib/undef.h"
4600
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004601#include "stringlib/ucs1lib.h"
4602#include "stringlib/codecs.h"
4603#include "stringlib/undef.h"
4604
4605#include "stringlib/ucs2lib.h"
4606#include "stringlib/codecs.h"
4607#include "stringlib/undef.h"
4608
4609#include "stringlib/ucs4lib.h"
4610#include "stringlib/codecs.h"
4611#include "stringlib/undef.h"
4612
Antoine Pitrouab868312009-01-10 15:40:25 +00004613/* Mask to quickly check whether a C 'long' contains a
4614 non-ASCII, UTF8-encoded char. */
4615#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004616# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004617#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004618# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004619#else
4620# error C 'long' size should be either 4 or 8!
4621#endif
4622
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004623static Py_ssize_t
4624ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004625{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004626 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004627 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004628
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004629 /*
4630 * Issue #17237: m68k is a bit different from most architectures in
4631 * that objects do not use "natural alignment" - for example, int and
4632 * long are only aligned at 2-byte boundaries. Therefore the assert()
4633 * won't work; also, tests have shown that skipping the "optimised
4634 * version" will even speed up m68k.
4635 */
4636#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004637#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004638 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4639 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004640 /* Fast path, see in STRINGLIB(utf8_decode) for
4641 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004642 /* Help allocation */
4643 const char *_p = p;
4644 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004645 while (_p < aligned_end) {
4646 unsigned long value = *(const unsigned long *) _p;
4647 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004648 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004649 *((unsigned long *)q) = value;
4650 _p += SIZEOF_LONG;
4651 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004652 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004653 p = _p;
4654 while (p < end) {
4655 if ((unsigned char)*p & 0x80)
4656 break;
4657 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004658 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004659 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004660 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004662#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004663 while (p < end) {
4664 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4665 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004666 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004667 /* Help allocation */
4668 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004669 while (_p < aligned_end) {
4670 unsigned long value = *(unsigned long *) _p;
4671 if (value & ASCII_CHAR_MASK)
4672 break;
4673 _p += SIZEOF_LONG;
4674 }
4675 p = _p;
4676 if (_p == end)
4677 break;
4678 }
4679 if ((unsigned char)*p & 0x80)
4680 break;
4681 ++p;
4682 }
4683 memcpy(dest, start, p - start);
4684 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685}
Antoine Pitrouab868312009-01-10 15:40:25 +00004686
Victor Stinner785938e2011-12-11 20:09:03 +01004687PyObject *
4688PyUnicode_DecodeUTF8Stateful(const char *s,
4689 Py_ssize_t size,
4690 const char *errors,
4691 Py_ssize_t *consumed)
4692{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004693 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004694 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004695 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696
4697 Py_ssize_t startinpos;
4698 Py_ssize_t endinpos;
4699 const char *errmsg = "";
4700 PyObject *errorHandler = NULL;
4701 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004702
4703 if (size == 0) {
4704 if (consumed)
4705 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004706 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004707 }
4708
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004709 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4710 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004711 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 *consumed = 1;
4713 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004714 }
4715
Victor Stinner8f674cc2013-04-17 23:02:17 +02004716 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004717 writer.min_length = size;
4718 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004720
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004721 writer.pos = ascii_decode(s, end, writer.data);
4722 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723 while (s < end) {
4724 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004725 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004727 if (PyUnicode_IS_ASCII(writer.buffer))
4728 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004729 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004730 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004732 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004733 } else {
4734 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004735 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004736 }
4737
4738 switch (ch) {
4739 case 0:
4740 if (s == end || consumed)
4741 goto End;
4742 errmsg = "unexpected end of data";
4743 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004744 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 break;
4746 case 1:
4747 errmsg = "invalid start byte";
4748 startinpos = s - starts;
4749 endinpos = startinpos + 1;
4750 break;
4751 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004752 case 3:
4753 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004754 errmsg = "invalid continuation byte";
4755 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004756 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004757 break;
4758 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004759 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760 goto onError;
4761 continue;
4762 }
4763
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004764 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765 errors, &errorHandler,
4766 "utf-8", errmsg,
4767 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004768 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004769 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004770 }
4771
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004773 if (consumed)
4774 *consumed = s - starts;
4775
4776 Py_XDECREF(errorHandler);
4777 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004778 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004779
4780onError:
4781 Py_XDECREF(errorHandler);
4782 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004783 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004785}
4786
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004787#ifdef __APPLE__
4788
4789/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004790 used to decode the command line arguments on Mac OS X.
4791
4792 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004793 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004794
4795wchar_t*
4796_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4797{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004798 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799 wchar_t *unicode;
4800 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004801
4802 /* Note: size will always be longer than the resulting Unicode
4803 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004804 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004805 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004806 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004807 if (!unicode)
4808 return NULL;
4809
4810 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004811 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004812 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004813 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004815#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004816 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004819#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004820 if (ch > 0xFF) {
4821#if SIZEOF_WCHAR_T == 4
4822 assert(0);
4823#else
4824 assert(Py_UNICODE_IS_SURROGATE(ch));
4825 /* compute and append the two surrogates: */
4826 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4827 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4828#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004830 else {
4831 if (!ch && s == e)
4832 break;
4833 /* surrogateescape */
4834 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4835 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838 return unicode;
4839}
4840
4841#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004843/* Primary internal function which creates utf8 encoded bytes objects.
4844
4845 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004846 and allocate exactly as much space needed at the end. Else allocate the
4847 maximum possible needed (4 result bytes per Unicode character), and return
4848 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004849*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004850PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004851_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004852{
Victor Stinner6099a032011-12-18 14:22:26 +01004853 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004854 void *data;
4855 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004857 if (!PyUnicode_Check(unicode)) {
4858 PyErr_BadArgument();
4859 return NULL;
4860 }
4861
4862 if (PyUnicode_READY(unicode) == -1)
4863 return NULL;
4864
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004865 if (PyUnicode_UTF8(unicode))
4866 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4867 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004868
4869 kind = PyUnicode_KIND(unicode);
4870 data = PyUnicode_DATA(unicode);
4871 size = PyUnicode_GET_LENGTH(unicode);
4872
Benjamin Petersonead6b532011-12-20 17:23:42 -06004873 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004874 default:
4875 assert(0);
4876 case PyUnicode_1BYTE_KIND:
4877 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4878 assert(!PyUnicode_IS_ASCII(unicode));
4879 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4880 case PyUnicode_2BYTE_KIND:
4881 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4882 case PyUnicode_4BYTE_KIND:
4883 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004884 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004885}
4886
Alexander Belopolsky40018472011-02-26 01:02:56 +00004887PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004888PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4889 Py_ssize_t size,
4890 const char *errors)
4891{
4892 PyObject *v, *unicode;
4893
4894 unicode = PyUnicode_FromUnicode(s, size);
4895 if (unicode == NULL)
4896 return NULL;
4897 v = _PyUnicode_AsUTF8String(unicode, errors);
4898 Py_DECREF(unicode);
4899 return v;
4900}
4901
4902PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004903PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004905 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004906}
4907
Walter Dörwald41980ca2007-08-16 21:55:45 +00004908/* --- UTF-32 Codec ------------------------------------------------------- */
4909
4910PyObject *
4911PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004912 Py_ssize_t size,
4913 const char *errors,
4914 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004915{
4916 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4917}
4918
4919PyObject *
4920PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004921 Py_ssize_t size,
4922 const char *errors,
4923 int *byteorder,
4924 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004925{
4926 const char *starts = s;
4927 Py_ssize_t startinpos;
4928 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004929 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004930 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004931 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004932 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004933 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004934 PyObject *errorHandler = NULL;
4935 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004936
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937 q = (unsigned char *)s;
4938 e = q + size;
4939
4940 if (byteorder)
4941 bo = *byteorder;
4942
4943 /* Check for BOM marks (U+FEFF) in the input and adjust current
4944 byte order setting accordingly. In native mode, the leading BOM
4945 mark is skipped, in all other modes, it is copied to the output
4946 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004947 if (bo == 0 && size >= 4) {
4948 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4949 if (bom == 0x0000FEFF) {
4950 bo = -1;
4951 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004952 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004953 else if (bom == 0xFFFE0000) {
4954 bo = 1;
4955 q += 4;
4956 }
4957 if (byteorder)
4958 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004959 }
4960
Victor Stinnere64322e2012-10-30 23:12:47 +01004961 if (q == e) {
4962 if (consumed)
4963 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004964 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004965 }
4966
Victor Stinnere64322e2012-10-30 23:12:47 +01004967#ifdef WORDS_BIGENDIAN
4968 le = bo < 0;
4969#else
4970 le = bo <= 0;
4971#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004972 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004973
Victor Stinner8f674cc2013-04-17 23:02:17 +02004974 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004975 writer.min_length = (e - q + 3) / 4;
4976 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004977 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004978
Victor Stinnere64322e2012-10-30 23:12:47 +01004979 while (1) {
4980 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004982
Victor Stinnere64322e2012-10-30 23:12:47 +01004983 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 enum PyUnicode_Kind kind = writer.kind;
4985 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004986 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004988 if (le) {
4989 do {
4990 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4991 if (ch > maxch)
4992 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004993 if (kind != PyUnicode_1BYTE_KIND &&
4994 Py_UNICODE_IS_SURROGATE(ch))
4995 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004996 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004997 q += 4;
4998 } while (q <= last);
4999 }
5000 else {
5001 do {
5002 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5003 if (ch > maxch)
5004 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005005 if (kind != PyUnicode_1BYTE_KIND &&
5006 Py_UNICODE_IS_SURROGATE(ch))
5007 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005009 q += 4;
5010 } while (q <= last);
5011 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005012 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005013 }
5014
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005015 if (Py_UNICODE_IS_SURROGATE(ch)) {
5016 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5017 startinpos = ((const char *)q) - starts;
5018 endinpos = startinpos + 4;
5019 }
5020 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005022 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005023 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005025 startinpos = ((const char *)q) - starts;
5026 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005028 else {
5029 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005030 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005031 goto onError;
5032 q += 4;
5033 continue;
5034 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005035 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005036 startinpos = ((const char *)q) - starts;
5037 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005038 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005039
5040 /* The remaining input chars are ignored if the callback
5041 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005042 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005043 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005044 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005046 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005047 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005048 }
5049
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052
Walter Dörwald41980ca2007-08-16 21:55:45 +00005053 Py_XDECREF(errorHandler);
5054 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005055 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005058 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005059 Py_XDECREF(errorHandler);
5060 Py_XDECREF(exc);
5061 return NULL;
5062}
5063
5064PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005065_PyUnicode_EncodeUTF32(PyObject *str,
5066 const char *errors,
5067 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005068{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005069 int kind;
5070 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005071 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005072 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005073 unsigned char *p;
5074 Py_ssize_t nsize, i;
5075 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005076#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005077 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005078#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005079 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005081 const char *encoding;
5082 PyObject *errorHandler = NULL;
5083 PyObject *exc = NULL;
5084 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085
Serhiy Storchaka30793282014-01-04 22:44:01 +02005086#define STORECHAR(CH) \
5087 do { \
5088 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5089 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5090 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5091 p[iorder[0]] = (CH) & 0xff; \
5092 p += 4; \
5093 } while(0)
5094
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005095 if (!PyUnicode_Check(str)) {
5096 PyErr_BadArgument();
5097 return NULL;
5098 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005099 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005100 return NULL;
5101 kind = PyUnicode_KIND(str);
5102 data = PyUnicode_DATA(str);
5103 len = PyUnicode_GET_LENGTH(str);
5104
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005105 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005106 if (nsize > PY_SSIZE_T_MAX / 4)
5107 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005108 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005109 if (v == NULL)
5110 return NULL;
5111
Serhiy Storchaka30793282014-01-04 22:44:01 +02005112 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005114 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005115 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005116 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117
Serhiy Storchaka30793282014-01-04 22:44:01 +02005118 if (byteorder == -1) {
5119 /* force LE */
5120 iorder[0] = 0;
5121 iorder[1] = 1;
5122 iorder[2] = 2;
5123 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005124 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005125 }
5126 else if (byteorder == 1) {
5127 /* force BE */
5128 iorder[0] = 3;
5129 iorder[1] = 2;
5130 iorder[2] = 1;
5131 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005132 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005133 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005134 else
5135 encoding = "utf-32";
5136
5137 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005138 for (i = 0; i < len; i++)
5139 STORECHAR(PyUnicode_READ(kind, data, i));
5140 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005141 }
5142
Serhiy Storchaka30793282014-01-04 22:44:01 +02005143 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005144 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005145 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5146 i++;
5147 assert(ch <= MAX_UNICODE);
5148 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5149 STORECHAR(ch);
5150 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005151 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005152
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005153 rep = unicode_encode_call_errorhandler(
5154 errors, &errorHandler,
5155 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005156 str, &exc, i-1, i, &i);
5157
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005158 if (!rep)
5159 goto error;
5160
5161 if (PyBytes_Check(rep)) {
5162 repsize = PyBytes_GET_SIZE(rep);
5163 if (repsize & 3) {
5164 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005165 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005166 "surrogates not allowed");
5167 goto error;
5168 }
5169 moreunits = repsize / 4;
5170 }
5171 else {
5172 assert(PyUnicode_Check(rep));
5173 if (PyUnicode_READY(rep) < 0)
5174 goto error;
5175 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5176 if (!PyUnicode_IS_ASCII(rep)) {
5177 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005178 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005179 "surrogates not allowed");
5180 goto error;
5181 }
5182 }
5183
5184 /* four bytes are reserved for each surrogate */
5185 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005186 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005187 Py_ssize_t morebytes = 4 * (moreunits - 1);
5188 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5189 /* integer overflow */
5190 PyErr_NoMemory();
5191 goto error;
5192 }
5193 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5194 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005195 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005196 }
5197
5198 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005199 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5200 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005202 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005203 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005204 repdata = PyUnicode_1BYTE_DATA(rep);
5205 while (repsize--) {
5206 Py_UCS4 ch = *repdata++;
5207 STORECHAR(ch);
5208 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005209 }
5210
5211 Py_CLEAR(rep);
5212 }
5213
5214 /* Cut back to size actually needed. This is necessary for, for example,
5215 encoding of a string containing isolated surrogates and the 'ignore'
5216 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005217 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005218 if (nsize != PyBytes_GET_SIZE(v))
5219 _PyBytes_Resize(&v, nsize);
5220 Py_XDECREF(errorHandler);
5221 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005222 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005223 error:
5224 Py_XDECREF(rep);
5225 Py_XDECREF(errorHandler);
5226 Py_XDECREF(exc);
5227 Py_XDECREF(v);
5228 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005229#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005230}
5231
Alexander Belopolsky40018472011-02-26 01:02:56 +00005232PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005233PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5234 Py_ssize_t size,
5235 const char *errors,
5236 int byteorder)
5237{
5238 PyObject *result;
5239 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5240 if (tmp == NULL)
5241 return NULL;
5242 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5243 Py_DECREF(tmp);
5244 return result;
5245}
5246
5247PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005248PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249{
Victor Stinnerb960b342011-11-20 19:12:52 +01005250 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005251}
5252
Guido van Rossumd57fd912000-03-10 22:53:23 +00005253/* --- UTF-16 Codec ------------------------------------------------------- */
5254
Tim Peters772747b2001-08-09 22:21:55 +00005255PyObject *
5256PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005257 Py_ssize_t size,
5258 const char *errors,
5259 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005260{
Walter Dörwald69652032004-09-07 20:24:22 +00005261 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5262}
5263
5264PyObject *
5265PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005266 Py_ssize_t size,
5267 const char *errors,
5268 int *byteorder,
5269 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005270{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005271 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005272 Py_ssize_t startinpos;
5273 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005274 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005275 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005276 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005277 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005278 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005279 PyObject *errorHandler = NULL;
5280 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005281 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005282
Tim Peters772747b2001-08-09 22:21:55 +00005283 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005284 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005285
5286 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005287 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005288
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005289 /* Check for BOM marks (U+FEFF) in the input and adjust current
5290 byte order setting accordingly. In native mode, the leading BOM
5291 mark is skipped, in all other modes, it is copied to the output
5292 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005293 if (bo == 0 && size >= 2) {
5294 const Py_UCS4 bom = (q[1] << 8) | q[0];
5295 if (bom == 0xFEFF) {
5296 q += 2;
5297 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005298 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005299 else if (bom == 0xFFFE) {
5300 q += 2;
5301 bo = 1;
5302 }
5303 if (byteorder)
5304 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005305 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005306
Antoine Pitrou63065d72012-05-15 23:48:04 +02005307 if (q == e) {
5308 if (consumed)
5309 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005310 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005311 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005312
Christian Heimes743e0cd2012-10-17 23:52:17 +02005313#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005314 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005315 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005316#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005317 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005318 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005319#endif
Tim Peters772747b2001-08-09 22:21:55 +00005320
Antoine Pitrou63065d72012-05-15 23:48:04 +02005321 /* Note: size will always be longer than the resulting Unicode
5322 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005323 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005324 writer.min_length = (e - q + 1) / 2;
5325 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005326 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005327
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328 while (1) {
5329 Py_UCS4 ch = 0;
5330 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005331 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005332 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005333 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005336 native_ordering);
5337 else
5338 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005339 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005340 native_ordering);
5341 } else if (kind == PyUnicode_2BYTE_KIND) {
5342 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005343 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005344 native_ordering);
5345 } else {
5346 assert(kind == PyUnicode_4BYTE_KIND);
5347 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005348 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005349 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005350 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005351 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005352
Antoine Pitrou63065d72012-05-15 23:48:04 +02005353 switch (ch)
5354 {
5355 case 0:
5356 /* remaining byte at the end? (size should be even) */
5357 if (q == e || consumed)
5358 goto End;
5359 errmsg = "truncated data";
5360 startinpos = ((const char *)q) - starts;
5361 endinpos = ((const char *)e) - starts;
5362 break;
5363 /* The remaining input chars are ignored if the callback
5364 chooses to skip the input */
5365 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005366 q -= 2;
5367 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005368 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005370 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 endinpos = ((const char *)e) - starts;
5372 break;
5373 case 2:
5374 errmsg = "illegal encoding";
5375 startinpos = ((const char *)q) - 2 - starts;
5376 endinpos = startinpos + 2;
5377 break;
5378 case 3:
5379 errmsg = "illegal UTF-16 surrogate";
5380 startinpos = ((const char *)q) - 4 - starts;
5381 endinpos = startinpos + 2;
5382 break;
5383 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005384 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005385 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005386 continue;
5387 }
5388
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005389 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005390 errors,
5391 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005392 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005393 &starts,
5394 (const char **)&e,
5395 &startinpos,
5396 &endinpos,
5397 &exc,
5398 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005399 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005400 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005401 }
5402
Antoine Pitrou63065d72012-05-15 23:48:04 +02005403End:
Walter Dörwald69652032004-09-07 20:24:22 +00005404 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005406
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005407 Py_XDECREF(errorHandler);
5408 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005409 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005410
Benjamin Peterson29060642009-01-31 22:14:21 +00005411 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005412 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005413 Py_XDECREF(errorHandler);
5414 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415 return NULL;
5416}
5417
Tim Peters772747b2001-08-09 22:21:55 +00005418PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005419_PyUnicode_EncodeUTF16(PyObject *str,
5420 const char *errors,
5421 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005422{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005423 enum PyUnicode_Kind kind;
5424 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005425 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005426 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005427 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005428 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005429#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005430 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005431#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005432 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005433#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005434 const char *encoding;
5435 Py_ssize_t nsize, pos;
5436 PyObject *errorHandler = NULL;
5437 PyObject *exc = NULL;
5438 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005439
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005440 if (!PyUnicode_Check(str)) {
5441 PyErr_BadArgument();
5442 return NULL;
5443 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005444 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005445 return NULL;
5446 kind = PyUnicode_KIND(str);
5447 data = PyUnicode_DATA(str);
5448 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005449
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005450 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005451 if (kind == PyUnicode_4BYTE_KIND) {
5452 const Py_UCS4 *in = (const Py_UCS4 *)data;
5453 const Py_UCS4 *end = in + len;
5454 while (in < end)
5455 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005456 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005457 }
5458 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005459 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005460 nsize = len + pairs + (byteorder == 0);
5461 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005462 if (v == NULL)
5463 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005464
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005465 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005466 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005467 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005468 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005469 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005470 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005471 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005472
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005473 if (kind == PyUnicode_1BYTE_KIND) {
5474 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5475 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005476 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005477
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 if (byteorder < 0)
5479 encoding = "utf-16-le";
5480 else if (byteorder > 0)
5481 encoding = "utf-16-be";
5482 else
5483 encoding = "utf-16";
5484
5485 pos = 0;
5486 while (pos < len) {
5487 Py_ssize_t repsize, moreunits;
5488
5489 if (kind == PyUnicode_2BYTE_KIND) {
5490 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5491 &out, native_ordering);
5492 }
5493 else {
5494 assert(kind == PyUnicode_4BYTE_KIND);
5495 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5496 &out, native_ordering);
5497 }
5498 if (pos == len)
5499 break;
5500
5501 rep = unicode_encode_call_errorhandler(
5502 errors, &errorHandler,
5503 encoding, "surrogates not allowed",
5504 str, &exc, pos, pos + 1, &pos);
5505 if (!rep)
5506 goto error;
5507
5508 if (PyBytes_Check(rep)) {
5509 repsize = PyBytes_GET_SIZE(rep);
5510 if (repsize & 1) {
5511 raise_encode_exception(&exc, encoding,
5512 str, pos - 1, pos,
5513 "surrogates not allowed");
5514 goto error;
5515 }
5516 moreunits = repsize / 2;
5517 }
5518 else {
5519 assert(PyUnicode_Check(rep));
5520 if (PyUnicode_READY(rep) < 0)
5521 goto error;
5522 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5523 if (!PyUnicode_IS_ASCII(rep)) {
5524 raise_encode_exception(&exc, encoding,
5525 str, pos - 1, pos,
5526 "surrogates not allowed");
5527 goto error;
5528 }
5529 }
5530
5531 /* two bytes are reserved for each surrogate */
5532 if (moreunits > 1) {
5533 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5534 Py_ssize_t morebytes = 2 * (moreunits - 1);
5535 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5536 /* integer overflow */
5537 PyErr_NoMemory();
5538 goto error;
5539 }
5540 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5541 goto error;
5542 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5543 }
5544
5545 if (PyBytes_Check(rep)) {
5546 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5547 out += moreunits;
5548 } else /* rep is unicode */ {
5549 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5550 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5551 &out, native_ordering);
5552 }
5553
5554 Py_CLEAR(rep);
5555 }
5556
5557 /* Cut back to size actually needed. This is necessary for, for example,
5558 encoding of a string containing isolated surrogates and the 'ignore' handler
5559 is used. */
5560 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5561 if (nsize != PyBytes_GET_SIZE(v))
5562 _PyBytes_Resize(&v, nsize);
5563 Py_XDECREF(errorHandler);
5564 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005565 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005566 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005567 error:
5568 Py_XDECREF(rep);
5569 Py_XDECREF(errorHandler);
5570 Py_XDECREF(exc);
5571 Py_XDECREF(v);
5572 return NULL;
5573#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005574}
5575
Alexander Belopolsky40018472011-02-26 01:02:56 +00005576PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005577PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5578 Py_ssize_t size,
5579 const char *errors,
5580 int byteorder)
5581{
5582 PyObject *result;
5583 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5584 if (tmp == NULL)
5585 return NULL;
5586 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5587 Py_DECREF(tmp);
5588 return result;
5589}
5590
5591PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005592PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005594 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005595}
5596
5597/* --- Unicode Escape Codec ----------------------------------------------- */
5598
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005599/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5600 if all the escapes in the string make it still a valid ASCII string.
5601 Returns -1 if any escapes were found which cause the string to
5602 pop out of ASCII range. Otherwise returns the length of the
5603 required buffer to hold the string.
5604 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005605static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005606length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5607{
5608 const unsigned char *p = (const unsigned char *)s;
5609 const unsigned char *end = p + size;
5610 Py_ssize_t length = 0;
5611
5612 if (size < 0)
5613 return -1;
5614
5615 for (; p < end; ++p) {
5616 if (*p > 127) {
5617 /* Non-ASCII */
5618 return -1;
5619 }
5620 else if (*p != '\\') {
5621 /* Normal character */
5622 ++length;
5623 }
5624 else {
5625 /* Backslash-escape, check next char */
5626 ++p;
5627 /* Escape sequence reaches till end of string or
5628 non-ASCII follow-up. */
5629 if (p >= end || *p > 127)
5630 return -1;
5631 switch (*p) {
5632 case '\n':
5633 /* backslash + \n result in zero characters */
5634 break;
5635 case '\\': case '\'': case '\"':
5636 case 'b': case 'f': case 't':
5637 case 'n': case 'r': case 'v': case 'a':
5638 ++length;
5639 break;
5640 case '0': case '1': case '2': case '3':
5641 case '4': case '5': case '6': case '7':
5642 case 'x': case 'u': case 'U': case 'N':
5643 /* these do not guarantee ASCII characters */
5644 return -1;
5645 default:
5646 /* count the backslash + the other character */
5647 length += 2;
5648 }
5649 }
5650 }
5651 return length;
5652}
5653
Fredrik Lundh06d12682001-01-24 07:59:11 +00005654static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005655
Alexander Belopolsky40018472011-02-26 01:02:56 +00005656PyObject *
5657PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005658 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005659 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005660{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005661 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005662 Py_ssize_t startinpos;
5663 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005664 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005666 char* message;
5667 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005668 PyObject *errorHandler = NULL;
5669 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005670 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005671
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005672 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005673 if (len == 0)
5674 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005675
5676 /* After length_of_escaped_ascii_string() there are two alternatives,
5677 either the string is pure ASCII with named escapes like \n, etc.
5678 and we determined it's exact size (common case)
5679 or it contains \x, \u, ... escape sequences. then we create a
5680 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005681 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005682 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005683 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005684 }
5685 else {
5686 /* Escaped strings will always be longer than the resulting
5687 Unicode string, so we start with size here and then reduce the
5688 length after conversion to the true value.
5689 (but if the error callback returns a long replacement string
5690 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005691 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005692 }
5693
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005695 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005697
Guido van Rossumd57fd912000-03-10 22:53:23 +00005698 while (s < end) {
5699 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005700 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005701 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005702
5703 /* Non-escape characters are interpreted as Unicode ordinals */
5704 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005705 x = (unsigned char)*s;
5706 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005707 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005708 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709 continue;
5710 }
5711
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005712 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005713 /* \ - Escapes */
5714 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005715 c = *s++;
5716 if (s > end)
5717 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005718
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005719 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005720
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005722#define WRITECHAR(ch) \
5723 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005724 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005725 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005726 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005727
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005729 case '\\': WRITECHAR('\\'); break;
5730 case '\'': WRITECHAR('\''); break;
5731 case '\"': WRITECHAR('\"'); break;
5732 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005733 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005734 case 'f': WRITECHAR('\014'); break;
5735 case 't': WRITECHAR('\t'); break;
5736 case 'n': WRITECHAR('\n'); break;
5737 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005739 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005740 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005741 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 case '0': case '1': case '2': case '3':
5745 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005746 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005747 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005748 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005749 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005750 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005752 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 break;
5754
Benjamin Peterson29060642009-01-31 22:14:21 +00005755 /* hex escapes */
5756 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005757 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005758 digits = 2;
5759 message = "truncated \\xXX escape";
5760 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761
Benjamin Peterson29060642009-01-31 22:14:21 +00005762 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005764 digits = 4;
5765 message = "truncated \\uXXXX escape";
5766 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005769 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005770 digits = 8;
5771 message = "truncated \\UXXXXXXXX escape";
5772 hexescape:
5773 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005774 if (end - s < digits) {
5775 /* count only hex digits */
5776 for (; s < end; ++s) {
5777 c = (unsigned char)*s;
5778 if (!Py_ISXDIGIT(c))
5779 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005780 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005781 goto error;
5782 }
5783 for (; digits--; ++s) {
5784 c = (unsigned char)*s;
5785 if (!Py_ISXDIGIT(c))
5786 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005787 chr = (chr<<4) & ~0xF;
5788 if (c >= '0' && c <= '9')
5789 chr += c - '0';
5790 else if (c >= 'a' && c <= 'f')
5791 chr += 10 + c - 'a';
5792 else
5793 chr += 10 + c - 'A';
5794 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005795 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 /* _decoding_error will have already written into the
5797 target buffer. */
5798 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005800 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005801 message = "illegal Unicode character";
5802 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005803 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005804 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005805 break;
5806
Benjamin Peterson29060642009-01-31 22:14:21 +00005807 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005808 case 'N':
5809 message = "malformed \\N character escape";
5810 if (ucnhash_CAPI == NULL) {
5811 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005812 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5813 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005814 if (ucnhash_CAPI == NULL)
5815 goto ucnhashError;
5816 }
5817 if (*s == '{') {
5818 const char *start = s+1;
5819 /* look for the closing brace */
5820 while (*s != '}' && s < end)
5821 s++;
5822 if (s > start && s < end && *s == '}') {
5823 /* found a name. look it up in the unicode database */
5824 message = "unknown Unicode character name";
5825 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005826 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005827 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005828 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005829 goto store;
5830 }
5831 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005832 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005833
5834 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005835 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005836 message = "\\ at end of string";
5837 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005838 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005839 }
5840 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005841 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005842 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005843 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005844 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005846 continue;
5847
5848 error:
5849 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005850 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005851 errors, &errorHandler,
5852 "unicodeescape", message,
5853 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005854 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005855 goto onError;
5856 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005858#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005860 Py_XDECREF(errorHandler);
5861 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005862 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005863
Benjamin Peterson29060642009-01-31 22:14:21 +00005864 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005865 PyErr_SetString(
5866 PyExc_UnicodeError,
5867 "\\N escapes not supported (can't load unicodedata module)"
5868 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005869 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005870 Py_XDECREF(errorHandler);
5871 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005872 return NULL;
5873
Benjamin Peterson29060642009-01-31 22:14:21 +00005874 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005875 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005876 Py_XDECREF(errorHandler);
5877 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 return NULL;
5879}
5880
5881/* Return a Unicode-Escape string version of the Unicode object.
5882
5883 If quotes is true, the string is enclosed in u"" or u'' quotes as
5884 appropriate.
5885
5886*/
5887
Alexander Belopolsky40018472011-02-26 01:02:56 +00005888PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005891 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005892 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005894 int kind;
5895 void *data;
5896 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897
Ezio Melottie7f90372012-10-05 03:33:31 +03005898 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005899 escape.
5900
Ezio Melottie7f90372012-10-05 03:33:31 +03005901 For UCS1 strings it's '\xxx', 4 bytes per source character.
5902 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5903 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005904 */
5905
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005906 if (!PyUnicode_Check(unicode)) {
5907 PyErr_BadArgument();
5908 return NULL;
5909 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005910 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005911 return NULL;
5912 len = PyUnicode_GET_LENGTH(unicode);
5913 kind = PyUnicode_KIND(unicode);
5914 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005915 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5917 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5918 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5919 }
5920
5921 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005922 return PyBytes_FromStringAndSize(NULL, 0);
5923
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005924 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005926
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005927 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 if (repr == NULL)
5932 return NULL;
5933
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005934 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005936 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005937 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005938
Walter Dörwald79e913e2007-05-12 11:08:06 +00005939 /* Escape backslashes */
5940 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 *p++ = '\\';
5942 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005943 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005944 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005945
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005946 /* Map 21-bit characters to '\U00xxxxxx' */
5947 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005948 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005949 *p++ = '\\';
5950 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005951 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5952 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5953 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5954 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5955 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5956 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5957 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5958 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005960 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005961
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005963 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964 *p++ = '\\';
5965 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005966 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5967 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5968 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5969 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005971
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005972 /* Map special whitespace to '\t', \n', '\r' */
5973 else if (ch == '\t') {
5974 *p++ = '\\';
5975 *p++ = 't';
5976 }
5977 else if (ch == '\n') {
5978 *p++ = '\\';
5979 *p++ = 'n';
5980 }
5981 else if (ch == '\r') {
5982 *p++ = '\\';
5983 *p++ = 'r';
5984 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005985
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005986 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005987 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005989 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005990 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5991 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005992 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005993
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994 /* Copy everything else as-is */
5995 else
5996 *p++ = (char) ch;
5997 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005999 assert(p - PyBytes_AS_STRING(repr) > 0);
6000 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6001 return NULL;
6002 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003}
6004
Alexander Belopolsky40018472011-02-26 01:02:56 +00006005PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006006PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6007 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006009 PyObject *result;
6010 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6011 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006013 result = PyUnicode_AsUnicodeEscapeString(tmp);
6014 Py_DECREF(tmp);
6015 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016}
6017
6018/* --- Raw Unicode Escape Codec ------------------------------------------- */
6019
Alexander Belopolsky40018472011-02-26 01:02:56 +00006020PyObject *
6021PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006022 Py_ssize_t size,
6023 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006025 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006026 Py_ssize_t startinpos;
6027 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006028 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 const char *end;
6030 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006031 PyObject *errorHandler = NULL;
6032 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006033
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006034 if (size == 0)
6035 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006036
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 /* Escaped strings will always be longer than the resulting
6038 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006039 length after conversion to the true value. (But decoding error
6040 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006041 _PyUnicodeWriter_Init(&writer);
6042 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006043
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 end = s + size;
6045 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 unsigned char c;
6047 Py_UCS4 x;
6048 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006049 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 /* Non-escape characters are interpreted as Unicode ordinals */
6052 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006053 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006054 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006055 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006057 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 startinpos = s-starts;
6059
6060 /* \u-escapes are only interpreted iff the number of leading
6061 backslashes if odd */
6062 bs = s;
6063 for (;s < end;) {
6064 if (*s != '\\')
6065 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006066 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006067 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006068 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006069 }
6070 if (((s - bs) & 1) == 0 ||
6071 s >= end ||
6072 (*s != 'u' && *s != 'U')) {
6073 continue;
6074 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006075 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 count = *s=='u' ? 4 : 8;
6077 s++;
6078
6079 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 for (x = 0, i = 0; i < count; ++i, ++s) {
6081 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006082 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006084 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 errors, &errorHandler,
6086 "rawunicodeescape", "truncated \\uXXXX",
6087 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006088 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 goto onError;
6090 goto nextByte;
6091 }
6092 x = (x<<4) & ~0xF;
6093 if (c >= '0' && c <= '9')
6094 x += c - '0';
6095 else if (c >= 'a' && c <= 'f')
6096 x += 10 + c - 'a';
6097 else
6098 x += 10 + c - 'A';
6099 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006100 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006101 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006102 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006103 }
6104 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006105 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006106 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006107 errors, &errorHandler,
6108 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006110 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006112 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006113 nextByte:
6114 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006116 Py_XDECREF(errorHandler);
6117 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006118 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006119
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006121 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006122 Py_XDECREF(errorHandler);
6123 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006124 return NULL;
6125}
6126
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127
Alexander Belopolsky40018472011-02-26 01:02:56 +00006128PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006129PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006131 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132 char *p;
6133 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006134 Py_ssize_t expandsize, pos;
6135 int kind;
6136 void *data;
6137 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006139 if (!PyUnicode_Check(unicode)) {
6140 PyErr_BadArgument();
6141 return NULL;
6142 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006143 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006144 return NULL;
6145 kind = PyUnicode_KIND(unicode);
6146 data = PyUnicode_DATA(unicode);
6147 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006148 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6149 bytes, and 1 byte characters 4. */
6150 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006151
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006154
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006155 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006156 if (repr == NULL)
6157 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006158 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006159 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006161 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162 for (pos = 0; pos < len; pos++) {
6163 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006164 /* Map 32-bit characters to '\Uxxxxxxxx' */
6165 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006166 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006167 *p++ = '\\';
6168 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006169 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6170 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6171 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6172 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6173 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6174 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6175 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6176 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006177 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006178 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180 *p++ = '\\';
6181 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006182 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6183 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6184 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6185 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 /* Copy everything else as-is */
6188 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189 *p++ = (char) ch;
6190 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006191
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006192 assert(p > q);
6193 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006194 return NULL;
6195 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196}
6197
Alexander Belopolsky40018472011-02-26 01:02:56 +00006198PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6200 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006202 PyObject *result;
6203 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6204 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006205 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6207 Py_DECREF(tmp);
6208 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209}
6210
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006211/* --- Unicode Internal Codec ------------------------------------------- */
6212
Alexander Belopolsky40018472011-02-26 01:02:56 +00006213PyObject *
6214_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006215 Py_ssize_t size,
6216 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006217{
6218 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006219 Py_ssize_t startinpos;
6220 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006221 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006222 const char *end;
6223 const char *reason;
6224 PyObject *errorHandler = NULL;
6225 PyObject *exc = NULL;
6226
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006227 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006228 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006229 1))
6230 return NULL;
6231
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006232 if (size == 0)
6233 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006234
Victor Stinner8f674cc2013-04-17 23:02:17 +02006235 _PyUnicodeWriter_Init(&writer);
6236 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6237 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006238 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006239 }
6240 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006241
Victor Stinner8f674cc2013-04-17 23:02:17 +02006242 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006243 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006244 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006245 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006246 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006247 endinpos = end-starts;
6248 reason = "truncated input";
6249 goto error;
6250 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006251 /* We copy the raw representation one byte at a time because the
6252 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006253 ((char *) &uch)[0] = s[0];
6254 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006255#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006256 ((char *) &uch)[2] = s[2];
6257 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006258#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006259 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006260#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006261 /* We have to sanity check the raw data, otherwise doom looms for
6262 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006263 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006264 endinpos = s - starts + Py_UNICODE_SIZE;
6265 reason = "illegal code point (> 0x10FFFF)";
6266 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006267 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006268#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006269 s += Py_UNICODE_SIZE;
6270#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006271 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006272 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006273 Py_UNICODE uch2;
6274 ((char *) &uch2)[0] = s[0];
6275 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006276 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006277 {
Victor Stinner551ac952011-11-29 22:58:13 +01006278 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006279 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006280 }
6281 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006282#endif
6283
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006284 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006285 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006286 continue;
6287
6288 error:
6289 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006290 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006291 errors, &errorHandler,
6292 "unicode_internal", reason,
6293 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006294 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 }
6297
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006298 Py_XDECREF(errorHandler);
6299 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006300 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006301
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006303 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006304 Py_XDECREF(errorHandler);
6305 Py_XDECREF(exc);
6306 return NULL;
6307}
6308
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309/* --- Latin-1 Codec ------------------------------------------------------ */
6310
Alexander Belopolsky40018472011-02-26 01:02:56 +00006311PyObject *
6312PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006313 Py_ssize_t size,
6314 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006315{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006317 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006318}
6319
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006321static void
6322make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006323 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006324 PyObject *unicode,
6325 Py_ssize_t startpos, Py_ssize_t endpos,
6326 const char *reason)
6327{
6328 if (*exceptionObject == NULL) {
6329 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006330 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006331 encoding, unicode, startpos, endpos, reason);
6332 }
6333 else {
6334 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6335 goto onError;
6336 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6337 goto onError;
6338 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6339 goto onError;
6340 return;
6341 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006342 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006343 }
6344}
6345
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006346/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006347static void
6348raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006349 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006350 PyObject *unicode,
6351 Py_ssize_t startpos, Py_ssize_t endpos,
6352 const char *reason)
6353{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006354 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006355 encoding, unicode, startpos, endpos, reason);
6356 if (*exceptionObject != NULL)
6357 PyCodec_StrictErrors(*exceptionObject);
6358}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006359
6360/* error handling callback helper:
6361 build arguments, call the callback and check the arguments,
6362 put the result into newpos and return the replacement string, which
6363 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006364static PyObject *
6365unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006366 PyObject **errorHandler,
6367 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006368 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006369 Py_ssize_t startpos, Py_ssize_t endpos,
6370 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006372 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006373 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006374 PyObject *restuple;
6375 PyObject *resunicode;
6376
6377 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006378 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006380 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381 }
6382
Benjamin Petersonbac79492012-01-14 13:34:47 -05006383 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006384 return NULL;
6385 len = PyUnicode_GET_LENGTH(unicode);
6386
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006387 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006388 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391
6392 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006395 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006396 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006397 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006398 Py_DECREF(restuple);
6399 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006400 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006401 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 &resunicode, newpos)) {
6403 Py_DECREF(restuple);
6404 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006406 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6407 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6408 Py_DECREF(restuple);
6409 return NULL;
6410 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006412 *newpos = len + *newpos;
6413 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006414 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 Py_DECREF(restuple);
6416 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006417 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 Py_INCREF(resunicode);
6419 Py_DECREF(restuple);
6420 return resunicode;
6421}
6422
Alexander Belopolsky40018472011-02-26 01:02:56 +00006423static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006424unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006425 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006426 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006428 /* input state */
6429 Py_ssize_t pos=0, size;
6430 int kind;
6431 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 /* output object */
6433 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 /* pointer into the output */
6435 char *str;
6436 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006437 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006438 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6439 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440 PyObject *errorHandler = NULL;
6441 PyObject *exc = NULL;
6442 /* the following variable is used for caching string comparisons
6443 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6444 int known_errorHandler = -1;
6445
Benjamin Petersonbac79492012-01-14 13:34:47 -05006446 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006447 return NULL;
6448 size = PyUnicode_GET_LENGTH(unicode);
6449 kind = PyUnicode_KIND(unicode);
6450 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006451 /* allocate enough for a simple encoding without
6452 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006453 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006454 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006455 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006456 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006457 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006458 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459 ressize = size;
6460
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006461 while (pos < size) {
6462 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 /* can we encode this? */
6465 if (c<limit) {
6466 /* no overflow check, because we know that the space is enough */
6467 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006468 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006469 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 Py_ssize_t requiredsize;
6472 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006473 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006474 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006475 Py_ssize_t collstart = pos;
6476 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006478 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 ++collend;
6480 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6481 if (known_errorHandler==-1) {
6482 if ((errors==NULL) || (!strcmp(errors, "strict")))
6483 known_errorHandler = 1;
6484 else if (!strcmp(errors, "replace"))
6485 known_errorHandler = 2;
6486 else if (!strcmp(errors, "ignore"))
6487 known_errorHandler = 3;
6488 else if (!strcmp(errors, "xmlcharrefreplace"))
6489 known_errorHandler = 4;
6490 else
6491 known_errorHandler = 0;
6492 }
6493 switch (known_errorHandler) {
6494 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006495 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006496 goto onError;
6497 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006498 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 *str++ = '?'; /* fall through */
6500 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 break;
6503 case 4: /* xmlcharrefreplace */
6504 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006505 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006507 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006509 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006511 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006512 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006513 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006515 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006516 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006517 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006519 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006520 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006521 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006522 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006523 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006524 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006525 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006526 if (requiredsize > PY_SSIZE_T_MAX - incr)
6527 goto overflow;
6528 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006530 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6531 goto overflow;
6532 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006534 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 requiredsize = 2*ressize;
6536 if (_PyBytes_Resize(&res, requiredsize))
6537 goto onError;
6538 str = PyBytes_AS_STRING(res) + respos;
6539 ressize = requiredsize;
6540 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 /* generate replacement */
6542 for (i = collstart; i < collend; ++i) {
6543 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 break;
6547 default:
6548 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 encoding, reason, unicode, &exc,
6550 collstart, collend, &newpos);
6551 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006552 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006554 if (PyBytes_Check(repunicode)) {
6555 /* Directly copy bytes result to output. */
6556 repsize = PyBytes_Size(repunicode);
6557 if (repsize > 1) {
6558 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006559 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006560 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6561 Py_DECREF(repunicode);
6562 goto overflow;
6563 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006564 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6565 Py_DECREF(repunicode);
6566 goto onError;
6567 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006568 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006569 ressize += repsize-1;
6570 }
6571 memcpy(str, PyBytes_AsString(repunicode), repsize);
6572 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006573 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006574 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006575 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006576 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006577 /* need more space? (at least enough for what we
6578 have+the replacement+the rest of the string, so
6579 we won't have to check space for encodable characters) */
6580 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006582 requiredsize = respos;
6583 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6584 goto overflow;
6585 requiredsize += repsize;
6586 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6587 goto overflow;
6588 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006590 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 requiredsize = 2*ressize;
6592 if (_PyBytes_Resize(&res, requiredsize)) {
6593 Py_DECREF(repunicode);
6594 goto onError;
6595 }
6596 str = PyBytes_AS_STRING(res) + respos;
6597 ressize = requiredsize;
6598 }
6599 /* check if there is anything unencodable in the replacement
6600 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006601 for (i = 0; repsize-->0; ++i, ++str) {
6602 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006604 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006605 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 Py_DECREF(repunicode);
6607 goto onError;
6608 }
6609 *str = (char)c;
6610 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006612 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006613 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006614 }
6615 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006616 /* Resize if we allocated to much */
6617 size = str - PyBytes_AS_STRING(res);
6618 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006619 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006620 if (_PyBytes_Resize(&res, size) < 0)
6621 goto onError;
6622 }
6623
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006624 Py_XDECREF(errorHandler);
6625 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006626 return res;
6627
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006628 overflow:
6629 PyErr_SetString(PyExc_OverflowError,
6630 "encoded result is too long for a Python string");
6631
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006632 onError:
6633 Py_XDECREF(res);
6634 Py_XDECREF(errorHandler);
6635 Py_XDECREF(exc);
6636 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637}
6638
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006639/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006640PyObject *
6641PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006642 Py_ssize_t size,
6643 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 PyObject *result;
6646 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6647 if (unicode == NULL)
6648 return NULL;
6649 result = unicode_encode_ucs1(unicode, errors, 256);
6650 Py_DECREF(unicode);
6651 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652}
6653
Alexander Belopolsky40018472011-02-26 01:02:56 +00006654PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006655_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006656{
6657 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 PyErr_BadArgument();
6659 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006660 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006661 if (PyUnicode_READY(unicode) == -1)
6662 return NULL;
6663 /* Fast path: if it is a one-byte string, construct
6664 bytes object directly. */
6665 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6666 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6667 PyUnicode_GET_LENGTH(unicode));
6668 /* Non-Latin-1 characters present. Defer to above function to
6669 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006670 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006671}
6672
6673PyObject*
6674PyUnicode_AsLatin1String(PyObject *unicode)
6675{
6676 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006677}
6678
6679/* --- 7-bit ASCII Codec -------------------------------------------------- */
6680
Alexander Belopolsky40018472011-02-26 01:02:56 +00006681PyObject *
6682PyUnicode_DecodeASCII(const char *s,
6683 Py_ssize_t size,
6684 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006685{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006687 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006688 int kind;
6689 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006690 Py_ssize_t startinpos;
6691 Py_ssize_t endinpos;
6692 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 const char *e;
6694 PyObject *errorHandler = NULL;
6695 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006696
Guido van Rossumd57fd912000-03-10 22:53:23 +00006697 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006698 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006699
Guido van Rossumd57fd912000-03-10 22:53:23 +00006700 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006701 if (size == 1 && (unsigned char)s[0] < 128)
6702 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006703
Victor Stinner8f674cc2013-04-17 23:02:17 +02006704 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006705 writer.min_length = size;
6706 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006707 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006708
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006709 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006710 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006711 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006712 writer.pos = outpos;
6713 if (writer.pos == size)
6714 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006715
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006716 s += writer.pos;
6717 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006719 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006721 PyUnicode_WRITE(kind, data, writer.pos, c);
6722 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 ++s;
6724 }
6725 else {
6726 startinpos = s-starts;
6727 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006728 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 errors, &errorHandler,
6730 "ascii", "ordinal not in range(128)",
6731 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006732 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006734 kind = writer.kind;
6735 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006737 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006738 Py_XDECREF(errorHandler);
6739 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006740 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006741
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006743 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 Py_XDECREF(errorHandler);
6745 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006746 return NULL;
6747}
6748
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006749/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006750PyObject *
6751PyUnicode_EncodeASCII(const Py_UNICODE *p,
6752 Py_ssize_t size,
6753 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006754{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755 PyObject *result;
6756 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6757 if (unicode == NULL)
6758 return NULL;
6759 result = unicode_encode_ucs1(unicode, errors, 128);
6760 Py_DECREF(unicode);
6761 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006762}
6763
Alexander Belopolsky40018472011-02-26 01:02:56 +00006764PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006765_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006766{
6767 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 PyErr_BadArgument();
6769 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006771 if (PyUnicode_READY(unicode) == -1)
6772 return NULL;
6773 /* Fast path: if it is an ASCII-only string, construct bytes object
6774 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006775 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006776 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6777 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006778 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006779}
6780
6781PyObject *
6782PyUnicode_AsASCIIString(PyObject *unicode)
6783{
6784 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006785}
6786
Victor Stinner99b95382011-07-04 14:23:54 +02006787#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006788
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006789/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006790
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006791#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006792#define NEED_RETRY
6793#endif
6794
Victor Stinner3a50e702011-10-18 21:21:00 +02006795#ifndef WC_ERR_INVALID_CHARS
6796# define WC_ERR_INVALID_CHARS 0x0080
6797#endif
6798
6799static char*
6800code_page_name(UINT code_page, PyObject **obj)
6801{
6802 *obj = NULL;
6803 if (code_page == CP_ACP)
6804 return "mbcs";
6805 if (code_page == CP_UTF7)
6806 return "CP_UTF7";
6807 if (code_page == CP_UTF8)
6808 return "CP_UTF8";
6809
6810 *obj = PyBytes_FromFormat("cp%u", code_page);
6811 if (*obj == NULL)
6812 return NULL;
6813 return PyBytes_AS_STRING(*obj);
6814}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006815
Victor Stinner3a50e702011-10-18 21:21:00 +02006816static DWORD
6817decode_code_page_flags(UINT code_page)
6818{
6819 if (code_page == CP_UTF7) {
6820 /* The CP_UTF7 decoder only supports flags=0 */
6821 return 0;
6822 }
6823 else
6824 return MB_ERR_INVALID_CHARS;
6825}
6826
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006828 * Decode a byte string from a Windows code page into unicode object in strict
6829 * mode.
6830 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006831 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6832 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006833 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006834static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006835decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006836 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006837 const char *in,
6838 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006839{
Victor Stinner3a50e702011-10-18 21:21:00 +02006840 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006841 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006842 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006843
6844 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006845 assert(insize > 0);
6846 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6847 if (outsize <= 0)
6848 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006849
6850 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006851 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006852 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006853 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 if (*v == NULL)
6855 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006856 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857 }
6858 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006859 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006860 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006861 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006863 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006864 }
6865
6866 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006867 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6868 if (outsize <= 0)
6869 goto error;
6870 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006871
Victor Stinner3a50e702011-10-18 21:21:00 +02006872error:
6873 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6874 return -2;
6875 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006876 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006877}
6878
Victor Stinner3a50e702011-10-18 21:21:00 +02006879/*
6880 * Decode a byte string from a code page into unicode object with an error
6881 * handler.
6882 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006883 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 * UnicodeDecodeError exception and returns -1 on error.
6885 */
6886static int
6887decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006888 PyObject **v,
6889 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006890 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006891{
6892 const char *startin = in;
6893 const char *endin = in + size;
6894 const DWORD flags = decode_code_page_flags(code_page);
6895 /* Ideally, we should get reason from FormatMessage. This is the Windows
6896 2000 English version of the message. */
6897 const char *reason = "No mapping for the Unicode character exists "
6898 "in the target code page.";
6899 /* each step cannot decode more than 1 character, but a character can be
6900 represented as a surrogate pair */
6901 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006902 int insize;
6903 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006904 PyObject *errorHandler = NULL;
6905 PyObject *exc = NULL;
6906 PyObject *encoding_obj = NULL;
6907 char *encoding;
6908 DWORD err;
6909 int ret = -1;
6910
6911 assert(size > 0);
6912
6913 encoding = code_page_name(code_page, &encoding_obj);
6914 if (encoding == NULL)
6915 return -1;
6916
Victor Stinner7d00cc12014-03-17 23:08:06 +01006917 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006918 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6919 UnicodeDecodeError. */
6920 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6921 if (exc != NULL) {
6922 PyCodec_StrictErrors(exc);
6923 Py_CLEAR(exc);
6924 }
6925 goto error;
6926 }
6927
6928 if (*v == NULL) {
6929 /* Create unicode object */
6930 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6931 PyErr_NoMemory();
6932 goto error;
6933 }
Victor Stinnerab595942011-12-17 04:59:06 +01006934 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006935 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006936 if (*v == NULL)
6937 goto error;
6938 startout = PyUnicode_AS_UNICODE(*v);
6939 }
6940 else {
6941 /* Extend unicode object */
6942 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6943 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6944 PyErr_NoMemory();
6945 goto error;
6946 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006947 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006948 goto error;
6949 startout = PyUnicode_AS_UNICODE(*v) + n;
6950 }
6951
6952 /* Decode the byte string character per character */
6953 out = startout;
6954 while (in < endin)
6955 {
6956 /* Decode a character */
6957 insize = 1;
6958 do
6959 {
6960 outsize = MultiByteToWideChar(code_page, flags,
6961 in, insize,
6962 buffer, Py_ARRAY_LENGTH(buffer));
6963 if (outsize > 0)
6964 break;
6965 err = GetLastError();
6966 if (err != ERROR_NO_UNICODE_TRANSLATION
6967 && err != ERROR_INSUFFICIENT_BUFFER)
6968 {
6969 PyErr_SetFromWindowsErr(0);
6970 goto error;
6971 }
6972 insize++;
6973 }
6974 /* 4=maximum length of a UTF-8 sequence */
6975 while (insize <= 4 && (in + insize) <= endin);
6976
6977 if (outsize <= 0) {
6978 Py_ssize_t startinpos, endinpos, outpos;
6979
Victor Stinner7d00cc12014-03-17 23:08:06 +01006980 /* last character in partial decode? */
6981 if (in + insize >= endin && !final)
6982 break;
6983
Victor Stinner3a50e702011-10-18 21:21:00 +02006984 startinpos = in - startin;
6985 endinpos = startinpos + 1;
6986 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006987 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006988 errors, &errorHandler,
6989 encoding, reason,
6990 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006991 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006992 {
6993 goto error;
6994 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006995 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006996 }
6997 else {
6998 in += insize;
6999 memcpy(out, buffer, outsize * sizeof(wchar_t));
7000 out += outsize;
7001 }
7002 }
7003
7004 /* write a NUL character at the end */
7005 *out = 0;
7006
7007 /* Extend unicode object */
7008 outsize = out - startout;
7009 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007010 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007011 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007012 /* (in - startin) <= size and size is an int */
7013 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007014
7015error:
7016 Py_XDECREF(encoding_obj);
7017 Py_XDECREF(errorHandler);
7018 Py_XDECREF(exc);
7019 return ret;
7020}
7021
Victor Stinner3a50e702011-10-18 21:21:00 +02007022static PyObject *
7023decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007024 const char *s, Py_ssize_t size,
7025 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007026{
Victor Stinner76a31a62011-11-04 00:05:13 +01007027 PyObject *v = NULL;
7028 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 if (code_page < 0) {
7031 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7032 return NULL;
7033 }
7034
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007036 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007037
Victor Stinner76a31a62011-11-04 00:05:13 +01007038 do
7039 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007041 if (size > INT_MAX) {
7042 chunk_size = INT_MAX;
7043 final = 0;
7044 done = 0;
7045 }
7046 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007048 {
7049 chunk_size = (int)size;
7050 final = (consumed == NULL);
7051 done = 1;
7052 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053
Victor Stinner76a31a62011-11-04 00:05:13 +01007054 if (chunk_size == 0 && done) {
7055 if (v != NULL)
7056 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007057 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059
Victor Stinner76a31a62011-11-04 00:05:13 +01007060 converted = decode_code_page_strict(code_page, &v,
7061 s, chunk_size);
7062 if (converted == -2)
7063 converted = decode_code_page_errors(code_page, &v,
7064 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007065 errors, final);
7066 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007067
7068 if (converted < 0) {
7069 Py_XDECREF(v);
7070 return NULL;
7071 }
7072
7073 if (consumed)
7074 *consumed += converted;
7075
7076 s += converted;
7077 size -= converted;
7078 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007079
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007080 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081}
7082
Alexander Belopolsky40018472011-02-26 01:02:56 +00007083PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007084PyUnicode_DecodeCodePageStateful(int code_page,
7085 const char *s,
7086 Py_ssize_t size,
7087 const char *errors,
7088 Py_ssize_t *consumed)
7089{
7090 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7091}
7092
7093PyObject *
7094PyUnicode_DecodeMBCSStateful(const char *s,
7095 Py_ssize_t size,
7096 const char *errors,
7097 Py_ssize_t *consumed)
7098{
7099 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7100}
7101
7102PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007103PyUnicode_DecodeMBCS(const char *s,
7104 Py_ssize_t size,
7105 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007106{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007107 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7108}
7109
Victor Stinner3a50e702011-10-18 21:21:00 +02007110static DWORD
7111encode_code_page_flags(UINT code_page, const char *errors)
7112{
7113 if (code_page == CP_UTF8) {
7114 if (winver.dwMajorVersion >= 6)
7115 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7116 and later */
7117 return WC_ERR_INVALID_CHARS;
7118 else
7119 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7120 return 0;
7121 }
7122 else if (code_page == CP_UTF7) {
7123 /* CP_UTF7 only supports flags=0 */
7124 return 0;
7125 }
7126 else {
7127 if (errors != NULL && strcmp(errors, "replace") == 0)
7128 return 0;
7129 else
7130 return WC_NO_BEST_FIT_CHARS;
7131 }
7132}
7133
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007134/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 * Encode a Unicode string to a Windows code page into a byte string in strict
7136 * mode.
7137 *
7138 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007139 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007140 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007141static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007142encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007143 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007144 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007145{
Victor Stinner554f3f02010-06-16 23:33:54 +00007146 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 BOOL *pusedDefaultChar = &usedDefaultChar;
7148 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007149 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007150 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007151 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 const DWORD flags = encode_code_page_flags(code_page, NULL);
7153 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007154 /* Create a substring so that we can get the UTF-16 representation
7155 of just the slice under consideration. */
7156 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007157
Martin v. Löwis3d325192011-11-04 18:23:06 +01007158 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007159
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007161 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007163 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007164
Victor Stinner2fc507f2011-11-04 20:06:39 +01007165 substring = PyUnicode_Substring(unicode, offset, offset+len);
7166 if (substring == NULL)
7167 return -1;
7168 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7169 if (p == NULL) {
7170 Py_DECREF(substring);
7171 return -1;
7172 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007173 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007174
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007175 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007177 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 NULL, 0,
7179 NULL, pusedDefaultChar);
7180 if (outsize <= 0)
7181 goto error;
7182 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 if (pusedDefaultChar && *pusedDefaultChar) {
7184 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007186 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007187
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007189 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007191 if (*outbytes == NULL) {
7192 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007194 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007196 }
7197 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 const Py_ssize_t n = PyBytes_Size(*outbytes);
7200 if (outsize > PY_SSIZE_T_MAX - n) {
7201 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007202 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007203 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007205 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7206 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007208 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007210 }
7211
7212 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007214 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 out, outsize,
7216 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 if (outsize <= 0)
7219 goto error;
7220 if (pusedDefaultChar && *pusedDefaultChar)
7221 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007222 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007223
Victor Stinner3a50e702011-10-18 21:21:00 +02007224error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007225 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007226 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7227 return -2;
7228 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007229 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007230}
7231
Victor Stinner3a50e702011-10-18 21:21:00 +02007232/*
7233 * Encode a Unicode string to a Windows code page into a byte string using a
7234 * error handler.
7235 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007236 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 * -1 on other error.
7238 */
7239static int
7240encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007241 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007242 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007243{
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007245 Py_ssize_t pos = unicode_offset;
7246 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 /* Ideally, we should get reason from FormatMessage. This is the Windows
7248 2000 English version of the message. */
7249 const char *reason = "invalid character";
7250 /* 4=maximum length of a UTF-8 sequence */
7251 char buffer[4];
7252 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7253 Py_ssize_t outsize;
7254 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 PyObject *errorHandler = NULL;
7256 PyObject *exc = NULL;
7257 PyObject *encoding_obj = NULL;
7258 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007259 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 PyObject *rep;
7261 int ret = -1;
7262
7263 assert(insize > 0);
7264
7265 encoding = code_page_name(code_page, &encoding_obj);
7266 if (encoding == NULL)
7267 return -1;
7268
7269 if (errors == NULL || strcmp(errors, "strict") == 0) {
7270 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7271 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007272 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 if (exc != NULL) {
7274 PyCodec_StrictErrors(exc);
7275 Py_DECREF(exc);
7276 }
7277 Py_XDECREF(encoding_obj);
7278 return -1;
7279 }
7280
7281 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7282 pusedDefaultChar = &usedDefaultChar;
7283 else
7284 pusedDefaultChar = NULL;
7285
7286 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7287 PyErr_NoMemory();
7288 goto error;
7289 }
7290 outsize = insize * Py_ARRAY_LENGTH(buffer);
7291
7292 if (*outbytes == NULL) {
7293 /* Create string object */
7294 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7295 if (*outbytes == NULL)
7296 goto error;
7297 out = PyBytes_AS_STRING(*outbytes);
7298 }
7299 else {
7300 /* Extend string object */
7301 Py_ssize_t n = PyBytes_Size(*outbytes);
7302 if (n > PY_SSIZE_T_MAX - outsize) {
7303 PyErr_NoMemory();
7304 goto error;
7305 }
7306 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7307 goto error;
7308 out = PyBytes_AS_STRING(*outbytes) + n;
7309 }
7310
7311 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007312 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007313 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007314 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7315 wchar_t chars[2];
7316 int charsize;
7317 if (ch < 0x10000) {
7318 chars[0] = (wchar_t)ch;
7319 charsize = 1;
7320 }
7321 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007322 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7323 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007324 charsize = 2;
7325 }
7326
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007328 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 buffer, Py_ARRAY_LENGTH(buffer),
7330 NULL, pusedDefaultChar);
7331 if (outsize > 0) {
7332 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7333 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007334 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007335 memcpy(out, buffer, outsize);
7336 out += outsize;
7337 continue;
7338 }
7339 }
7340 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7341 PyErr_SetFromWindowsErr(0);
7342 goto error;
7343 }
7344
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 rep = unicode_encode_call_errorhandler(
7346 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007347 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007348 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007349 if (rep == NULL)
7350 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007352
7353 if (PyBytes_Check(rep)) {
7354 outsize = PyBytes_GET_SIZE(rep);
7355 if (outsize != 1) {
7356 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7357 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7358 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7359 Py_DECREF(rep);
7360 goto error;
7361 }
7362 out = PyBytes_AS_STRING(*outbytes) + offset;
7363 }
7364 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7365 out += outsize;
7366 }
7367 else {
7368 Py_ssize_t i;
7369 enum PyUnicode_Kind kind;
7370 void *data;
7371
Benjamin Petersonbac79492012-01-14 13:34:47 -05007372 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 Py_DECREF(rep);
7374 goto error;
7375 }
7376
7377 outsize = PyUnicode_GET_LENGTH(rep);
7378 if (outsize != 1) {
7379 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7380 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7381 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7382 Py_DECREF(rep);
7383 goto error;
7384 }
7385 out = PyBytes_AS_STRING(*outbytes) + offset;
7386 }
7387 kind = PyUnicode_KIND(rep);
7388 data = PyUnicode_DATA(rep);
7389 for (i=0; i < outsize; i++) {
7390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7391 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007392 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007393 encoding, unicode,
7394 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 "unable to encode error handler result to ASCII");
7396 Py_DECREF(rep);
7397 goto error;
7398 }
7399 *out = (unsigned char)ch;
7400 out++;
7401 }
7402 }
7403 Py_DECREF(rep);
7404 }
7405 /* write a NUL byte */
7406 *out = 0;
7407 outsize = out - PyBytes_AS_STRING(*outbytes);
7408 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7409 if (_PyBytes_Resize(outbytes, outsize) < 0)
7410 goto error;
7411 ret = 0;
7412
7413error:
7414 Py_XDECREF(encoding_obj);
7415 Py_XDECREF(errorHandler);
7416 Py_XDECREF(exc);
7417 return ret;
7418}
7419
Victor Stinner3a50e702011-10-18 21:21:00 +02007420static PyObject *
7421encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007422 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 const char *errors)
7424{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007425 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007427 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007428 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007429
Benjamin Petersonbac79492012-01-14 13:34:47 -05007430 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007431 return NULL;
7432 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007433
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 if (code_page < 0) {
7435 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7436 return NULL;
7437 }
7438
Martin v. Löwis3d325192011-11-04 18:23:06 +01007439 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007440 return PyBytes_FromStringAndSize(NULL, 0);
7441
Victor Stinner7581cef2011-11-03 22:32:33 +01007442 offset = 0;
7443 do
7444 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007446 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007447 chunks. */
7448 if (len > INT_MAX/2) {
7449 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007450 done = 0;
7451 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007452 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007453#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007454 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007455 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007456 done = 1;
7457 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458
Victor Stinner76a31a62011-11-04 00:05:13 +01007459 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007460 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007461 errors);
7462 if (ret == -2)
7463 ret = encode_code_page_errors(code_page, &outbytes,
7464 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007465 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007466 if (ret < 0) {
7467 Py_XDECREF(outbytes);
7468 return NULL;
7469 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007470
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007473 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007474
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 return outbytes;
7476}
7477
7478PyObject *
7479PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7480 Py_ssize_t size,
7481 const char *errors)
7482{
Victor Stinner7581cef2011-11-03 22:32:33 +01007483 PyObject *unicode, *res;
7484 unicode = PyUnicode_FromUnicode(p, size);
7485 if (unicode == NULL)
7486 return NULL;
7487 res = encode_code_page(CP_ACP, unicode, errors);
7488 Py_DECREF(unicode);
7489 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007490}
7491
7492PyObject *
7493PyUnicode_EncodeCodePage(int code_page,
7494 PyObject *unicode,
7495 const char *errors)
7496{
Victor Stinner7581cef2011-11-03 22:32:33 +01007497 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007498}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007499
Alexander Belopolsky40018472011-02-26 01:02:56 +00007500PyObject *
7501PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007502{
7503 if (!PyUnicode_Check(unicode)) {
7504 PyErr_BadArgument();
7505 return NULL;
7506 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007507 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007508}
7509
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510#undef NEED_RETRY
7511
Victor Stinner99b95382011-07-04 14:23:54 +02007512#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007513
Guido van Rossumd57fd912000-03-10 22:53:23 +00007514/* --- Character Mapping Codec -------------------------------------------- */
7515
Victor Stinnerfb161b12013-04-18 01:44:27 +02007516static int
7517charmap_decode_string(const char *s,
7518 Py_ssize_t size,
7519 PyObject *mapping,
7520 const char *errors,
7521 _PyUnicodeWriter *writer)
7522{
7523 const char *starts = s;
7524 const char *e;
7525 Py_ssize_t startinpos, endinpos;
7526 PyObject *errorHandler = NULL, *exc = NULL;
7527 Py_ssize_t maplen;
7528 enum PyUnicode_Kind mapkind;
7529 void *mapdata;
7530 Py_UCS4 x;
7531 unsigned char ch;
7532
7533 if (PyUnicode_READY(mapping) == -1)
7534 return -1;
7535
7536 maplen = PyUnicode_GET_LENGTH(mapping);
7537 mapdata = PyUnicode_DATA(mapping);
7538 mapkind = PyUnicode_KIND(mapping);
7539
7540 e = s + size;
7541
7542 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7543 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7544 * is disabled in encoding aliases, latin1 is preferred because
7545 * its implementation is faster. */
7546 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7547 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7548 Py_UCS4 maxchar = writer->maxchar;
7549
7550 assert (writer->kind == PyUnicode_1BYTE_KIND);
7551 while (s < e) {
7552 ch = *s;
7553 x = mapdata_ucs1[ch];
7554 if (x > maxchar) {
7555 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7556 goto onError;
7557 maxchar = writer->maxchar;
7558 outdata = (Py_UCS1 *)writer->data;
7559 }
7560 outdata[writer->pos] = x;
7561 writer->pos++;
7562 ++s;
7563 }
7564 return 0;
7565 }
7566
7567 while (s < e) {
7568 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7569 enum PyUnicode_Kind outkind = writer->kind;
7570 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7571 if (outkind == PyUnicode_1BYTE_KIND) {
7572 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7573 Py_UCS4 maxchar = writer->maxchar;
7574 while (s < e) {
7575 ch = *s;
7576 x = mapdata_ucs2[ch];
7577 if (x > maxchar)
7578 goto Error;
7579 outdata[writer->pos] = x;
7580 writer->pos++;
7581 ++s;
7582 }
7583 break;
7584 }
7585 else if (outkind == PyUnicode_2BYTE_KIND) {
7586 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7587 while (s < e) {
7588 ch = *s;
7589 x = mapdata_ucs2[ch];
7590 if (x == 0xFFFE)
7591 goto Error;
7592 outdata[writer->pos] = x;
7593 writer->pos++;
7594 ++s;
7595 }
7596 break;
7597 }
7598 }
7599 ch = *s;
7600
7601 if (ch < maplen)
7602 x = PyUnicode_READ(mapkind, mapdata, ch);
7603 else
7604 x = 0xfffe; /* invalid value */
7605Error:
7606 if (x == 0xfffe)
7607 {
7608 /* undefined mapping */
7609 startinpos = s-starts;
7610 endinpos = startinpos+1;
7611 if (unicode_decode_call_errorhandler_writer(
7612 errors, &errorHandler,
7613 "charmap", "character maps to <undefined>",
7614 &starts, &e, &startinpos, &endinpos, &exc, &s,
7615 writer)) {
7616 goto onError;
7617 }
7618 continue;
7619 }
7620
7621 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7622 goto onError;
7623 ++s;
7624 }
7625 Py_XDECREF(errorHandler);
7626 Py_XDECREF(exc);
7627 return 0;
7628
7629onError:
7630 Py_XDECREF(errorHandler);
7631 Py_XDECREF(exc);
7632 return -1;
7633}
7634
7635static int
7636charmap_decode_mapping(const char *s,
7637 Py_ssize_t size,
7638 PyObject *mapping,
7639 const char *errors,
7640 _PyUnicodeWriter *writer)
7641{
7642 const char *starts = s;
7643 const char *e;
7644 Py_ssize_t startinpos, endinpos;
7645 PyObject *errorHandler = NULL, *exc = NULL;
7646 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007647 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007648
7649 e = s + size;
7650
7651 while (s < e) {
7652 ch = *s;
7653
7654 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7655 key = PyLong_FromLong((long)ch);
7656 if (key == NULL)
7657 goto onError;
7658
7659 item = PyObject_GetItem(mapping, key);
7660 Py_DECREF(key);
7661 if (item == NULL) {
7662 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7663 /* No mapping found means: mapping is undefined. */
7664 PyErr_Clear();
7665 goto Undefined;
7666 } else
7667 goto onError;
7668 }
7669
7670 /* Apply mapping */
7671 if (item == Py_None)
7672 goto Undefined;
7673 if (PyLong_Check(item)) {
7674 long value = PyLong_AS_LONG(item);
7675 if (value == 0xFFFE)
7676 goto Undefined;
7677 if (value < 0 || value > MAX_UNICODE) {
7678 PyErr_Format(PyExc_TypeError,
7679 "character mapping must be in range(0x%lx)",
7680 (unsigned long)MAX_UNICODE + 1);
7681 goto onError;
7682 }
7683
7684 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7685 goto onError;
7686 }
7687 else if (PyUnicode_Check(item)) {
7688 if (PyUnicode_READY(item) == -1)
7689 goto onError;
7690 if (PyUnicode_GET_LENGTH(item) == 1) {
7691 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7692 if (value == 0xFFFE)
7693 goto Undefined;
7694 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7695 goto onError;
7696 }
7697 else {
7698 writer->overallocate = 1;
7699 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7700 goto onError;
7701 }
7702 }
7703 else {
7704 /* wrong return value */
7705 PyErr_SetString(PyExc_TypeError,
7706 "character mapping must return integer, None or str");
7707 goto onError;
7708 }
7709 Py_CLEAR(item);
7710 ++s;
7711 continue;
7712
7713Undefined:
7714 /* undefined mapping */
7715 Py_CLEAR(item);
7716 startinpos = s-starts;
7717 endinpos = startinpos+1;
7718 if (unicode_decode_call_errorhandler_writer(
7719 errors, &errorHandler,
7720 "charmap", "character maps to <undefined>",
7721 &starts, &e, &startinpos, &endinpos, &exc, &s,
7722 writer)) {
7723 goto onError;
7724 }
7725 }
7726 Py_XDECREF(errorHandler);
7727 Py_XDECREF(exc);
7728 return 0;
7729
7730onError:
7731 Py_XDECREF(item);
7732 Py_XDECREF(errorHandler);
7733 Py_XDECREF(exc);
7734 return -1;
7735}
7736
Alexander Belopolsky40018472011-02-26 01:02:56 +00007737PyObject *
7738PyUnicode_DecodeCharmap(const char *s,
7739 Py_ssize_t size,
7740 PyObject *mapping,
7741 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007743 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007744
Guido van Rossumd57fd912000-03-10 22:53:23 +00007745 /* Default to Latin-1 */
7746 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007747 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007748
Guido van Rossumd57fd912000-03-10 22:53:23 +00007749 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007750 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007751 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007752 writer.min_length = size;
7753 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007754 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007755
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007756 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007757 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7758 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007759 }
7760 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007761 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7762 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007763 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007764 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007765
Benjamin Peterson29060642009-01-31 22:14:21 +00007766 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007767 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007768 return NULL;
7769}
7770
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007771/* Charmap encoding: the lookup table */
7772
Alexander Belopolsky40018472011-02-26 01:02:56 +00007773struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007774 PyObject_HEAD
7775 unsigned char level1[32];
7776 int count2, count3;
7777 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007778};
7779
7780static PyObject*
7781encoding_map_size(PyObject *obj, PyObject* args)
7782{
7783 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007784 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007785 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007786}
7787
7788static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007789 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 PyDoc_STR("Return the size (in bytes) of this object") },
7791 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007792};
7793
7794static void
7795encoding_map_dealloc(PyObject* o)
7796{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007797 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007798}
7799
7800static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007801 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007802 "EncodingMap", /*tp_name*/
7803 sizeof(struct encoding_map), /*tp_basicsize*/
7804 0, /*tp_itemsize*/
7805 /* methods */
7806 encoding_map_dealloc, /*tp_dealloc*/
7807 0, /*tp_print*/
7808 0, /*tp_getattr*/
7809 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007810 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 0, /*tp_repr*/
7812 0, /*tp_as_number*/
7813 0, /*tp_as_sequence*/
7814 0, /*tp_as_mapping*/
7815 0, /*tp_hash*/
7816 0, /*tp_call*/
7817 0, /*tp_str*/
7818 0, /*tp_getattro*/
7819 0, /*tp_setattro*/
7820 0, /*tp_as_buffer*/
7821 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7822 0, /*tp_doc*/
7823 0, /*tp_traverse*/
7824 0, /*tp_clear*/
7825 0, /*tp_richcompare*/
7826 0, /*tp_weaklistoffset*/
7827 0, /*tp_iter*/
7828 0, /*tp_iternext*/
7829 encoding_map_methods, /*tp_methods*/
7830 0, /*tp_members*/
7831 0, /*tp_getset*/
7832 0, /*tp_base*/
7833 0, /*tp_dict*/
7834 0, /*tp_descr_get*/
7835 0, /*tp_descr_set*/
7836 0, /*tp_dictoffset*/
7837 0, /*tp_init*/
7838 0, /*tp_alloc*/
7839 0, /*tp_new*/
7840 0, /*tp_free*/
7841 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007842};
7843
7844PyObject*
7845PyUnicode_BuildEncodingMap(PyObject* string)
7846{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007847 PyObject *result;
7848 struct encoding_map *mresult;
7849 int i;
7850 int need_dict = 0;
7851 unsigned char level1[32];
7852 unsigned char level2[512];
7853 unsigned char *mlevel1, *mlevel2, *mlevel3;
7854 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007855 int kind;
7856 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007857 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007858 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007859
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007860 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007861 PyErr_BadArgument();
7862 return NULL;
7863 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007864 kind = PyUnicode_KIND(string);
7865 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007866 length = PyUnicode_GET_LENGTH(string);
7867 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868 memset(level1, 0xFF, sizeof level1);
7869 memset(level2, 0xFF, sizeof level2);
7870
7871 /* If there isn't a one-to-one mapping of NULL to \0,
7872 or if there are non-BMP characters, we need to use
7873 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007874 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007876 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007877 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007878 ch = PyUnicode_READ(kind, data, i);
7879 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007880 need_dict = 1;
7881 break;
7882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007883 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884 /* unmapped character */
7885 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 l1 = ch >> 11;
7887 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888 if (level1[l1] == 0xFF)
7889 level1[l1] = count2++;
7890 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007891 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 }
7893
7894 if (count2 >= 0xFF || count3 >= 0xFF)
7895 need_dict = 1;
7896
7897 if (need_dict) {
7898 PyObject *result = PyDict_New();
7899 PyObject *key, *value;
7900 if (!result)
7901 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007902 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007903 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007904 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 if (!key || !value)
7906 goto failed1;
7907 if (PyDict_SetItem(result, key, value) == -1)
7908 goto failed1;
7909 Py_DECREF(key);
7910 Py_DECREF(value);
7911 }
7912 return result;
7913 failed1:
7914 Py_XDECREF(key);
7915 Py_XDECREF(value);
7916 Py_DECREF(result);
7917 return NULL;
7918 }
7919
7920 /* Create a three-level trie */
7921 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7922 16*count2 + 128*count3 - 1);
7923 if (!result)
7924 return PyErr_NoMemory();
7925 PyObject_Init(result, &EncodingMapType);
7926 mresult = (struct encoding_map*)result;
7927 mresult->count2 = count2;
7928 mresult->count3 = count3;
7929 mlevel1 = mresult->level1;
7930 mlevel2 = mresult->level23;
7931 mlevel3 = mresult->level23 + 16*count2;
7932 memcpy(mlevel1, level1, 32);
7933 memset(mlevel2, 0xFF, 16*count2);
7934 memset(mlevel3, 0, 128*count3);
7935 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007936 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007938 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7939 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007940 /* unmapped character */
7941 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007942 o1 = ch>>11;
7943 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944 i2 = 16*mlevel1[o1] + o2;
7945 if (mlevel2[i2] == 0xFF)
7946 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007947 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007948 i3 = 128*mlevel2[i2] + o3;
7949 mlevel3[i3] = i;
7950 }
7951 return result;
7952}
7953
7954static int
Victor Stinner22168992011-11-20 17:09:18 +01007955encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007956{
7957 struct encoding_map *map = (struct encoding_map*)mapping;
7958 int l1 = c>>11;
7959 int l2 = (c>>7) & 0xF;
7960 int l3 = c & 0x7F;
7961 int i;
7962
Victor Stinner22168992011-11-20 17:09:18 +01007963 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007964 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 if (c == 0)
7966 return 0;
7967 /* level 1*/
7968 i = map->level1[l1];
7969 if (i == 0xFF) {
7970 return -1;
7971 }
7972 /* level 2*/
7973 i = map->level23[16*i+l2];
7974 if (i == 0xFF) {
7975 return -1;
7976 }
7977 /* level 3 */
7978 i = map->level23[16*map->count2 + 128*i + l3];
7979 if (i == 0) {
7980 return -1;
7981 }
7982 return i;
7983}
7984
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985/* Lookup the character ch in the mapping. If the character
7986 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007987 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007988static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007989charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990{
Christian Heimes217cfd12007-12-02 14:31:20 +00007991 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007992 PyObject *x;
7993
7994 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007996 x = PyObject_GetItem(mapping, w);
7997 Py_DECREF(w);
7998 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8000 /* No mapping found means: mapping is undefined. */
8001 PyErr_Clear();
8002 x = Py_None;
8003 Py_INCREF(x);
8004 return x;
8005 } else
8006 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008008 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008009 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008010 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 long value = PyLong_AS_LONG(x);
8012 if (value < 0 || value > 255) {
8013 PyErr_SetString(PyExc_TypeError,
8014 "character mapping must be in range(256)");
8015 Py_DECREF(x);
8016 return NULL;
8017 }
8018 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008020 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 /* wrong return value */
8024 PyErr_Format(PyExc_TypeError,
8025 "character mapping must return integer, bytes or None, not %.400s",
8026 x->ob_type->tp_name);
8027 Py_DECREF(x);
8028 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008029 }
8030}
8031
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008033charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008035 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8036 /* exponentially overallocate to minimize reallocations */
8037 if (requiredsize < 2*outsize)
8038 requiredsize = 2*outsize;
8039 if (_PyBytes_Resize(outobj, requiredsize))
8040 return -1;
8041 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042}
8043
Benjamin Peterson14339b62009-01-31 16:36:08 +00008044typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008045 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008046} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008047/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008048 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049 space is available. Return a new reference to the object that
8050 was put in the output buffer, or Py_None, if the mapping was undefined
8051 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008052 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008053static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008054charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008055 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008056{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008057 PyObject *rep;
8058 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008059 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008060
Christian Heimes90aa7642007-12-19 02:45:37 +00008061 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008064 if (res == -1)
8065 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 if (outsize<requiredsize)
8067 if (charmapencode_resize(outobj, outpos, requiredsize))
8068 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008069 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008070 outstart[(*outpos)++] = (char)res;
8071 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008072 }
8073
8074 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008077 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008078 Py_DECREF(rep);
8079 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008080 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 if (PyLong_Check(rep)) {
8082 Py_ssize_t requiredsize = *outpos+1;
8083 if (outsize<requiredsize)
8084 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8085 Py_DECREF(rep);
8086 return enc_EXCEPTION;
8087 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008088 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008090 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 else {
8092 const char *repchars = PyBytes_AS_STRING(rep);
8093 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8094 Py_ssize_t requiredsize = *outpos+repsize;
8095 if (outsize<requiredsize)
8096 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8097 Py_DECREF(rep);
8098 return enc_EXCEPTION;
8099 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008100 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 memcpy(outstart + *outpos, repchars, repsize);
8102 *outpos += repsize;
8103 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008104 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008105 Py_DECREF(rep);
8106 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107}
8108
8109/* handle an error in PyUnicode_EncodeCharmap
8110 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008111static int
8112charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008113 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008114 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008115 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008116 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117{
8118 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008120 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008121 enum PyUnicode_Kind kind;
8122 void *data;
8123 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008124 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008125 Py_ssize_t collstartpos = *inpos;
8126 Py_ssize_t collendpos = *inpos+1;
8127 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008128 char *encoding = "charmap";
8129 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008131 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008132 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133
Benjamin Petersonbac79492012-01-14 13:34:47 -05008134 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008135 return -1;
8136 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008137 /* find all unencodable characters */
8138 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008139 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008140 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008141 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008142 val = encoding_map_lookup(ch, mapping);
8143 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 break;
8145 ++collendpos;
8146 continue;
8147 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008148
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008149 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8150 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 if (rep==NULL)
8152 return -1;
8153 else if (rep!=Py_None) {
8154 Py_DECREF(rep);
8155 break;
8156 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008157 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008158 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008159 }
8160 /* cache callback name lookup
8161 * (if not done yet, i.e. it's the first error) */
8162 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 if ((errors==NULL) || (!strcmp(errors, "strict")))
8164 *known_errorHandler = 1;
8165 else if (!strcmp(errors, "replace"))
8166 *known_errorHandler = 2;
8167 else if (!strcmp(errors, "ignore"))
8168 *known_errorHandler = 3;
8169 else if (!strcmp(errors, "xmlcharrefreplace"))
8170 *known_errorHandler = 4;
8171 else
8172 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008173 }
8174 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008175 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008176 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 return -1;
8178 case 2: /* replace */
8179 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 x = charmapencode_output('?', mapping, res, respos);
8181 if (x==enc_EXCEPTION) {
8182 return -1;
8183 }
8184 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008185 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 return -1;
8187 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008188 }
8189 /* fall through */
8190 case 3: /* ignore */
8191 *inpos = collendpos;
8192 break;
8193 case 4: /* xmlcharrefreplace */
8194 /* generate replacement (temporarily (mis)uses p) */
8195 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 char buffer[2+29+1+1];
8197 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008199 for (cp = buffer; *cp; ++cp) {
8200 x = charmapencode_output(*cp, mapping, res, respos);
8201 if (x==enc_EXCEPTION)
8202 return -1;
8203 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008204 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 return -1;
8206 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008207 }
8208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008209 *inpos = collendpos;
8210 break;
8211 default:
8212 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008213 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008215 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008217 if (PyBytes_Check(repunicode)) {
8218 /* Directly copy bytes result to output. */
8219 Py_ssize_t outsize = PyBytes_Size(*res);
8220 Py_ssize_t requiredsize;
8221 repsize = PyBytes_Size(repunicode);
8222 requiredsize = *respos + repsize;
8223 if (requiredsize > outsize)
8224 /* Make room for all additional bytes. */
8225 if (charmapencode_resize(res, respos, requiredsize)) {
8226 Py_DECREF(repunicode);
8227 return -1;
8228 }
8229 memcpy(PyBytes_AsString(*res) + *respos,
8230 PyBytes_AsString(repunicode), repsize);
8231 *respos += repsize;
8232 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008233 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008234 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008235 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008236 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008237 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008238 Py_DECREF(repunicode);
8239 return -1;
8240 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008241 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008242 data = PyUnicode_DATA(repunicode);
8243 kind = PyUnicode_KIND(repunicode);
8244 for (index = 0; index < repsize; index++) {
8245 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8246 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008248 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 return -1;
8250 }
8251 else if (x==enc_FAILED) {
8252 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008253 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 return -1;
8255 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008256 }
8257 *inpos = newpos;
8258 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259 }
8260 return 0;
8261}
8262
Alexander Belopolsky40018472011-02-26 01:02:56 +00008263PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008264_PyUnicode_EncodeCharmap(PyObject *unicode,
8265 PyObject *mapping,
8266 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 /* output object */
8269 PyObject *res = NULL;
8270 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008271 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008272 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008273 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008274 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275 PyObject *errorHandler = NULL;
8276 PyObject *exc = NULL;
8277 /* the following variable is used for caching string comparisons
8278 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8279 * 3=ignore, 4=xmlcharrefreplace */
8280 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008281 void *data;
8282 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008283
Benjamin Petersonbac79492012-01-14 13:34:47 -05008284 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285 return NULL;
8286 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008287 data = PyUnicode_DATA(unicode);
8288 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008289
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290 /* Default to Latin-1 */
8291 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008292 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008293
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294 /* allocate enough for a simple encoding without
8295 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008296 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008297 if (res == NULL)
8298 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008299 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008303 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 if (x==enc_EXCEPTION) /* error */
8307 goto onError;
8308 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008309 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 &exc,
8311 &known_errorHandler, &errorHandler, errors,
8312 &res, &respos)) {
8313 goto onError;
8314 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008315 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 else
8317 /* done with this character => adjust input position */
8318 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008320
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008322 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008323 if (_PyBytes_Resize(&res, respos) < 0)
8324 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008325
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326 Py_XDECREF(exc);
8327 Py_XDECREF(errorHandler);
8328 return res;
8329
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 Py_XDECREF(res);
8332 Py_XDECREF(exc);
8333 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334 return NULL;
8335}
8336
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008337/* Deprecated */
8338PyObject *
8339PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8340 Py_ssize_t size,
8341 PyObject *mapping,
8342 const char *errors)
8343{
8344 PyObject *result;
8345 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8346 if (unicode == NULL)
8347 return NULL;
8348 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8349 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008350 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008351}
8352
Alexander Belopolsky40018472011-02-26 01:02:56 +00008353PyObject *
8354PyUnicode_AsCharmapString(PyObject *unicode,
8355 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008356{
8357 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 PyErr_BadArgument();
8359 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008360 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008362}
8363
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008365static void
8366make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008367 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008368 Py_ssize_t startpos, Py_ssize_t endpos,
8369 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008370{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008372 *exceptionObject = _PyUnicodeTranslateError_Create(
8373 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008374 }
8375 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8377 goto onError;
8378 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8379 goto onError;
8380 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8381 goto onError;
8382 return;
8383 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008384 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008385 }
8386}
8387
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388/* error handling callback helper:
8389 build arguments, call the callback and check the arguments,
8390 put the result into newpos and return the replacement string, which
8391 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008392static PyObject *
8393unicode_translate_call_errorhandler(const char *errors,
8394 PyObject **errorHandler,
8395 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008396 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008397 Py_ssize_t startpos, Py_ssize_t endpos,
8398 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008400 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008402 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 PyObject *restuple;
8404 PyObject *resunicode;
8405
8406 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 }
8411
8412 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008413 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416
8417 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008422 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 Py_DECREF(restuple);
8424 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 }
8426 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 &resunicode, &i_newpos)) {
8428 Py_DECREF(restuple);
8429 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008431 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008433 else
8434 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008436 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 Py_DECREF(restuple);
8438 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008439 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 Py_INCREF(resunicode);
8441 Py_DECREF(restuple);
8442 return resunicode;
8443}
8444
8445/* Lookup the character ch in the mapping and put the result in result,
8446 which must be decrefed by the caller.
8447 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008448static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450{
Christian Heimes217cfd12007-12-02 14:31:20 +00008451 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 PyObject *x;
8453
8454 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456 x = PyObject_GetItem(mapping, w);
8457 Py_DECREF(w);
8458 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8460 /* No mapping found means: use 1:1 mapping. */
8461 PyErr_Clear();
8462 *result = NULL;
8463 return 0;
8464 } else
8465 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 }
8467 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 *result = x;
8469 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008471 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008473 if (value < 0 || value > MAX_UNICODE) {
8474 PyErr_Format(PyExc_ValueError,
8475 "character mapping must be in range(0x%x)",
8476 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 Py_DECREF(x);
8478 return -1;
8479 }
8480 *result = x;
8481 return 0;
8482 }
8483 else if (PyUnicode_Check(x)) {
8484 *result = x;
8485 return 0;
8486 }
8487 else {
8488 /* wrong return value */
8489 PyErr_SetString(PyExc_TypeError,
8490 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008491 Py_DECREF(x);
8492 return -1;
8493 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494}
Victor Stinner1194ea02014-04-04 19:37:40 +02008495
8496/* lookup the character, write the result into the writer.
8497 Return 1 if the result was written into the writer, return 0 if the mapping
8498 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008499static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008500charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8501 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502{
Victor Stinner1194ea02014-04-04 19:37:40 +02008503 PyObject *item;
8504
8505 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008507
8508 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008510 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008513 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008515
8516 if (item == Py_None) {
8517 Py_DECREF(item);
8518 return 0;
8519 }
8520
8521 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008522 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8523 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8524 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008525 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8526 Py_DECREF(item);
8527 return -1;
8528 }
8529 Py_DECREF(item);
8530 return 1;
8531 }
8532
8533 if (!PyUnicode_Check(item)) {
8534 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008536 }
8537
8538 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8539 Py_DECREF(item);
8540 return -1;
8541 }
8542
8543 Py_DECREF(item);
8544 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008545}
8546
Victor Stinner89a76ab2014-04-05 11:44:04 +02008547static int
8548unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8549 Py_UCS1 *translate)
8550{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008551 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008552 int ret = 0;
8553
Victor Stinner89a76ab2014-04-05 11:44:04 +02008554 if (charmaptranslate_lookup(ch, mapping, &item)) {
8555 return -1;
8556 }
8557
8558 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008559 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008560 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008561 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008562 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008563 /* not found => default to 1:1 mapping */
8564 translate[ch] = ch;
8565 return 1;
8566 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008567 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008568 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008569 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8570 used it */
8571 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008572 /* invalid character or character outside ASCII:
8573 skip the fast translate */
8574 goto exit;
8575 }
8576 translate[ch] = (Py_UCS1)replace;
8577 }
8578 else if (PyUnicode_Check(item)) {
8579 Py_UCS4 replace;
8580
8581 if (PyUnicode_READY(item) == -1) {
8582 Py_DECREF(item);
8583 return -1;
8584 }
8585 if (PyUnicode_GET_LENGTH(item) != 1)
8586 goto exit;
8587
8588 replace = PyUnicode_READ_CHAR(item, 0);
8589 if (replace > 127)
8590 goto exit;
8591 translate[ch] = (Py_UCS1)replace;
8592 }
8593 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008594 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008595 goto exit;
8596 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008597 ret = 1;
8598
Benjamin Peterson1365de72014-04-07 20:15:41 -04008599 exit:
8600 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008601 return ret;
8602}
8603
8604/* Fast path for ascii => ascii translation. Return 1 if the whole string
8605 was translated into writer, return 0 if the input string was partially
8606 translated into writer, raise an exception and return -1 on error. */
8607static int
8608unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008609 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008610{
Victor Stinner872b2912014-04-05 14:27:07 +02008611 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008612 Py_ssize_t len;
8613 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008614 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008615
8616 if (PyUnicode_READY(input) == -1)
8617 return -1;
8618 if (!PyUnicode_IS_ASCII(input))
8619 return 0;
8620 len = PyUnicode_GET_LENGTH(input);
8621
Victor Stinner872b2912014-04-05 14:27:07 +02008622 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008623
8624 in = PyUnicode_1BYTE_DATA(input);
8625 end = in + len;
8626
8627 assert(PyUnicode_IS_ASCII(writer->buffer));
8628 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8629 out = PyUnicode_1BYTE_DATA(writer->buffer);
8630
Victor Stinner872b2912014-04-05 14:27:07 +02008631 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008632 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008633 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008634 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008635 int translate = unicode_fast_translate_lookup(mapping, ch,
8636 ascii_table);
8637 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008638 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008639 if (translate == 0)
8640 goto exit;
8641 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008642 }
Victor Stinner872b2912014-04-05 14:27:07 +02008643 if (ch2 == 0xfe) {
8644 if (ignore)
8645 continue;
8646 goto exit;
8647 }
8648 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008649 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008650 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008651 }
Victor Stinner872b2912014-04-05 14:27:07 +02008652 res = 1;
8653
8654exit:
8655 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8656 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008657}
8658
Alexander Belopolsky40018472011-02-26 01:02:56 +00008659PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660_PyUnicode_TranslateCharmap(PyObject *input,
8661 PyObject *mapping,
8662 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008663{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008665 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 Py_ssize_t size, i;
8667 int kind;
8668 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008669 _PyUnicodeWriter writer;
8670 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671 char *reason = "character maps to <undefined>";
8672 PyObject *errorHandler = NULL;
8673 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008674 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008675 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 PyErr_BadArgument();
8679 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 if (PyUnicode_READY(input) == -1)
8683 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008684 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008685 kind = PyUnicode_KIND(input);
8686 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687
8688 if (size == 0) {
8689 Py_INCREF(input);
8690 return input;
8691 }
8692
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008693 /* allocate enough for a simple 1:1 translation without
8694 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008695 _PyUnicodeWriter_Init(&writer);
8696 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008698
Victor Stinner872b2912014-04-05 14:27:07 +02008699 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8700
8701 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008702 if (res < 0) {
8703 _PyUnicodeWriter_Dealloc(&writer);
8704 return NULL;
8705 }
8706 if (res == 1)
8707 return _PyUnicodeWriter_Finish(&writer);
8708
Victor Stinner89a76ab2014-04-05 11:44:04 +02008709 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008710 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008712 int translate;
8713 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8714 Py_ssize_t newpos;
8715 /* startpos for collecting untranslatable chars */
8716 Py_ssize_t collstart;
8717 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008718 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008719
Victor Stinner1194ea02014-04-04 19:37:40 +02008720 ch = PyUnicode_READ(kind, data, i);
8721 translate = charmaptranslate_output(ch, mapping, &writer);
8722 if (translate < 0)
8723 goto onError;
8724
8725 if (translate != 0) {
8726 /* it worked => adjust input pointer */
8727 ++i;
8728 continue;
8729 }
8730
8731 /* untranslatable character */
8732 collstart = i;
8733 collend = i+1;
8734
8735 /* find all untranslatable characters */
8736 while (collend < size) {
8737 PyObject *x;
8738 ch = PyUnicode_READ(kind, data, collend);
8739 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008740 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008741 Py_XDECREF(x);
8742 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008744 ++collend;
8745 }
8746
8747 if (ignore) {
8748 i = collend;
8749 }
8750 else {
8751 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8752 reason, input, &exc,
8753 collstart, collend, &newpos);
8754 if (repunicode == NULL)
8755 goto onError;
8756 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008758 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008759 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008760 Py_DECREF(repunicode);
8761 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008762 }
8763 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008764 Py_XDECREF(exc);
8765 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008766 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008767
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008769 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770 Py_XDECREF(exc);
8771 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772 return NULL;
8773}
8774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775/* Deprecated. Use PyUnicode_Translate instead. */
8776PyObject *
8777PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8778 Py_ssize_t size,
8779 PyObject *mapping,
8780 const char *errors)
8781{
Christian Heimes5f520f42012-09-11 14:03:25 +02008782 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8784 if (!unicode)
8785 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008786 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8787 Py_DECREF(unicode);
8788 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008789}
8790
Alexander Belopolsky40018472011-02-26 01:02:56 +00008791PyObject *
8792PyUnicode_Translate(PyObject *str,
8793 PyObject *mapping,
8794 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008795{
8796 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008797
Guido van Rossumd57fd912000-03-10 22:53:23 +00008798 str = PyUnicode_FromObject(str);
8799 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008800 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008802 Py_DECREF(str);
8803 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008804}
Tim Petersced69f82003-09-16 20:30:58 +00008805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008807fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808{
8809 /* No need to call PyUnicode_READY(self) because this function is only
8810 called as a callback from fixup() which does it already. */
8811 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8812 const int kind = PyUnicode_KIND(self);
8813 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008814 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008815 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008816 Py_ssize_t i;
8817
8818 for (i = 0; i < len; ++i) {
8819 ch = PyUnicode_READ(kind, data, i);
8820 fixed = 0;
8821 if (ch > 127) {
8822 if (Py_UNICODE_ISSPACE(ch))
8823 fixed = ' ';
8824 else {
8825 const int decimal = Py_UNICODE_TODECIMAL(ch);
8826 if (decimal >= 0)
8827 fixed = '0' + decimal;
8828 }
8829 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008830 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008831 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832 PyUnicode_WRITE(kind, data, i, fixed);
8833 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008834 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008835 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008837 }
8838
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008839 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840}
8841
8842PyObject *
8843_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8844{
8845 if (!PyUnicode_Check(unicode)) {
8846 PyErr_BadInternalCall();
8847 return NULL;
8848 }
8849 if (PyUnicode_READY(unicode) == -1)
8850 return NULL;
8851 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8852 /* If the string is already ASCII, just return the same string */
8853 Py_INCREF(unicode);
8854 return unicode;
8855 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008856 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857}
8858
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008859PyObject *
8860PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8861 Py_ssize_t length)
8862{
Victor Stinnerf0124502011-11-21 23:12:56 +01008863 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008864 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008865 Py_UCS4 maxchar;
8866 enum PyUnicode_Kind kind;
8867 void *data;
8868
Victor Stinner99d7ad02012-02-22 13:37:39 +01008869 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008870 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008871 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008872 if (ch > 127) {
8873 int decimal = Py_UNICODE_TODECIMAL(ch);
8874 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008875 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008876 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008877 }
8878 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008879
8880 /* Copy to a new string */
8881 decimal = PyUnicode_New(length, maxchar);
8882 if (decimal == NULL)
8883 return decimal;
8884 kind = PyUnicode_KIND(decimal);
8885 data = PyUnicode_DATA(decimal);
8886 /* Iterate over code points */
8887 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008888 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008889 if (ch > 127) {
8890 int decimal = Py_UNICODE_TODECIMAL(ch);
8891 if (decimal >= 0)
8892 ch = '0' + decimal;
8893 }
8894 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008895 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008896 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008897}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008898/* --- Decimal Encoder ---------------------------------------------------- */
8899
Alexander Belopolsky40018472011-02-26 01:02:56 +00008900int
8901PyUnicode_EncodeDecimal(Py_UNICODE *s,
8902 Py_ssize_t length,
8903 char *output,
8904 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008905{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008906 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008907 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008908 enum PyUnicode_Kind kind;
8909 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008910
8911 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008912 PyErr_BadArgument();
8913 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008914 }
8915
Victor Stinner42bf7752011-11-21 22:52:58 +01008916 unicode = PyUnicode_FromUnicode(s, length);
8917 if (unicode == NULL)
8918 return -1;
8919
Benjamin Petersonbac79492012-01-14 13:34:47 -05008920 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008921 Py_DECREF(unicode);
8922 return -1;
8923 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008924 kind = PyUnicode_KIND(unicode);
8925 data = PyUnicode_DATA(unicode);
8926
Victor Stinnerb84d7232011-11-22 01:50:07 +01008927 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008928 PyObject *exc;
8929 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008930 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008931 Py_ssize_t startpos;
8932
8933 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008934
Benjamin Peterson29060642009-01-31 22:14:21 +00008935 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008936 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008937 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008938 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008939 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008940 decimal = Py_UNICODE_TODECIMAL(ch);
8941 if (decimal >= 0) {
8942 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008943 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 continue;
8945 }
8946 if (0 < ch && ch < 256) {
8947 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008948 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 continue;
8950 }
Victor Stinner6345be92011-11-25 20:09:01 +01008951
Victor Stinner42bf7752011-11-21 22:52:58 +01008952 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008953 exc = NULL;
8954 raise_encode_exception(&exc, "decimal", unicode,
8955 startpos, startpos+1,
8956 "invalid decimal Unicode string");
8957 Py_XDECREF(exc);
8958 Py_DECREF(unicode);
8959 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008960 }
8961 /* 0-terminate the output string */
8962 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008963 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008964 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008965}
8966
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967/* --- Helpers ------------------------------------------------------------ */
8968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008970any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008971 Py_ssize_t start,
8972 Py_ssize_t end)
8973{
8974 int kind1, kind2, kind;
8975 void *buf1, *buf2;
8976 Py_ssize_t len1, len2, result;
8977
8978 kind1 = PyUnicode_KIND(s1);
8979 kind2 = PyUnicode_KIND(s2);
8980 kind = kind1 > kind2 ? kind1 : kind2;
8981 buf1 = PyUnicode_DATA(s1);
8982 buf2 = PyUnicode_DATA(s2);
8983 if (kind1 != kind)
8984 buf1 = _PyUnicode_AsKind(s1, kind);
8985 if (!buf1)
8986 return -2;
8987 if (kind2 != kind)
8988 buf2 = _PyUnicode_AsKind(s2, kind);
8989 if (!buf2) {
8990 if (kind1 != kind) PyMem_Free(buf1);
8991 return -2;
8992 }
8993 len1 = PyUnicode_GET_LENGTH(s1);
8994 len2 = PyUnicode_GET_LENGTH(s2);
8995
Victor Stinner794d5672011-10-10 03:21:36 +02008996 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008997 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008998 case PyUnicode_1BYTE_KIND:
8999 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9000 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9001 else
9002 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9003 break;
9004 case PyUnicode_2BYTE_KIND:
9005 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9006 break;
9007 case PyUnicode_4BYTE_KIND:
9008 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9009 break;
9010 default:
9011 assert(0); result = -2;
9012 }
9013 }
9014 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009015 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009016 case PyUnicode_1BYTE_KIND:
9017 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9018 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9019 else
9020 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9021 break;
9022 case PyUnicode_2BYTE_KIND:
9023 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9024 break;
9025 case PyUnicode_4BYTE_KIND:
9026 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9027 break;
9028 default:
9029 assert(0); result = -2;
9030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031 }
9032
9033 if (kind1 != kind)
9034 PyMem_Free(buf1);
9035 if (kind2 != kind)
9036 PyMem_Free(buf2);
9037
9038 return result;
9039}
9040
9041Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009042_PyUnicode_InsertThousandsGrouping(
9043 PyObject *unicode, Py_ssize_t index,
9044 Py_ssize_t n_buffer,
9045 void *digits, Py_ssize_t n_digits,
9046 Py_ssize_t min_width,
9047 const char *grouping, PyObject *thousands_sep,
9048 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049{
Victor Stinner41a863c2012-02-24 00:37:51 +01009050 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009051 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009052 Py_ssize_t thousands_sep_len;
9053 Py_ssize_t len;
9054
9055 if (unicode != NULL) {
9056 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009057 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009058 }
9059 else {
9060 kind = PyUnicode_1BYTE_KIND;
9061 data = NULL;
9062 }
9063 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9064 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9065 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9066 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009067 if (thousands_sep_kind < kind) {
9068 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9069 if (!thousands_sep_data)
9070 return -1;
9071 }
9072 else {
9073 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9074 if (!data)
9075 return -1;
9076 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009077 }
9078
Benjamin Petersonead6b532011-12-20 17:23:42 -06009079 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009081 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009082 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009083 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009084 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009085 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009086 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009087 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009088 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009089 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009090 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009091 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009094 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009095 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009096 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009097 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009100 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009102 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009103 break;
9104 default:
9105 assert(0);
9106 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009108 if (unicode != NULL && thousands_sep_kind != kind) {
9109 if (thousands_sep_kind < kind)
9110 PyMem_Free(thousands_sep_data);
9111 else
9112 PyMem_Free(data);
9113 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009114 if (unicode == NULL) {
9115 *maxchar = 127;
9116 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009117 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009118 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009119 }
9120 }
9121 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009122}
9123
9124
Thomas Wouters477c8d52006-05-27 19:21:47 +00009125/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009126#define ADJUST_INDICES(start, end, len) \
9127 if (end > len) \
9128 end = len; \
9129 else if (end < 0) { \
9130 end += len; \
9131 if (end < 0) \
9132 end = 0; \
9133 } \
9134 if (start < 0) { \
9135 start += len; \
9136 if (start < 0) \
9137 start = 0; \
9138 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009139
Alexander Belopolsky40018472011-02-26 01:02:56 +00009140Py_ssize_t
9141PyUnicode_Count(PyObject *str,
9142 PyObject *substr,
9143 Py_ssize_t start,
9144 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009146 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009147 PyObject* str_obj;
9148 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009149 int kind1, kind2, kind;
9150 void *buf1 = NULL, *buf2 = NULL;
9151 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009152
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009153 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009154 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009155 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009156 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009157 if (!sub_obj) {
9158 Py_DECREF(str_obj);
9159 return -1;
9160 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009161 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009162 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009163 Py_DECREF(str_obj);
9164 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165 }
Tim Petersced69f82003-09-16 20:30:58 +00009166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 kind1 = PyUnicode_KIND(str_obj);
9168 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009169 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009170 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009171 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009172 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009173 if (kind2 > kind) {
9174 Py_DECREF(sub_obj);
9175 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009176 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009177 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009178 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009179 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 if (!buf2)
9181 goto onError;
9182 len1 = PyUnicode_GET_LENGTH(str_obj);
9183 len2 = PyUnicode_GET_LENGTH(sub_obj);
9184
9185 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009186 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009188 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9189 result = asciilib_count(
9190 ((Py_UCS1*)buf1) + start, end - start,
9191 buf2, len2, PY_SSIZE_T_MAX
9192 );
9193 else
9194 result = ucs1lib_count(
9195 ((Py_UCS1*)buf1) + start, end - start,
9196 buf2, len2, PY_SSIZE_T_MAX
9197 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 break;
9199 case PyUnicode_2BYTE_KIND:
9200 result = ucs2lib_count(
9201 ((Py_UCS2*)buf1) + start, end - start,
9202 buf2, len2, PY_SSIZE_T_MAX
9203 );
9204 break;
9205 case PyUnicode_4BYTE_KIND:
9206 result = ucs4lib_count(
9207 ((Py_UCS4*)buf1) + start, end - start,
9208 buf2, len2, PY_SSIZE_T_MAX
9209 );
9210 break;
9211 default:
9212 assert(0); result = 0;
9213 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009214
9215 Py_DECREF(sub_obj);
9216 Py_DECREF(str_obj);
9217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 if (kind2 != kind)
9219 PyMem_Free(buf2);
9220
Guido van Rossumd57fd912000-03-10 22:53:23 +00009221 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222 onError:
9223 Py_DECREF(sub_obj);
9224 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 if (kind2 != kind && buf2)
9226 PyMem_Free(buf2);
9227 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009228}
9229
Alexander Belopolsky40018472011-02-26 01:02:56 +00009230Py_ssize_t
9231PyUnicode_Find(PyObject *str,
9232 PyObject *sub,
9233 Py_ssize_t start,
9234 Py_ssize_t end,
9235 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009237 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009238
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009240 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009241 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009242 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009243 if (!sub) {
9244 Py_DECREF(str);
9245 return -2;
9246 }
9247 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9248 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009249 Py_DECREF(str);
9250 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251 }
Tim Petersced69f82003-09-16 20:30:58 +00009252
Victor Stinner794d5672011-10-10 03:21:36 +02009253 result = any_find_slice(direction,
9254 str, sub, start, end
9255 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009256
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009258 Py_DECREF(sub);
9259
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 return result;
9261}
9262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263Py_ssize_t
9264PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9265 Py_ssize_t start, Py_ssize_t end,
9266 int direction)
9267{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009269 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 if (PyUnicode_READY(str) == -1)
9271 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009272 if (start < 0 || end < 0) {
9273 PyErr_SetString(PyExc_IndexError, "string index out of range");
9274 return -2;
9275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 if (end > PyUnicode_GET_LENGTH(str))
9277 end = PyUnicode_GET_LENGTH(str);
9278 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009279 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9280 kind, end-start, ch, direction);
9281 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009283 else
9284 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285}
9286
Alexander Belopolsky40018472011-02-26 01:02:56 +00009287static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009288tailmatch(PyObject *self,
9289 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009290 Py_ssize_t start,
9291 Py_ssize_t end,
9292 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 int kind_self;
9295 int kind_sub;
9296 void *data_self;
9297 void *data_sub;
9298 Py_ssize_t offset;
9299 Py_ssize_t i;
9300 Py_ssize_t end_sub;
9301
9302 if (PyUnicode_READY(self) == -1 ||
9303 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009304 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305
9306 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009307 return 1;
9308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009309 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9310 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009312 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009314 kind_self = PyUnicode_KIND(self);
9315 data_self = PyUnicode_DATA(self);
9316 kind_sub = PyUnicode_KIND(substring);
9317 data_sub = PyUnicode_DATA(substring);
9318 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9319
9320 if (direction > 0)
9321 offset = end;
9322 else
9323 offset = start;
9324
9325 if (PyUnicode_READ(kind_self, data_self, offset) ==
9326 PyUnicode_READ(kind_sub, data_sub, 0) &&
9327 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9328 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9329 /* If both are of the same kind, memcmp is sufficient */
9330 if (kind_self == kind_sub) {
9331 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009332 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 data_sub,
9334 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009335 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 }
9337 /* otherwise we have to compare each character by first accesing it */
9338 else {
9339 /* We do not need to compare 0 and len(substring)-1 because
9340 the if statement above ensured already that they are equal
9341 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 for (i = 1; i < end_sub; ++i) {
9343 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9344 PyUnicode_READ(kind_sub, data_sub, i))
9345 return 0;
9346 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009347 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009349 }
9350
9351 return 0;
9352}
9353
Alexander Belopolsky40018472011-02-26 01:02:56 +00009354Py_ssize_t
9355PyUnicode_Tailmatch(PyObject *str,
9356 PyObject *substr,
9357 Py_ssize_t start,
9358 Py_ssize_t end,
9359 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009361 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009362
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363 str = PyUnicode_FromObject(str);
9364 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009365 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366 substr = PyUnicode_FromObject(substr);
9367 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 Py_DECREF(str);
9369 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370 }
Tim Petersced69f82003-09-16 20:30:58 +00009371
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009372 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009373 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 Py_DECREF(str);
9375 Py_DECREF(substr);
9376 return result;
9377}
9378
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379/* Apply fixfct filter to the Unicode object self and return a
9380 reference to the modified object */
9381
Alexander Belopolsky40018472011-02-26 01:02:56 +00009382static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009383fixup(PyObject *self,
9384 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 PyObject *u;
9387 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009388 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009390 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009392 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009393 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 /* fix functions return the new maximum character in a string,
9396 if the kind of the resulting unicode object does not change,
9397 everything is fine. Otherwise we need to change the string kind
9398 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009399 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009400
9401 if (maxchar_new == 0) {
9402 /* no changes */;
9403 if (PyUnicode_CheckExact(self)) {
9404 Py_DECREF(u);
9405 Py_INCREF(self);
9406 return self;
9407 }
9408 else
9409 return u;
9410 }
9411
Victor Stinnere6abb482012-05-02 01:15:40 +02009412 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009413
Victor Stinnereaab6042011-12-11 22:22:39 +01009414 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009416
9417 /* In case the maximum character changed, we need to
9418 convert the string to the new category. */
9419 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9420 if (v == NULL) {
9421 Py_DECREF(u);
9422 return NULL;
9423 }
9424 if (maxchar_new > maxchar_old) {
9425 /* If the maxchar increased so that the kind changed, not all
9426 characters are representable anymore and we need to fix the
9427 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009428 _PyUnicode_FastCopyCharacters(v, 0,
9429 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009430 maxchar_old = fixfct(v);
9431 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 }
9433 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009434 _PyUnicode_FastCopyCharacters(v, 0,
9435 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009437 Py_DECREF(u);
9438 assert(_PyUnicode_CheckConsistency(v, 1));
9439 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009440}
9441
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009442static PyObject *
9443ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009444{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009445 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9446 char *resdata, *data = PyUnicode_DATA(self);
9447 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009448
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009449 res = PyUnicode_New(len, 127);
9450 if (res == NULL)
9451 return NULL;
9452 resdata = PyUnicode_DATA(res);
9453 if (lower)
9454 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009456 _Py_bytes_upper(resdata, data, len);
9457 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458}
9459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009461handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009463 Py_ssize_t j;
9464 int final_sigma;
9465 Py_UCS4 c;
9466 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009467
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009468 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9469
9470 where ! is a negation and \p{xxx} is a character with property xxx.
9471 */
9472 for (j = i - 1; j >= 0; j--) {
9473 c = PyUnicode_READ(kind, data, j);
9474 if (!_PyUnicode_IsCaseIgnorable(c))
9475 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009476 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009477 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9478 if (final_sigma) {
9479 for (j = i + 1; j < length; j++) {
9480 c = PyUnicode_READ(kind, data, j);
9481 if (!_PyUnicode_IsCaseIgnorable(c))
9482 break;
9483 }
9484 final_sigma = j == length || !_PyUnicode_IsCased(c);
9485 }
9486 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487}
9488
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009489static int
9490lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9491 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009493 /* Obscure special case. */
9494 if (c == 0x3A3) {
9495 mapped[0] = handle_capital_sigma(kind, data, length, i);
9496 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009498 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499}
9500
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009501static Py_ssize_t
9502do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009504 Py_ssize_t i, k = 0;
9505 int n_res, j;
9506 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009507
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009508 c = PyUnicode_READ(kind, data, 0);
9509 n_res = _PyUnicode_ToUpperFull(c, mapped);
9510 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009511 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009512 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009514 for (i = 1; i < length; i++) {
9515 c = PyUnicode_READ(kind, data, i);
9516 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9517 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009518 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009519 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009520 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009521 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009522 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009523}
9524
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009525static Py_ssize_t
9526do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9527 Py_ssize_t i, k = 0;
9528
9529 for (i = 0; i < length; i++) {
9530 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9531 int n_res, j;
9532 if (Py_UNICODE_ISUPPER(c)) {
9533 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9534 }
9535 else if (Py_UNICODE_ISLOWER(c)) {
9536 n_res = _PyUnicode_ToUpperFull(c, mapped);
9537 }
9538 else {
9539 n_res = 1;
9540 mapped[0] = c;
9541 }
9542 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009543 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009544 res[k++] = mapped[j];
9545 }
9546 }
9547 return k;
9548}
9549
9550static Py_ssize_t
9551do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9552 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009554 Py_ssize_t i, k = 0;
9555
9556 for (i = 0; i < length; i++) {
9557 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9558 int n_res, j;
9559 if (lower)
9560 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9561 else
9562 n_res = _PyUnicode_ToUpperFull(c, mapped);
9563 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009564 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 res[k++] = mapped[j];
9566 }
9567 }
9568 return k;
9569}
9570
9571static Py_ssize_t
9572do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9573{
9574 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9575}
9576
9577static Py_ssize_t
9578do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9579{
9580 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9581}
9582
Benjamin Petersone51757f2012-01-12 21:10:29 -05009583static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009584do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9585{
9586 Py_ssize_t i, k = 0;
9587
9588 for (i = 0; i < length; i++) {
9589 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9590 Py_UCS4 mapped[3];
9591 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9592 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009593 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009594 res[k++] = mapped[j];
9595 }
9596 }
9597 return k;
9598}
9599
9600static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009601do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9602{
9603 Py_ssize_t i, k = 0;
9604 int previous_is_cased;
9605
9606 previous_is_cased = 0;
9607 for (i = 0; i < length; i++) {
9608 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9609 Py_UCS4 mapped[3];
9610 int n_res, j;
9611
9612 if (previous_is_cased)
9613 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9614 else
9615 n_res = _PyUnicode_ToTitleFull(c, mapped);
9616
9617 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009618 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009619 res[k++] = mapped[j];
9620 }
9621
9622 previous_is_cased = _PyUnicode_IsCased(c);
9623 }
9624 return k;
9625}
9626
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009627static PyObject *
9628case_operation(PyObject *self,
9629 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9630{
9631 PyObject *res = NULL;
9632 Py_ssize_t length, newlength = 0;
9633 int kind, outkind;
9634 void *data, *outdata;
9635 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9636
Benjamin Petersoneea48462012-01-16 14:28:50 -05009637 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638
9639 kind = PyUnicode_KIND(self);
9640 data = PyUnicode_DATA(self);
9641 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009642 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009643 PyErr_SetString(PyExc_OverflowError, "string is too long");
9644 return NULL;
9645 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009646 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647 if (tmp == NULL)
9648 return PyErr_NoMemory();
9649 newlength = perform(kind, data, length, tmp, &maxchar);
9650 res = PyUnicode_New(newlength, maxchar);
9651 if (res == NULL)
9652 goto leave;
9653 tmpend = tmp + newlength;
9654 outdata = PyUnicode_DATA(res);
9655 outkind = PyUnicode_KIND(res);
9656 switch (outkind) {
9657 case PyUnicode_1BYTE_KIND:
9658 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9659 break;
9660 case PyUnicode_2BYTE_KIND:
9661 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9662 break;
9663 case PyUnicode_4BYTE_KIND:
9664 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9665 break;
9666 default:
9667 assert(0);
9668 break;
9669 }
9670 leave:
9671 PyMem_FREE(tmp);
9672 return res;
9673}
9674
Tim Peters8ce9f162004-08-27 01:49:32 +00009675PyObject *
9676PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009677{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009679 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009681 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009682 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9683 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009684 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009685 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009686 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009688 int use_memcpy;
9689 unsigned char *res_data = NULL, *sep_data = NULL;
9690 PyObject *last_obj;
9691 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009692
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009693 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009694 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009695 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009696 }
9697
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009698 /* NOTE: the following code can't call back into Python code,
9699 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009700 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009701
Tim Peters05eba1f2004-08-27 21:32:02 +00009702 seqlen = PySequence_Fast_GET_SIZE(fseq);
9703 /* If empty sequence, return u"". */
9704 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009705 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009706 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009707 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009708
Tim Peters05eba1f2004-08-27 21:32:02 +00009709 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009710 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009711 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009712 if (seqlen == 1) {
9713 if (PyUnicode_CheckExact(items[0])) {
9714 res = items[0];
9715 Py_INCREF(res);
9716 Py_DECREF(fseq);
9717 return res;
9718 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009719 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009720 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009721 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009722 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009723 /* Set up sep and seplen */
9724 if (separator == NULL) {
9725 /* fall back to a blank space separator */
9726 sep = PyUnicode_FromOrdinal(' ');
9727 if (!sep)
9728 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009729 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009730 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009731 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009732 else {
9733 if (!PyUnicode_Check(separator)) {
9734 PyErr_Format(PyExc_TypeError,
9735 "separator: expected str instance,"
9736 " %.80s found",
9737 Py_TYPE(separator)->tp_name);
9738 goto onError;
9739 }
9740 if (PyUnicode_READY(separator))
9741 goto onError;
9742 sep = separator;
9743 seplen = PyUnicode_GET_LENGTH(separator);
9744 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9745 /* inc refcount to keep this code path symmetric with the
9746 above case of a blank separator */
9747 Py_INCREF(sep);
9748 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009749 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009750 }
9751
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009752 /* There are at least two things to join, or else we have a subclass
9753 * of str in the sequence.
9754 * Do a pre-pass to figure out the total amount of space we'll
9755 * need (sz), and see whether all argument are strings.
9756 */
9757 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009758#ifdef Py_DEBUG
9759 use_memcpy = 0;
9760#else
9761 use_memcpy = 1;
9762#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 for (i = 0; i < seqlen; i++) {
9764 const Py_ssize_t old_sz = sz;
9765 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009766 if (!PyUnicode_Check(item)) {
9767 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009768 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009769 " %.80s found",
9770 i, Py_TYPE(item)->tp_name);
9771 goto onError;
9772 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009773 if (PyUnicode_READY(item) == -1)
9774 goto onError;
9775 sz += PyUnicode_GET_LENGTH(item);
9776 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009777 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009778 if (i != 0)
9779 sz += seplen;
9780 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9781 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009782 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009783 goto onError;
9784 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009785 if (use_memcpy && last_obj != NULL) {
9786 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9787 use_memcpy = 0;
9788 }
9789 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009790 }
Tim Petersced69f82003-09-16 20:30:58 +00009791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009793 if (res == NULL)
9794 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009795
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009796 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009797#ifdef Py_DEBUG
9798 use_memcpy = 0;
9799#else
9800 if (use_memcpy) {
9801 res_data = PyUnicode_1BYTE_DATA(res);
9802 kind = PyUnicode_KIND(res);
9803 if (seplen != 0)
9804 sep_data = PyUnicode_1BYTE_DATA(sep);
9805 }
9806#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009807 if (use_memcpy) {
9808 for (i = 0; i < seqlen; ++i) {
9809 Py_ssize_t itemlen;
9810 item = items[i];
9811
9812 /* Copy item, and maybe the separator. */
9813 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009814 Py_MEMCPY(res_data,
9815 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009816 kind * seplen);
9817 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009818 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009819
9820 itemlen = PyUnicode_GET_LENGTH(item);
9821 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009822 Py_MEMCPY(res_data,
9823 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009824 kind * itemlen);
9825 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009826 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009827 }
9828 assert(res_data == PyUnicode_1BYTE_DATA(res)
9829 + kind * PyUnicode_GET_LENGTH(res));
9830 }
9831 else {
9832 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9833 Py_ssize_t itemlen;
9834 item = items[i];
9835
9836 /* Copy item, and maybe the separator. */
9837 if (i && seplen != 0) {
9838 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9839 res_offset += seplen;
9840 }
9841
9842 itemlen = PyUnicode_GET_LENGTH(item);
9843 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009844 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009845 res_offset += itemlen;
9846 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009847 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009848 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009849 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009850
Tim Peters05eba1f2004-08-27 21:32:02 +00009851 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009853 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009855
Benjamin Peterson29060642009-01-31 22:14:21 +00009856 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009857 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009858 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009859 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009860 return NULL;
9861}
9862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863#define FILL(kind, data, value, start, length) \
9864 do { \
9865 Py_ssize_t i_ = 0; \
9866 assert(kind != PyUnicode_WCHAR_KIND); \
9867 switch ((kind)) { \
9868 case PyUnicode_1BYTE_KIND: { \
9869 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009870 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 break; \
9872 } \
9873 case PyUnicode_2BYTE_KIND: { \
9874 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9875 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9876 break; \
9877 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009878 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9880 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9881 break; \
9882 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009883 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 } \
9885 } while (0)
9886
Victor Stinnerd3f08822012-05-29 12:57:52 +02009887void
9888_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9889 Py_UCS4 fill_char)
9890{
9891 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9892 const void *data = PyUnicode_DATA(unicode);
9893 assert(PyUnicode_IS_READY(unicode));
9894 assert(unicode_modifiable(unicode));
9895 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9896 assert(start >= 0);
9897 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9898 FILL(kind, data, fill_char, start, length);
9899}
9900
Victor Stinner3fe55312012-01-04 00:33:50 +01009901Py_ssize_t
9902PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9903 Py_UCS4 fill_char)
9904{
9905 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009906
9907 if (!PyUnicode_Check(unicode)) {
9908 PyErr_BadInternalCall();
9909 return -1;
9910 }
9911 if (PyUnicode_READY(unicode) == -1)
9912 return -1;
9913 if (unicode_check_modifiable(unicode))
9914 return -1;
9915
Victor Stinnerd3f08822012-05-29 12:57:52 +02009916 if (start < 0) {
9917 PyErr_SetString(PyExc_IndexError, "string index out of range");
9918 return -1;
9919 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009920 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9921 PyErr_SetString(PyExc_ValueError,
9922 "fill character is bigger than "
9923 "the string maximum character");
9924 return -1;
9925 }
9926
9927 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9928 length = Py_MIN(maxlen, length);
9929 if (length <= 0)
9930 return 0;
9931
Victor Stinnerd3f08822012-05-29 12:57:52 +02009932 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009933 return length;
9934}
9935
Victor Stinner9310abb2011-10-05 00:59:23 +02009936static PyObject *
9937pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009938 Py_ssize_t left,
9939 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009941{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 PyObject *u;
9943 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009944 int kind;
9945 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009946
9947 if (left < 0)
9948 left = 0;
9949 if (right < 0)
9950 right = 0;
9951
Victor Stinnerc4b49542011-12-11 22:44:26 +01009952 if (left == 0 && right == 0)
9953 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009955 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9956 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009957 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9958 return NULL;
9959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009960 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009961 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009963 if (!u)
9964 return NULL;
9965
9966 kind = PyUnicode_KIND(u);
9967 data = PyUnicode_DATA(u);
9968 if (left)
9969 FILL(kind, data, fill, 0, left);
9970 if (right)
9971 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009972 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009973 assert(_PyUnicode_CheckConsistency(u, 1));
9974 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009975}
9976
Alexander Belopolsky40018472011-02-26 01:02:56 +00009977PyObject *
9978PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009979{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009981
9982 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009983 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009984 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009985 if (PyUnicode_READY(string) == -1) {
9986 Py_DECREF(string);
9987 return NULL;
9988 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009989
Benjamin Petersonead6b532011-12-20 17:23:42 -06009990 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009992 if (PyUnicode_IS_ASCII(string))
9993 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009994 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009995 PyUnicode_GET_LENGTH(string), keepends);
9996 else
9997 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009998 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009999 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 break;
10001 case PyUnicode_2BYTE_KIND:
10002 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010003 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 PyUnicode_GET_LENGTH(string), keepends);
10005 break;
10006 case PyUnicode_4BYTE_KIND:
10007 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010008 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 PyUnicode_GET_LENGTH(string), keepends);
10010 break;
10011 default:
10012 assert(0);
10013 list = 0;
10014 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010015 Py_DECREF(string);
10016 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010017}
10018
Alexander Belopolsky40018472011-02-26 01:02:56 +000010019static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010020split(PyObject *self,
10021 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010022 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010023{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024 int kind1, kind2, kind;
10025 void *buf1, *buf2;
10026 Py_ssize_t len1, len2;
10027 PyObject* out;
10028
Guido van Rossumd57fd912000-03-10 22:53:23 +000010029 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010030 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010031
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 if (PyUnicode_READY(self) == -1)
10033 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010036 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010038 if (PyUnicode_IS_ASCII(self))
10039 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010040 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010041 PyUnicode_GET_LENGTH(self), maxcount
10042 );
10043 else
10044 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010045 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010046 PyUnicode_GET_LENGTH(self), maxcount
10047 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 case PyUnicode_2BYTE_KIND:
10049 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010050 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 PyUnicode_GET_LENGTH(self), maxcount
10052 );
10053 case PyUnicode_4BYTE_KIND:
10054 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010055 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 PyUnicode_GET_LENGTH(self), maxcount
10057 );
10058 default:
10059 assert(0);
10060 return NULL;
10061 }
10062
10063 if (PyUnicode_READY(substring) == -1)
10064 return NULL;
10065
10066 kind1 = PyUnicode_KIND(self);
10067 kind2 = PyUnicode_KIND(substring);
10068 kind = kind1 > kind2 ? kind1 : kind2;
10069 buf1 = PyUnicode_DATA(self);
10070 buf2 = PyUnicode_DATA(substring);
10071 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010072 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 if (!buf1)
10074 return NULL;
10075 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010076 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 if (!buf2) {
10078 if (kind1 != kind) PyMem_Free(buf1);
10079 return NULL;
10080 }
10081 len1 = PyUnicode_GET_LENGTH(self);
10082 len2 = PyUnicode_GET_LENGTH(substring);
10083
Benjamin Petersonead6b532011-12-20 17:23:42 -060010084 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010086 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10087 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010088 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010089 else
10090 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010091 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 break;
10093 case PyUnicode_2BYTE_KIND:
10094 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010095 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 break;
10097 case PyUnicode_4BYTE_KIND:
10098 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010099 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 break;
10101 default:
10102 out = NULL;
10103 }
10104 if (kind1 != kind)
10105 PyMem_Free(buf1);
10106 if (kind2 != kind)
10107 PyMem_Free(buf2);
10108 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109}
10110
Alexander Belopolsky40018472011-02-26 01:02:56 +000010111static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010112rsplit(PyObject *self,
10113 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010114 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 int kind1, kind2, kind;
10117 void *buf1, *buf2;
10118 Py_ssize_t len1, len2;
10119 PyObject* out;
10120
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010121 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010122 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 if (PyUnicode_READY(self) == -1)
10125 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010128 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010130 if (PyUnicode_IS_ASCII(self))
10131 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010132 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010133 PyUnicode_GET_LENGTH(self), maxcount
10134 );
10135 else
10136 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010137 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010138 PyUnicode_GET_LENGTH(self), maxcount
10139 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_2BYTE_KIND:
10141 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 PyUnicode_GET_LENGTH(self), maxcount
10144 );
10145 case PyUnicode_4BYTE_KIND:
10146 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010147 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 PyUnicode_GET_LENGTH(self), maxcount
10149 );
10150 default:
10151 assert(0);
10152 return NULL;
10153 }
10154
10155 if (PyUnicode_READY(substring) == -1)
10156 return NULL;
10157
10158 kind1 = PyUnicode_KIND(self);
10159 kind2 = PyUnicode_KIND(substring);
10160 kind = kind1 > kind2 ? kind1 : kind2;
10161 buf1 = PyUnicode_DATA(self);
10162 buf2 = PyUnicode_DATA(substring);
10163 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010164 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 if (!buf1)
10166 return NULL;
10167 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010168 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 if (!buf2) {
10170 if (kind1 != kind) PyMem_Free(buf1);
10171 return NULL;
10172 }
10173 len1 = PyUnicode_GET_LENGTH(self);
10174 len2 = PyUnicode_GET_LENGTH(substring);
10175
Benjamin Petersonead6b532011-12-20 17:23:42 -060010176 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010178 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10179 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010180 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010181 else
10182 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010183 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 break;
10185 case PyUnicode_2BYTE_KIND:
10186 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 break;
10189 case PyUnicode_4BYTE_KIND:
10190 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010191 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 break;
10193 default:
10194 out = NULL;
10195 }
10196 if (kind1 != kind)
10197 PyMem_Free(buf1);
10198 if (kind2 != kind)
10199 PyMem_Free(buf2);
10200 return out;
10201}
10202
10203static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010204anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10205 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010207 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010209 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10210 return asciilib_find(buf1, len1, buf2, len2, offset);
10211 else
10212 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 case PyUnicode_2BYTE_KIND:
10214 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10215 case PyUnicode_4BYTE_KIND:
10216 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10217 }
10218 assert(0);
10219 return -1;
10220}
10221
10222static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010223anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10224 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010226 switch (kind) {
10227 case PyUnicode_1BYTE_KIND:
10228 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10229 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10230 else
10231 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10232 case PyUnicode_2BYTE_KIND:
10233 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10234 case PyUnicode_4BYTE_KIND:
10235 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10236 }
10237 assert(0);
10238 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010239}
10240
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010241static void
10242replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10243 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10244{
10245 int kind = PyUnicode_KIND(u);
10246 void *data = PyUnicode_DATA(u);
10247 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10248 if (kind == PyUnicode_1BYTE_KIND) {
10249 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10250 (Py_UCS1 *)data + len,
10251 u1, u2, maxcount);
10252 }
10253 else if (kind == PyUnicode_2BYTE_KIND) {
10254 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10255 (Py_UCS2 *)data + len,
10256 u1, u2, maxcount);
10257 }
10258 else {
10259 assert(kind == PyUnicode_4BYTE_KIND);
10260 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10261 (Py_UCS4 *)data + len,
10262 u1, u2, maxcount);
10263 }
10264}
10265
Alexander Belopolsky40018472011-02-26 01:02:56 +000010266static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267replace(PyObject *self, PyObject *str1,
10268 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010269{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 PyObject *u;
10271 char *sbuf = PyUnicode_DATA(self);
10272 char *buf1 = PyUnicode_DATA(str1);
10273 char *buf2 = PyUnicode_DATA(str2);
10274 int srelease = 0, release1 = 0, release2 = 0;
10275 int skind = PyUnicode_KIND(self);
10276 int kind1 = PyUnicode_KIND(str1);
10277 int kind2 = PyUnicode_KIND(str2);
10278 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10279 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10280 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010281 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010282 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283
10284 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010285 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010287 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010288
Victor Stinner59de0ee2011-10-07 10:01:28 +020010289 if (str1 == str2)
10290 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291
Victor Stinner49a0a212011-10-12 23:46:10 +020010292 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010293 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10294 if (maxchar < maxchar_str1)
10295 /* substring too wide to be present */
10296 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010297 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10298 /* Replacing str1 with str2 may cause a maxchar reduction in the
10299 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010300 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010301 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010304 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010306 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010308 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010309 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010310 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010311
Victor Stinner69ed0f42013-04-09 21:48:24 +020010312 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010313 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010314 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010315 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010316 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010318 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010320
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010321 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10322 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010323 }
10324 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 int rkind = skind;
10326 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010327 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 if (kind1 < rkind) {
10330 /* widen substring */
10331 buf1 = _PyUnicode_AsKind(str1, rkind);
10332 if (!buf1) goto error;
10333 release1 = 1;
10334 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010335 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010336 if (i < 0)
10337 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 if (rkind > kind2) {
10339 /* widen replacement */
10340 buf2 = _PyUnicode_AsKind(str2, rkind);
10341 if (!buf2) goto error;
10342 release2 = 1;
10343 }
10344 else if (rkind < kind2) {
10345 /* widen self and buf1 */
10346 rkind = kind2;
10347 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010348 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 sbuf = _PyUnicode_AsKind(self, rkind);
10350 if (!sbuf) goto error;
10351 srelease = 1;
10352 buf1 = _PyUnicode_AsKind(str1, rkind);
10353 if (!buf1) goto error;
10354 release1 = 1;
10355 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010356 u = PyUnicode_New(slen, maxchar);
10357 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010359 assert(PyUnicode_KIND(u) == rkind);
10360 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010361
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010362 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010363 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010364 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010366 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010368
10369 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010370 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010371 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010373 if (i == -1)
10374 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010375 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010377 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010379 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010381 }
10382 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010384 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 int rkind = skind;
10386 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010389 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 buf1 = _PyUnicode_AsKind(str1, rkind);
10391 if (!buf1) goto error;
10392 release1 = 1;
10393 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010394 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010395 if (n == 0)
10396 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010398 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 buf2 = _PyUnicode_AsKind(str2, rkind);
10400 if (!buf2) goto error;
10401 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010404 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 rkind = kind2;
10406 sbuf = _PyUnicode_AsKind(self, rkind);
10407 if (!sbuf) goto error;
10408 srelease = 1;
10409 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010410 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 buf1 = _PyUnicode_AsKind(str1, rkind);
10412 if (!buf1) goto error;
10413 release1 = 1;
10414 }
10415 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10416 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010417 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 PyErr_SetString(PyExc_OverflowError,
10419 "replace string is too long");
10420 goto error;
10421 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010422 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010423 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010424 _Py_INCREF_UNICODE_EMPTY();
10425 if (!unicode_empty)
10426 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010427 u = unicode_empty;
10428 goto done;
10429 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010430 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 PyErr_SetString(PyExc_OverflowError,
10432 "replace string is too long");
10433 goto error;
10434 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010435 u = PyUnicode_New(new_size, maxchar);
10436 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 assert(PyUnicode_KIND(u) == rkind);
10439 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 ires = i = 0;
10441 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 while (n-- > 0) {
10443 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010444 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010445 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010446 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010447 if (j == -1)
10448 break;
10449 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010450 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010451 memcpy(res + rkind * ires,
10452 sbuf + rkind * i,
10453 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010455 }
10456 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010460 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010464 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010466 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010467 memcpy(res + rkind * ires,
10468 sbuf + rkind * i,
10469 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010470 }
10471 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010472 /* interleave */
10473 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010474 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010476 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010478 if (--n <= 0)
10479 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010480 memcpy(res + rkind * ires,
10481 sbuf + rkind * i,
10482 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 ires++;
10484 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010485 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010486 memcpy(res + rkind * ires,
10487 sbuf + rkind * i,
10488 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 }
10491
10492 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010493 unicode_adjust_maxchar(&u);
10494 if (u == NULL)
10495 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010496 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010497
10498 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (srelease)
10500 PyMem_FREE(sbuf);
10501 if (release1)
10502 PyMem_FREE(buf1);
10503 if (release2)
10504 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010505 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010507
Benjamin Peterson29060642009-01-31 22:14:21 +000010508 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010509 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 if (srelease)
10511 PyMem_FREE(sbuf);
10512 if (release1)
10513 PyMem_FREE(buf1);
10514 if (release2)
10515 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010516 return unicode_result_unchanged(self);
10517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 error:
10519 if (srelease && sbuf)
10520 PyMem_FREE(sbuf);
10521 if (release1 && buf1)
10522 PyMem_FREE(buf1);
10523 if (release2 && buf2)
10524 PyMem_FREE(buf2);
10525 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526}
10527
10528/* --- Unicode Object Methods --------------------------------------------- */
10529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010530PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010531 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010532\n\
10533Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010534characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535
10536static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010537unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010538{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010539 if (PyUnicode_READY(self) == -1)
10540 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010541 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542}
10543
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010544PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010545 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546\n\
10547Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010548have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549
10550static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010551unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010553 if (PyUnicode_READY(self) == -1)
10554 return NULL;
10555 if (PyUnicode_GET_LENGTH(self) == 0)
10556 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010557 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558}
10559
Benjamin Petersond5890c82012-01-14 13:23:30 -050010560PyDoc_STRVAR(casefold__doc__,
10561 "S.casefold() -> str\n\
10562\n\
10563Return a version of S suitable for caseless comparisons.");
10564
10565static PyObject *
10566unicode_casefold(PyObject *self)
10567{
10568 if (PyUnicode_READY(self) == -1)
10569 return NULL;
10570 if (PyUnicode_IS_ASCII(self))
10571 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010572 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010573}
10574
10575
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010576/* Argument converter. Coerces to a single unicode character */
10577
10578static int
10579convert_uc(PyObject *obj, void *addr)
10580{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010582 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010583
Benjamin Peterson14339b62009-01-31 16:36:08 +000010584 uniobj = PyUnicode_FromObject(obj);
10585 if (uniobj == NULL) {
10586 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010587 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010588 return 0;
10589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010591 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010592 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010593 Py_DECREF(uniobj);
10594 return 0;
10595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010597 Py_DECREF(uniobj);
10598 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010599}
10600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010601PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010602 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010603\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010604Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010605done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606
10607static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010608unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010610 Py_ssize_t marg, left;
10611 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 Py_UCS4 fillchar = ' ';
10613
Victor Stinnere9a29352011-10-01 02:14:59 +020010614 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616
Benjamin Petersonbac79492012-01-14 13:34:47 -050010617 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618 return NULL;
10619
Victor Stinnerc4b49542011-12-11 22:44:26 +010010620 if (PyUnicode_GET_LENGTH(self) >= width)
10621 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622
Victor Stinnerc4b49542011-12-11 22:44:26 +010010623 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624 left = marg / 2 + (marg & width & 1);
10625
Victor Stinner9310abb2011-10-05 00:59:23 +020010626 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627}
10628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629/* This function assumes that str1 and str2 are readied by the caller. */
10630
Marc-André Lemburge5034372000-08-08 08:04:29 +000010631static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010632unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010633{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010634#define COMPARE(TYPE1, TYPE2) \
10635 do { \
10636 TYPE1* p1 = (TYPE1 *)data1; \
10637 TYPE2* p2 = (TYPE2 *)data2; \
10638 TYPE1* end = p1 + len; \
10639 Py_UCS4 c1, c2; \
10640 for (; p1 != end; p1++, p2++) { \
10641 c1 = *p1; \
10642 c2 = *p2; \
10643 if (c1 != c2) \
10644 return (c1 < c2) ? -1 : 1; \
10645 } \
10646 } \
10647 while (0)
10648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 int kind1, kind2;
10650 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010651 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 kind1 = PyUnicode_KIND(str1);
10654 kind2 = PyUnicode_KIND(str2);
10655 data1 = PyUnicode_DATA(str1);
10656 data2 = PyUnicode_DATA(str2);
10657 len1 = PyUnicode_GET_LENGTH(str1);
10658 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010659 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010660
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010661 switch(kind1) {
10662 case PyUnicode_1BYTE_KIND:
10663 {
10664 switch(kind2) {
10665 case PyUnicode_1BYTE_KIND:
10666 {
10667 int cmp = memcmp(data1, data2, len);
10668 /* normalize result of memcmp() into the range [-1; 1] */
10669 if (cmp < 0)
10670 return -1;
10671 if (cmp > 0)
10672 return 1;
10673 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010674 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010675 case PyUnicode_2BYTE_KIND:
10676 COMPARE(Py_UCS1, Py_UCS2);
10677 break;
10678 case PyUnicode_4BYTE_KIND:
10679 COMPARE(Py_UCS1, Py_UCS4);
10680 break;
10681 default:
10682 assert(0);
10683 }
10684 break;
10685 }
10686 case PyUnicode_2BYTE_KIND:
10687 {
10688 switch(kind2) {
10689 case PyUnicode_1BYTE_KIND:
10690 COMPARE(Py_UCS2, Py_UCS1);
10691 break;
10692 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010693 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010694 COMPARE(Py_UCS2, Py_UCS2);
10695 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010696 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010697 case PyUnicode_4BYTE_KIND:
10698 COMPARE(Py_UCS2, Py_UCS4);
10699 break;
10700 default:
10701 assert(0);
10702 }
10703 break;
10704 }
10705 case PyUnicode_4BYTE_KIND:
10706 {
10707 switch(kind2) {
10708 case PyUnicode_1BYTE_KIND:
10709 COMPARE(Py_UCS4, Py_UCS1);
10710 break;
10711 case PyUnicode_2BYTE_KIND:
10712 COMPARE(Py_UCS4, Py_UCS2);
10713 break;
10714 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010715 {
10716#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10717 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10718 /* normalize result of wmemcmp() into the range [-1; 1] */
10719 if (cmp < 0)
10720 return -1;
10721 if (cmp > 0)
10722 return 1;
10723#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010724 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010725#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010726 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010727 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010728 default:
10729 assert(0);
10730 }
10731 break;
10732 }
10733 default:
10734 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010735 }
10736
Victor Stinner770e19e2012-10-04 22:59:45 +020010737 if (len1 == len2)
10738 return 0;
10739 if (len1 < len2)
10740 return -1;
10741 else
10742 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010743
10744#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010745}
10746
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010747Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010748unicode_compare_eq(PyObject *str1, PyObject *str2)
10749{
10750 int kind;
10751 void *data1, *data2;
10752 Py_ssize_t len;
10753 int cmp;
10754
Victor Stinnere5567ad2012-10-23 02:48:49 +020010755 len = PyUnicode_GET_LENGTH(str1);
10756 if (PyUnicode_GET_LENGTH(str2) != len)
10757 return 0;
10758 kind = PyUnicode_KIND(str1);
10759 if (PyUnicode_KIND(str2) != kind)
10760 return 0;
10761 data1 = PyUnicode_DATA(str1);
10762 data2 = PyUnicode_DATA(str2);
10763
10764 cmp = memcmp(data1, data2, len * kind);
10765 return (cmp == 0);
10766}
10767
10768
Alexander Belopolsky40018472011-02-26 01:02:56 +000010769int
10770PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10773 if (PyUnicode_READY(left) == -1 ||
10774 PyUnicode_READY(right) == -1)
10775 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010776
10777 /* a string is equal to itself */
10778 if (left == right)
10779 return 0;
10780
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010781 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010783 PyErr_Format(PyExc_TypeError,
10784 "Can't compare %.100s and %.100s",
10785 left->ob_type->tp_name,
10786 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010787 return -1;
10788}
10789
Martin v. Löwis5b222132007-06-10 09:51:05 +000010790int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010791_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10792{
10793 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10794 if (right_str == NULL)
10795 return -1;
10796 return PyUnicode_Compare(left, right_str);
10797}
10798
10799int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010800PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10801{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 Py_ssize_t i;
10803 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 Py_UCS4 chr;
10805
Victor Stinner910337b2011-10-03 03:20:16 +020010806 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 if (PyUnicode_READY(uni) == -1)
10808 return -1;
10809 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010810 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010811 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010812 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010813 size_t len, len2 = strlen(str);
10814 int cmp;
10815
10816 len = Py_MIN(len1, len2);
10817 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010818 if (cmp != 0) {
10819 if (cmp < 0)
10820 return -1;
10821 else
10822 return 1;
10823 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010824 if (len1 > len2)
10825 return 1; /* uni is longer */
10826 if (len2 > len1)
10827 return -1; /* str is longer */
10828 return 0;
10829 }
10830 else {
10831 void *data = PyUnicode_DATA(uni);
10832 /* Compare Unicode string and source character set string */
10833 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010834 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010835 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10836 /* This check keeps Python strings that end in '\0' from comparing equal
10837 to C strings identical up to that point. */
10838 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10839 return 1; /* uni is longer */
10840 if (str[i])
10841 return -1; /* str is longer */
10842 return 0;
10843 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010844}
10845
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010846
Benjamin Peterson29060642009-01-31 22:14:21 +000010847#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010848 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010849
Alexander Belopolsky40018472011-02-26 01:02:56 +000010850PyObject *
10851PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010852{
10853 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010854 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010855
Victor Stinnere5567ad2012-10-23 02:48:49 +020010856 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10857 Py_RETURN_NOTIMPLEMENTED;
10858
10859 if (PyUnicode_READY(left) == -1 ||
10860 PyUnicode_READY(right) == -1)
10861 return NULL;
10862
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010863 if (left == right) {
10864 switch (op) {
10865 case Py_EQ:
10866 case Py_LE:
10867 case Py_GE:
10868 /* a string is equal to itself */
10869 v = Py_True;
10870 break;
10871 case Py_NE:
10872 case Py_LT:
10873 case Py_GT:
10874 v = Py_False;
10875 break;
10876 default:
10877 PyErr_BadArgument();
10878 return NULL;
10879 }
10880 }
10881 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010882 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010883 result ^= (op == Py_NE);
10884 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010885 }
10886 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010887 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010888
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010889 /* Convert the return value to a Boolean */
10890 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010891 case Py_LE:
10892 v = TEST_COND(result <= 0);
10893 break;
10894 case Py_GE:
10895 v = TEST_COND(result >= 0);
10896 break;
10897 case Py_LT:
10898 v = TEST_COND(result == -1);
10899 break;
10900 case Py_GT:
10901 v = TEST_COND(result == 1);
10902 break;
10903 default:
10904 PyErr_BadArgument();
10905 return NULL;
10906 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010907 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010908 Py_INCREF(v);
10909 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010910}
10911
Alexander Belopolsky40018472011-02-26 01:02:56 +000010912int
10913PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010914{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010915 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010916 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010917 void *buf1, *buf2;
10918 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010919 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010920
10921 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010922 sub = PyUnicode_FromObject(element);
10923 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010924 PyErr_Format(PyExc_TypeError,
10925 "'in <string>' requires string as left operand, not %s",
10926 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010927 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010928 }
10929
Thomas Wouters477c8d52006-05-27 19:21:47 +000010930 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010931 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010932 Py_DECREF(sub);
10933 return -1;
10934 }
10935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010936 kind1 = PyUnicode_KIND(str);
10937 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 buf1 = PyUnicode_DATA(str);
10939 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010940 if (kind2 != kind1) {
10941 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010942 Py_DECREF(sub);
10943 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010944 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010945 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010946 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 if (!buf2) {
10949 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010950 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010951 return -1;
10952 }
10953 len1 = PyUnicode_GET_LENGTH(str);
10954 len2 = PyUnicode_GET_LENGTH(sub);
10955
Victor Stinner77282cb2013-04-14 19:22:47 +020010956 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 case PyUnicode_1BYTE_KIND:
10958 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10959 break;
10960 case PyUnicode_2BYTE_KIND:
10961 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10962 break;
10963 case PyUnicode_4BYTE_KIND:
10964 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10965 break;
10966 default:
10967 result = -1;
10968 assert(0);
10969 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010970
10971 Py_DECREF(str);
10972 Py_DECREF(sub);
10973
Victor Stinner77282cb2013-04-14 19:22:47 +020010974 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 PyMem_Free(buf2);
10976
Guido van Rossum403d68b2000-03-13 15:55:09 +000010977 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010978}
10979
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980/* Concat to string or Unicode object giving a new Unicode object. */
10981
Alexander Belopolsky40018472011-02-26 01:02:56 +000010982PyObject *
10983PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010985 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010986 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010987 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988
10989 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010995 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996
10997 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010998 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010999 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011002 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011003 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 }
11006
Victor Stinner488fa492011-12-12 00:01:39 +010011007 u_len = PyUnicode_GET_LENGTH(u);
11008 v_len = PyUnicode_GET_LENGTH(v);
11009 if (u_len > PY_SSIZE_T_MAX - v_len) {
11010 PyErr_SetString(PyExc_OverflowError,
11011 "strings are too large to concat");
11012 goto onError;
11013 }
11014 new_len = u_len + v_len;
11015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011017 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011018 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011019
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011021 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011023 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011024 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11025 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026 Py_DECREF(u);
11027 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011028 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011029 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030
Benjamin Peterson29060642009-01-31 22:14:21 +000011031 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032 Py_XDECREF(u);
11033 Py_XDECREF(v);
11034 return NULL;
11035}
11036
Walter Dörwald1ab83302007-05-18 17:15:44 +000011037void
Victor Stinner23e56682011-10-03 03:54:37 +020011038PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011039{
Victor Stinner23e56682011-10-03 03:54:37 +020011040 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011041 Py_UCS4 maxchar, maxchar2;
11042 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011043
11044 if (p_left == NULL) {
11045 if (!PyErr_Occurred())
11046 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011047 return;
11048 }
Victor Stinner23e56682011-10-03 03:54:37 +020011049 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011050 if (right == NULL || left == NULL
11051 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011052 if (!PyErr_Occurred())
11053 PyErr_BadInternalCall();
11054 goto error;
11055 }
11056
Benjamin Petersonbac79492012-01-14 13:34:47 -050011057 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011058 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011059 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011060 goto error;
11061
Victor Stinner488fa492011-12-12 00:01:39 +010011062 /* Shortcuts */
11063 if (left == unicode_empty) {
11064 Py_DECREF(left);
11065 Py_INCREF(right);
11066 *p_left = right;
11067 return;
11068 }
11069 if (right == unicode_empty)
11070 return;
11071
11072 left_len = PyUnicode_GET_LENGTH(left);
11073 right_len = PyUnicode_GET_LENGTH(right);
11074 if (left_len > PY_SSIZE_T_MAX - right_len) {
11075 PyErr_SetString(PyExc_OverflowError,
11076 "strings are too large to concat");
11077 goto error;
11078 }
11079 new_len = left_len + right_len;
11080
11081 if (unicode_modifiable(left)
11082 && PyUnicode_CheckExact(right)
11083 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011084 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11085 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011086 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011087 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011088 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11089 {
11090 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011091 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011092 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011093
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011094 /* copy 'right' into the newly allocated area of 'left' */
11095 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011096 }
Victor Stinner488fa492011-12-12 00:01:39 +010011097 else {
11098 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11099 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011100 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011101
Victor Stinner488fa492011-12-12 00:01:39 +010011102 /* Concat the two Unicode strings */
11103 res = PyUnicode_New(new_len, maxchar);
11104 if (res == NULL)
11105 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011106 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11107 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011108 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011109 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011110 }
11111 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011112 return;
11113
11114error:
Victor Stinner488fa492011-12-12 00:01:39 +010011115 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011116}
11117
11118void
11119PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11120{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011121 PyUnicode_Append(pleft, right);
11122 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011123}
11124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011125PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011128Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011129string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131
11132static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011133unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011135 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011136 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011137 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139 int kind1, kind2, kind;
11140 void *buf1, *buf2;
11141 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142
Jesus Ceaac451502011-04-20 17:09:23 +020011143 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11144 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011145 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 kind1 = PyUnicode_KIND(self);
11148 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011149 if (kind2 > kind1) {
11150 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011151 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011152 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011153 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154 buf1 = PyUnicode_DATA(self);
11155 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011157 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 if (!buf2) {
11159 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 return NULL;
11161 }
11162 len1 = PyUnicode_GET_LENGTH(self);
11163 len2 = PyUnicode_GET_LENGTH(substring);
11164
11165 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011166 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 case PyUnicode_1BYTE_KIND:
11168 iresult = ucs1lib_count(
11169 ((Py_UCS1*)buf1) + start, end - start,
11170 buf2, len2, PY_SSIZE_T_MAX
11171 );
11172 break;
11173 case PyUnicode_2BYTE_KIND:
11174 iresult = ucs2lib_count(
11175 ((Py_UCS2*)buf1) + start, end - start,
11176 buf2, len2, PY_SSIZE_T_MAX
11177 );
11178 break;
11179 case PyUnicode_4BYTE_KIND:
11180 iresult = ucs4lib_count(
11181 ((Py_UCS4*)buf1) + start, end - start,
11182 buf2, len2, PY_SSIZE_T_MAX
11183 );
11184 break;
11185 default:
11186 assert(0); iresult = 0;
11187 }
11188
11189 result = PyLong_FromSsize_t(iresult);
11190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 if (kind2 != kind)
11192 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193
11194 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011195
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 return result;
11197}
11198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011199PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011200 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011202Encode S using the codec registered for encoding. Default encoding\n\
11203is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011204handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011205a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11206'xmlcharrefreplace' as well as any other name registered with\n\
11207codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
11209static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011210unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011212 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213 char *encoding = NULL;
11214 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011215
Benjamin Peterson308d6372009-09-18 21:42:35 +000011216 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11217 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011219 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011220}
11221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011222PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011223 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224\n\
11225Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011226If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
11228static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011229unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011231 Py_ssize_t i, j, line_pos, src_len, incr;
11232 Py_UCS4 ch;
11233 PyObject *u;
11234 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011235 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011237 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011238 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239
Ezio Melotti745d54d2013-11-16 19:10:57 +020011240 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11241 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243
Antoine Pitrou22425222011-10-04 19:10:51 +020011244 if (PyUnicode_READY(self) == -1)
11245 return NULL;
11246
Thomas Wouters7e474022000-07-16 12:04:32 +000011247 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 src_len = PyUnicode_GET_LENGTH(self);
11249 i = j = line_pos = 0;
11250 kind = PyUnicode_KIND(self);
11251 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011252 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011253 for (; i < src_len; i++) {
11254 ch = PyUnicode_READ(kind, src_data, i);
11255 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011256 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011257 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011258 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 goto overflow;
11261 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011263 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011264 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011267 goto overflow;
11268 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011270 if (ch == '\n' || ch == '\r')
11271 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011273 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011274 if (!found)
11275 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011276
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279 if (!u)
11280 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011281 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Antoine Pitroue71d5742011-10-04 15:55:09 +020011283 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284
Antoine Pitroue71d5742011-10-04 15:55:09 +020011285 for (; i < src_len; i++) {
11286 ch = PyUnicode_READ(kind, src_data, i);
11287 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011289 incr = tabsize - (line_pos % tabsize);
11290 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011291 FILL(kind, dest_data, ' ', j, incr);
11292 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011293 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011294 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011295 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011296 line_pos++;
11297 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011298 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011299 if (ch == '\n' || ch == '\r')
11300 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011302 }
11303 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011304 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011305
Antoine Pitroue71d5742011-10-04 15:55:09 +020011306 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011307 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309}
11310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011311PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011312 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313\n\
11314Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011315such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316arguments start and end are interpreted as in slice notation.\n\
11317\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011318Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319
11320static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011323 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011324 Py_ssize_t start;
11325 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011326 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327
Jesus Ceaac451502011-04-20 17:09:23 +020011328 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11329 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331
Christian Heimesd47802e2013-06-29 21:33:36 +020011332 if (PyUnicode_READY(self) == -1) {
11333 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011335 }
11336 if (PyUnicode_READY(substring) == -1) {
11337 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340
Victor Stinner7931d9a2011-11-04 00:22:48 +010011341 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
11343 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (result == -2)
11346 return NULL;
11347
Christian Heimes217cfd12007-12-02 14:31:20 +000011348 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349}
11350
11351static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011352unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011354 void *data;
11355 enum PyUnicode_Kind kind;
11356 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011357
11358 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11359 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011361 }
11362 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11363 PyErr_SetString(PyExc_IndexError, "string index out of range");
11364 return NULL;
11365 }
11366 kind = PyUnicode_KIND(self);
11367 data = PyUnicode_DATA(self);
11368 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011369 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370}
11371
Guido van Rossumc2504932007-09-18 19:42:40 +000011372/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011373 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011374static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011375unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376{
Guido van Rossumc2504932007-09-18 19:42:40 +000011377 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011378 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011379
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011380#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011381 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011382#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 if (_PyUnicode_HASH(self) != -1)
11384 return _PyUnicode_HASH(self);
11385 if (PyUnicode_READY(self) == -1)
11386 return -1;
11387 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011388 /*
11389 We make the hash of the empty string be 0, rather than using
11390 (prefix ^ suffix), since this slightly obfuscates the hash secret
11391 */
11392 if (len == 0) {
11393 _PyUnicode_HASH(self) = 0;
11394 return 0;
11395 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011396 x = _Py_HashBytes(PyUnicode_DATA(self),
11397 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011399 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400}
11401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011402PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011405Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406
11407static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011410 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011411 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011412 Py_ssize_t start;
11413 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414
Jesus Ceaac451502011-04-20 17:09:23 +020011415 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11416 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418
Christian Heimesd47a0452013-06-29 21:21:37 +020011419 if (PyUnicode_READY(self) == -1) {
11420 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011422 }
11423 if (PyUnicode_READY(substring) == -1) {
11424 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427
Victor Stinner7931d9a2011-11-04 00:22:48 +010011428 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
11430 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 if (result == -2)
11433 return NULL;
11434
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 if (result < 0) {
11436 PyErr_SetString(PyExc_ValueError, "substring not found");
11437 return NULL;
11438 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011439
Christian Heimes217cfd12007-12-02 14:31:20 +000011440 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441}
11442
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011443PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011446Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011447at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448
11449static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011450unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 Py_ssize_t i, length;
11453 int kind;
11454 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455 int cased;
11456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 if (PyUnicode_READY(self) == -1)
11458 return NULL;
11459 length = PyUnicode_GET_LENGTH(self);
11460 kind = PyUnicode_KIND(self);
11461 data = PyUnicode_DATA(self);
11462
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (length == 1)
11465 return PyBool_FromLong(
11466 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011468 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011471
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 for (i = 0; i < length; i++) {
11474 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011475
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11477 return PyBool_FromLong(0);
11478 else if (!cased && Py_UNICODE_ISLOWER(ch))
11479 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011481 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482}
11483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011484PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011487Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011488at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489
11490static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011491unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 Py_ssize_t i, length;
11494 int kind;
11495 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 int cased;
11497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 if (PyUnicode_READY(self) == -1)
11499 return NULL;
11500 length = PyUnicode_GET_LENGTH(self);
11501 kind = PyUnicode_KIND(self);
11502 data = PyUnicode_DATA(self);
11503
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (length == 1)
11506 return PyBool_FromLong(
11507 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011509 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011512
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 for (i = 0; i < length; i++) {
11515 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011516
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11518 return PyBool_FromLong(0);
11519 else if (!cased && Py_UNICODE_ISUPPER(ch))
11520 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011522 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523}
11524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011525PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011526 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011528Return True if S is a titlecased string and there is at least one\n\
11529character in S, i.e. upper- and titlecase characters may only\n\
11530follow uncased characters and lowercase characters only cased ones.\n\
11531Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
11533static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011534unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 Py_ssize_t i, length;
11537 int kind;
11538 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539 int cased, previous_is_cased;
11540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 if (PyUnicode_READY(self) == -1)
11542 return NULL;
11543 length = PyUnicode_GET_LENGTH(self);
11544 kind = PyUnicode_KIND(self);
11545 data = PyUnicode_DATA(self);
11546
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 if (length == 1) {
11549 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11550 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11551 (Py_UNICODE_ISUPPER(ch) != 0));
11552 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011554 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011556 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011557
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 cased = 0;
11559 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 for (i = 0; i < length; i++) {
11561 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011562
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11564 if (previous_is_cased)
11565 return PyBool_FromLong(0);
11566 previous_is_cased = 1;
11567 cased = 1;
11568 }
11569 else if (Py_UNICODE_ISLOWER(ch)) {
11570 if (!previous_is_cased)
11571 return PyBool_FromLong(0);
11572 previous_is_cased = 1;
11573 cased = 1;
11574 }
11575 else
11576 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011578 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579}
11580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011581PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011582 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011584Return True if all characters in S are whitespace\n\
11585and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586
11587static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011588unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 Py_ssize_t i, length;
11591 int kind;
11592 void *data;
11593
11594 if (PyUnicode_READY(self) == -1)
11595 return NULL;
11596 length = PyUnicode_GET_LENGTH(self);
11597 kind = PyUnicode_KIND(self);
11598 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 if (length == 1)
11602 return PyBool_FromLong(
11603 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011605 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011609 for (i = 0; i < length; i++) {
11610 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011611 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011612 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011614 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615}
11616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011617PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011619\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011620Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011621and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011622
11623static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011624unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011625{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 Py_ssize_t i, length;
11627 int kind;
11628 void *data;
11629
11630 if (PyUnicode_READY(self) == -1)
11631 return NULL;
11632 length = PyUnicode_GET_LENGTH(self);
11633 kind = PyUnicode_KIND(self);
11634 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011635
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011636 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 if (length == 1)
11638 return PyBool_FromLong(
11639 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011640
11641 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011643 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 for (i = 0; i < length; i++) {
11646 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011647 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011648 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011649 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011650}
11651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011652PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011653 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011654\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011655Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011656and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011657
11658static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011659unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 int kind;
11662 void *data;
11663 Py_ssize_t len, i;
11664
11665 if (PyUnicode_READY(self) == -1)
11666 return NULL;
11667
11668 kind = PyUnicode_KIND(self);
11669 data = PyUnicode_DATA(self);
11670 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011671
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011672 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 if (len == 1) {
11674 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11675 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11676 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011677
11678 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011680 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682 for (i = 0; i < len; i++) {
11683 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011684 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011685 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011686 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011687 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688}
11689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011690PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011693Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011694False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695
11696static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011697unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011699 Py_ssize_t i, length;
11700 int kind;
11701 void *data;
11702
11703 if (PyUnicode_READY(self) == -1)
11704 return NULL;
11705 length = PyUnicode_GET_LENGTH(self);
11706 kind = PyUnicode_KIND(self);
11707 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 if (length == 1)
11711 return PyBool_FromLong(
11712 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011714 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011716 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011717
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 for (i = 0; i < length; i++) {
11719 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011720 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011722 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723}
11724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011725PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011726 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011728Return True if all characters in S are digits\n\
11729and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730
11731static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011732unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 Py_ssize_t i, length;
11735 int kind;
11736 void *data;
11737
11738 if (PyUnicode_READY(self) == -1)
11739 return NULL;
11740 length = PyUnicode_GET_LENGTH(self);
11741 kind = PyUnicode_KIND(self);
11742 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 if (length == 1) {
11746 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11747 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11748 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011750 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011752 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 for (i = 0; i < length; i++) {
11755 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011758 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759}
11760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011761PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011762 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011764Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011765False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766
11767static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011768unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 Py_ssize_t i, length;
11771 int kind;
11772 void *data;
11773
11774 if (PyUnicode_READY(self) == -1)
11775 return NULL;
11776 length = PyUnicode_GET_LENGTH(self);
11777 kind = PyUnicode_KIND(self);
11778 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 if (length == 1)
11782 return PyBool_FromLong(
11783 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011785 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011787 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011789 for (i = 0; i < length; i++) {
11790 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011791 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011793 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794}
11795
Martin v. Löwis47383402007-08-15 07:32:56 +000011796int
11797PyUnicode_IsIdentifier(PyObject *self)
11798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 int kind;
11800 void *data;
11801 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011802 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 if (PyUnicode_READY(self) == -1) {
11805 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011806 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 }
11808
11809 /* Special case for empty strings */
11810 if (PyUnicode_GET_LENGTH(self) == 0)
11811 return 0;
11812 kind = PyUnicode_KIND(self);
11813 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011814
11815 /* PEP 3131 says that the first character must be in
11816 XID_Start and subsequent characters in XID_Continue,
11817 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011818 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011819 letters, digits, underscore). However, given the current
11820 definition of XID_Start and XID_Continue, it is sufficient
11821 to check just for these, except that _ must be allowed
11822 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011824 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011825 return 0;
11826
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011827 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011828 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011830 return 1;
11831}
11832
11833PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011834 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011835\n\
11836Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011837to the language definition.\n\
11838\n\
11839Use keyword.iskeyword() to test for reserved identifiers\n\
11840such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011841
11842static PyObject*
11843unicode_isidentifier(PyObject *self)
11844{
11845 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11846}
11847
Georg Brandl559e5d72008-06-11 18:37:52 +000011848PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011849 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011850\n\
11851Return True if all characters in S are considered\n\
11852printable in repr() or S is empty, False otherwise.");
11853
11854static PyObject*
11855unicode_isprintable(PyObject *self)
11856{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 Py_ssize_t i, length;
11858 int kind;
11859 void *data;
11860
11861 if (PyUnicode_READY(self) == -1)
11862 return NULL;
11863 length = PyUnicode_GET_LENGTH(self);
11864 kind = PyUnicode_KIND(self);
11865 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011866
11867 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011868 if (length == 1)
11869 return PyBool_FromLong(
11870 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 for (i = 0; i < length; i++) {
11873 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011874 Py_RETURN_FALSE;
11875 }
11876 }
11877 Py_RETURN_TRUE;
11878}
11879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011880PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011881 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882\n\
11883Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011884iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
11886static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011887unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011889 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890}
11891
Martin v. Löwis18e16552006-02-15 17:27:45 +000011892static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011893unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 if (PyUnicode_READY(self) == -1)
11896 return -1;
11897 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898}
11899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011900PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011901 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011903Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011904done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905
11906static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011907unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011909 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 Py_UCS4 fillchar = ' ';
11911
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011912 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913 return NULL;
11914
Benjamin Petersonbac79492012-01-14 13:34:47 -050011915 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917
Victor Stinnerc4b49542011-12-11 22:44:26 +010011918 if (PyUnicode_GET_LENGTH(self) >= width)
11919 return unicode_result_unchanged(self);
11920
11921 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922}
11923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011924PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011927Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928
11929static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011930unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011932 if (PyUnicode_READY(self) == -1)
11933 return NULL;
11934 if (PyUnicode_IS_ASCII(self))
11935 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011936 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937}
11938
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011939#define LEFTSTRIP 0
11940#define RIGHTSTRIP 1
11941#define BOTHSTRIP 2
11942
11943/* Arrays indexed by above */
11944static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11945
11946#define STRIPNAME(i) (stripformat[i]+3)
11947
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011948/* externally visible for str.strip(unicode) */
11949PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011950_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 void *data;
11953 int kind;
11954 Py_ssize_t i, j, len;
11955 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011956 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011958 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11959 return NULL;
11960
11961 kind = PyUnicode_KIND(self);
11962 data = PyUnicode_DATA(self);
11963 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011964 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011965 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11966 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011967 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011968
Benjamin Peterson14339b62009-01-31 16:36:08 +000011969 i = 0;
11970 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011971 while (i < len) {
11972 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11973 if (!BLOOM(sepmask, ch))
11974 break;
11975 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11976 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011977 i++;
11978 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011979 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011980
Benjamin Peterson14339b62009-01-31 16:36:08 +000011981 j = len;
11982 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011983 j--;
11984 while (j >= i) {
11985 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11986 if (!BLOOM(sepmask, ch))
11987 break;
11988 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11989 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011990 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011991 }
11992
Benjamin Peterson29060642009-01-31 22:14:21 +000011993 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011994 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011995
Victor Stinner7931d9a2011-11-04 00:22:48 +010011996 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997}
11998
11999PyObject*
12000PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12001{
12002 unsigned char *data;
12003 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012004 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012005
Victor Stinnerde636f32011-10-01 03:55:54 +020012006 if (PyUnicode_READY(self) == -1)
12007 return NULL;
12008
Victor Stinner684d5fd2012-05-03 02:32:34 +020012009 length = PyUnicode_GET_LENGTH(self);
12010 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012011
Victor Stinner684d5fd2012-05-03 02:32:34 +020012012 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012013 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014
Victor Stinnerde636f32011-10-01 03:55:54 +020012015 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012016 PyErr_SetString(PyExc_IndexError, "string index out of range");
12017 return NULL;
12018 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012019 if (start >= length || end < start)
12020 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012021
Victor Stinner684d5fd2012-05-03 02:32:34 +020012022 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012023 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012024 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012025 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012026 }
12027 else {
12028 kind = PyUnicode_KIND(self);
12029 data = PyUnicode_1BYTE_DATA(self);
12030 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012031 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012032 length);
12033 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035
12036static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012037do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 Py_ssize_t len, i, j;
12040
12041 if (PyUnicode_READY(self) == -1)
12042 return NULL;
12043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012045
Victor Stinnercc7af722013-04-09 22:39:24 +020012046 if (PyUnicode_IS_ASCII(self)) {
12047 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12048
12049 i = 0;
12050 if (striptype != RIGHTSTRIP) {
12051 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012052 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012053 if (!_Py_ascii_whitespace[ch])
12054 break;
12055 i++;
12056 }
12057 }
12058
12059 j = len;
12060 if (striptype != LEFTSTRIP) {
12061 j--;
12062 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012063 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012064 if (!_Py_ascii_whitespace[ch])
12065 break;
12066 j--;
12067 }
12068 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012069 }
12070 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012071 else {
12072 int kind = PyUnicode_KIND(self);
12073 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012074
Victor Stinnercc7af722013-04-09 22:39:24 +020012075 i = 0;
12076 if (striptype != RIGHTSTRIP) {
12077 while (i < len) {
12078 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12079 if (!Py_UNICODE_ISSPACE(ch))
12080 break;
12081 i++;
12082 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012083 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012084
12085 j = len;
12086 if (striptype != LEFTSTRIP) {
12087 j--;
12088 while (j >= i) {
12089 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12090 if (!Py_UNICODE_ISSPACE(ch))
12091 break;
12092 j--;
12093 }
12094 j++;
12095 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012096 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012097
Victor Stinner7931d9a2011-11-04 00:22:48 +010012098 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099}
12100
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012101
12102static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012103do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012104{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012105 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012106
Serhiy Storchakac6792272013-10-19 21:03:34 +030012107 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012108 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012109
Benjamin Peterson14339b62009-01-31 16:36:08 +000012110 if (sep != NULL && sep != Py_None) {
12111 if (PyUnicode_Check(sep))
12112 return _PyUnicode_XStrip(self, striptype, sep);
12113 else {
12114 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012115 "%s arg must be None or str",
12116 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012117 return NULL;
12118 }
12119 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012120
Benjamin Peterson14339b62009-01-31 16:36:08 +000012121 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122}
12123
12124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012125PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012126 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012127\n\
12128Return a copy of the string S with leading and trailing\n\
12129whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012130If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131
12132static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012133unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012134{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 if (PyTuple_GET_SIZE(args) == 0)
12136 return do_strip(self, BOTHSTRIP); /* Common case */
12137 else
12138 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012139}
12140
12141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012142PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012143 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012144\n\
12145Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012146If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012147
12148static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012149unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012150{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012151 if (PyTuple_GET_SIZE(args) == 0)
12152 return do_strip(self, LEFTSTRIP); /* Common case */
12153 else
12154 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012155}
12156
12157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012158PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012160\n\
12161Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012162If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012163
12164static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012165unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012167 if (PyTuple_GET_SIZE(args) == 0)
12168 return do_strip(self, RIGHTSTRIP); /* Common case */
12169 else
12170 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012171}
12172
12173
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012175unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012177 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
Serhiy Storchaka05997252013-01-26 12:14:02 +020012180 if (len < 1)
12181 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182
Victor Stinnerc4b49542011-12-11 22:44:26 +010012183 /* no repeat, return original string */
12184 if (len == 1)
12185 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012186
Benjamin Petersonbac79492012-01-14 13:34:47 -050012187 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188 return NULL;
12189
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012190 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012191 PyErr_SetString(PyExc_OverflowError,
12192 "repeated string is too long");
12193 return NULL;
12194 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012196
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012197 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198 if (!u)
12199 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012200 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 if (PyUnicode_GET_LENGTH(str) == 1) {
12203 const int kind = PyUnicode_KIND(str);
12204 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012205 if (kind == PyUnicode_1BYTE_KIND) {
12206 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012207 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012208 }
12209 else if (kind == PyUnicode_2BYTE_KIND) {
12210 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012211 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012212 ucs2[n] = fill_char;
12213 } else {
12214 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12215 assert(kind == PyUnicode_4BYTE_KIND);
12216 for (n = 0; n < len; ++n)
12217 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012218 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 }
12220 else {
12221 /* number of characters copied this far */
12222 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012223 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012224 char *to = (char *) PyUnicode_DATA(u);
12225 Py_MEMCPY(to, PyUnicode_DATA(str),
12226 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012227 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012228 n = (done <= nchars-done) ? done : nchars-done;
12229 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012230 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012231 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 }
12233
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012234 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012235 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236}
12237
Alexander Belopolsky40018472011-02-26 01:02:56 +000012238PyObject *
12239PyUnicode_Replace(PyObject *obj,
12240 PyObject *subobj,
12241 PyObject *replobj,
12242 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243{
12244 PyObject *self;
12245 PyObject *str1;
12246 PyObject *str2;
12247 PyObject *result;
12248
12249 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012250 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012251 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012253 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 Py_DECREF(self);
12255 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256 }
12257 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012258 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012259 Py_DECREF(self);
12260 Py_DECREF(str1);
12261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012263 if (PyUnicode_READY(self) == -1 ||
12264 PyUnicode_READY(str1) == -1 ||
12265 PyUnicode_READY(str2) == -1)
12266 result = NULL;
12267 else
12268 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269 Py_DECREF(self);
12270 Py_DECREF(str1);
12271 Py_DECREF(str2);
12272 return result;
12273}
12274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012275PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012276 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277\n\
12278Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012279old replaced by new. If the optional argument count is\n\
12280given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281
12282static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285 PyObject *str1;
12286 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012287 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288 PyObject *result;
12289
Martin v. Löwis18e16552006-02-15 17:27:45 +000012290 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012292 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012293 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012295 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 return NULL;
12297 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012298 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012299 Py_DECREF(str1);
12300 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012301 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012302 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12303 result = NULL;
12304 else
12305 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306
12307 Py_DECREF(str1);
12308 Py_DECREF(str2);
12309 return result;
12310}
12311
Alexander Belopolsky40018472011-02-26 01:02:56 +000012312static PyObject *
12313unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012315 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 Py_ssize_t isize;
12317 Py_ssize_t osize, squote, dquote, i, o;
12318 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012319 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012323 return NULL;
12324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 isize = PyUnicode_GET_LENGTH(unicode);
12326 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 /* Compute length of output, quote characters, and
12329 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012330 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 max = 127;
12332 squote = dquote = 0;
12333 ikind = PyUnicode_KIND(unicode);
12334 for (i = 0; i < isize; i++) {
12335 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012336 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012338 case '\'': squote++; break;
12339 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012341 incr = 2;
12342 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 default:
12344 /* Fast-path ASCII */
12345 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012346 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012348 ;
12349 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012352 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012354 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012356 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012358 if (osize > PY_SSIZE_T_MAX - incr) {
12359 PyErr_SetString(PyExc_OverflowError,
12360 "string is too long to generate repr");
12361 return NULL;
12362 }
12363 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 }
12365
12366 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012367 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012369 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 if (dquote)
12371 /* Both squote and dquote present. Use squote,
12372 and escape them */
12373 osize += squote;
12374 else
12375 quote = '"';
12376 }
Victor Stinner55c08782013-04-14 18:45:39 +020012377 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378
12379 repr = PyUnicode_New(osize, max);
12380 if (repr == NULL)
12381 return NULL;
12382 okind = PyUnicode_KIND(repr);
12383 odata = PyUnicode_DATA(repr);
12384
12385 PyUnicode_WRITE(okind, odata, 0, quote);
12386 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012387 if (unchanged) {
12388 _PyUnicode_FastCopyCharacters(repr, 1,
12389 unicode, 0,
12390 isize);
12391 }
12392 else {
12393 for (i = 0, o = 1; i < isize; i++) {
12394 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395
Victor Stinner55c08782013-04-14 18:45:39 +020012396 /* Escape quotes and backslashes */
12397 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012398 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012400 continue;
12401 }
12402
12403 /* Map special whitespace to '\t', \n', '\r' */
12404 if (ch == '\t') {
12405 PyUnicode_WRITE(okind, odata, o++, '\\');
12406 PyUnicode_WRITE(okind, odata, o++, 't');
12407 }
12408 else if (ch == '\n') {
12409 PyUnicode_WRITE(okind, odata, o++, '\\');
12410 PyUnicode_WRITE(okind, odata, o++, 'n');
12411 }
12412 else if (ch == '\r') {
12413 PyUnicode_WRITE(okind, odata, o++, '\\');
12414 PyUnicode_WRITE(okind, odata, o++, 'r');
12415 }
12416
12417 /* Map non-printable US ASCII to '\xhh' */
12418 else if (ch < ' ' || ch == 0x7F) {
12419 PyUnicode_WRITE(okind, odata, o++, '\\');
12420 PyUnicode_WRITE(okind, odata, o++, 'x');
12421 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12422 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12423 }
12424
12425 /* Copy ASCII characters as-is */
12426 else if (ch < 0x7F) {
12427 PyUnicode_WRITE(okind, odata, o++, ch);
12428 }
12429
12430 /* Non-ASCII characters */
12431 else {
12432 /* Map Unicode whitespace and control characters
12433 (categories Z* and C* except ASCII space)
12434 */
12435 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12436 PyUnicode_WRITE(okind, odata, o++, '\\');
12437 /* Map 8-bit characters to '\xhh' */
12438 if (ch <= 0xff) {
12439 PyUnicode_WRITE(okind, odata, o++, 'x');
12440 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12441 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12442 }
12443 /* Map 16-bit characters to '\uxxxx' */
12444 else if (ch <= 0xffff) {
12445 PyUnicode_WRITE(okind, odata, o++, 'u');
12446 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12447 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12448 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12449 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12450 }
12451 /* Map 21-bit characters to '\U00xxxxxx' */
12452 else {
12453 PyUnicode_WRITE(okind, odata, o++, 'U');
12454 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12455 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12456 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12457 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12458 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12461 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12462 }
12463 }
12464 /* Copy characters as-is */
12465 else {
12466 PyUnicode_WRITE(okind, odata, o++, ch);
12467 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012468 }
12469 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012470 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012472 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012473 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474}
12475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012476PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012477 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478\n\
12479Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012480such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481arguments start and end are interpreted as in slice notation.\n\
12482\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012483Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484
12485static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012487{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012488 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012489 Py_ssize_t start;
12490 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012491 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492
Jesus Ceaac451502011-04-20 17:09:23 +020012493 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12494 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012495 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496
Christian Heimesea71a522013-06-29 21:17:34 +020012497 if (PyUnicode_READY(self) == -1) {
12498 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012499 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012500 }
12501 if (PyUnicode_READY(substring) == -1) {
12502 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012504 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505
Victor Stinner7931d9a2011-11-04 00:22:48 +010012506 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507
12508 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012510 if (result == -2)
12511 return NULL;
12512
Christian Heimes217cfd12007-12-02 14:31:20 +000012513 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514}
12515
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012516PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012517 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012519Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520
12521static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012524 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012525 Py_ssize_t start;
12526 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012527 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528
Jesus Ceaac451502011-04-20 17:09:23 +020012529 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12530 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012531 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532
Christian Heimesea71a522013-06-29 21:17:34 +020012533 if (PyUnicode_READY(self) == -1) {
12534 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012536 }
12537 if (PyUnicode_READY(substring) == -1) {
12538 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012540 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541
Victor Stinner7931d9a2011-11-04 00:22:48 +010012542 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543
12544 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 if (result == -2)
12547 return NULL;
12548
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549 if (result < 0) {
12550 PyErr_SetString(PyExc_ValueError, "substring not found");
12551 return NULL;
12552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553
Christian Heimes217cfd12007-12-02 14:31:20 +000012554 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555}
12556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012557PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012558 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012560Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012561done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562
12563static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012564unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012566 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 Py_UCS4 fillchar = ' ';
12568
Victor Stinnere9a29352011-10-01 02:14:59 +020012569 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012571
Benjamin Petersonbac79492012-01-14 13:34:47 -050012572 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573 return NULL;
12574
Victor Stinnerc4b49542011-12-11 22:44:26 +010012575 if (PyUnicode_GET_LENGTH(self) >= width)
12576 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577
Victor Stinnerc4b49542011-12-11 22:44:26 +010012578 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579}
12580
Alexander Belopolsky40018472011-02-26 01:02:56 +000012581PyObject *
12582PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583{
12584 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012585
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586 s = PyUnicode_FromObject(s);
12587 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012588 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012589 if (sep != NULL) {
12590 sep = PyUnicode_FromObject(sep);
12591 if (sep == NULL) {
12592 Py_DECREF(s);
12593 return NULL;
12594 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595 }
12596
Victor Stinner9310abb2011-10-05 00:59:23 +020012597 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598
12599 Py_DECREF(s);
12600 Py_XDECREF(sep);
12601 return result;
12602}
12603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012604PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012605 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606\n\
12607Return a list of the words in S, using sep as the\n\
12608delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012609splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012610whitespace string is a separator and empty strings are\n\
12611removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612
12613static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012614unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012616 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012618 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012620 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12621 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622 return NULL;
12623
12624 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012625 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012627 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012629 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630}
12631
Thomas Wouters477c8d52006-05-27 19:21:47 +000012632PyObject *
12633PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12634{
12635 PyObject* str_obj;
12636 PyObject* sep_obj;
12637 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012638 int kind1, kind2, kind;
12639 void *buf1 = NULL, *buf2 = NULL;
12640 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012641
12642 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012643 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012644 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012645 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012646 if (!sep_obj) {
12647 Py_DECREF(str_obj);
12648 return NULL;
12649 }
12650 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12651 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012652 Py_DECREF(str_obj);
12653 return NULL;
12654 }
12655
Victor Stinner14f8f022011-10-05 20:58:25 +020012656 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012658 kind = Py_MAX(kind1, kind2);
12659 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012661 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662 if (!buf1)
12663 goto onError;
12664 buf2 = PyUnicode_DATA(sep_obj);
12665 if (kind2 != kind)
12666 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12667 if (!buf2)
12668 goto onError;
12669 len1 = PyUnicode_GET_LENGTH(str_obj);
12670 len2 = PyUnicode_GET_LENGTH(sep_obj);
12671
Benjamin Petersonead6b532011-12-20 17:23:42 -060012672 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012673 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012674 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12675 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12676 else
12677 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678 break;
12679 case PyUnicode_2BYTE_KIND:
12680 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12681 break;
12682 case PyUnicode_4BYTE_KIND:
12683 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12684 break;
12685 default:
12686 assert(0);
12687 out = 0;
12688 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012689
12690 Py_DECREF(sep_obj);
12691 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 if (kind1 != kind)
12693 PyMem_Free(buf1);
12694 if (kind2 != kind)
12695 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012696
12697 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698 onError:
12699 Py_DECREF(sep_obj);
12700 Py_DECREF(str_obj);
12701 if (kind1 != kind && buf1)
12702 PyMem_Free(buf1);
12703 if (kind2 != kind && buf2)
12704 PyMem_Free(buf2);
12705 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012706}
12707
12708
12709PyObject *
12710PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12711{
12712 PyObject* str_obj;
12713 PyObject* sep_obj;
12714 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 int kind1, kind2, kind;
12716 void *buf1 = NULL, *buf2 = NULL;
12717 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012718
12719 str_obj = PyUnicode_FromObject(str_in);
12720 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012721 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012722 sep_obj = PyUnicode_FromObject(sep_in);
12723 if (!sep_obj) {
12724 Py_DECREF(str_obj);
12725 return NULL;
12726 }
12727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012728 kind1 = PyUnicode_KIND(str_in);
12729 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012730 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012731 buf1 = PyUnicode_DATA(str_in);
12732 if (kind1 != kind)
12733 buf1 = _PyUnicode_AsKind(str_in, kind);
12734 if (!buf1)
12735 goto onError;
12736 buf2 = PyUnicode_DATA(sep_obj);
12737 if (kind2 != kind)
12738 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12739 if (!buf2)
12740 goto onError;
12741 len1 = PyUnicode_GET_LENGTH(str_obj);
12742 len2 = PyUnicode_GET_LENGTH(sep_obj);
12743
Benjamin Petersonead6b532011-12-20 17:23:42 -060012744 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012746 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12747 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12748 else
12749 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 break;
12751 case PyUnicode_2BYTE_KIND:
12752 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12753 break;
12754 case PyUnicode_4BYTE_KIND:
12755 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12756 break;
12757 default:
12758 assert(0);
12759 out = 0;
12760 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012761
12762 Py_DECREF(sep_obj);
12763 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 if (kind1 != kind)
12765 PyMem_Free(buf1);
12766 if (kind2 != kind)
12767 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012768
12769 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012770 onError:
12771 Py_DECREF(sep_obj);
12772 Py_DECREF(str_obj);
12773 if (kind1 != kind && buf1)
12774 PyMem_Free(buf1);
12775 if (kind2 != kind && buf2)
12776 PyMem_Free(buf2);
12777 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012778}
12779
12780PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012781 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012782\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012783Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012784the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012785found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012786
12787static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012788unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012789{
Victor Stinner9310abb2011-10-05 00:59:23 +020012790 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012791}
12792
12793PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012794 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012795\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012796Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012798separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012799
12800static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012801unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802{
Victor Stinner9310abb2011-10-05 00:59:23 +020012803 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012804}
12805
Alexander Belopolsky40018472011-02-26 01:02:56 +000012806PyObject *
12807PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012808{
12809 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012810
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012811 s = PyUnicode_FromObject(s);
12812 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012813 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012814 if (sep != NULL) {
12815 sep = PyUnicode_FromObject(sep);
12816 if (sep == NULL) {
12817 Py_DECREF(s);
12818 return NULL;
12819 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012820 }
12821
Victor Stinner9310abb2011-10-05 00:59:23 +020012822 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012823
12824 Py_DECREF(s);
12825 Py_XDECREF(sep);
12826 return result;
12827}
12828
12829PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012830 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012831\n\
12832Return a list of the words in S, using sep as the\n\
12833delimiter string, starting at the end of the string and\n\
12834working to the front. If maxsplit is given, at most maxsplit\n\
12835splits are done. If sep is not specified, any whitespace string\n\
12836is a separator.");
12837
12838static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012839unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012840{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012841 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012842 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012843 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012844
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012845 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12846 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012847 return NULL;
12848
12849 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012850 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012851 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012852 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012853 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012854 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012855}
12856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012857PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012858 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859\n\
12860Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012861Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012862is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863
12864static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012865unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012867 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012868 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012870 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12871 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872 return NULL;
12873
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012874 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875}
12876
12877static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012878PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012879{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012880 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881}
12882
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012883PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885\n\
12886Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012887and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888
12889static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012890unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012892 if (PyUnicode_READY(self) == -1)
12893 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012894 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895}
12896
Larry Hastings61272b72014-01-07 12:41:53 -080012897/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012898
Larry Hastings31826802013-10-19 00:09:25 -070012899@staticmethod
12900str.maketrans as unicode_maketrans
12901
12902 x: object
12903
12904 y: unicode=NULL
12905
12906 z: unicode=NULL
12907
12908 /
12909
12910Return a translation table usable for str.translate().
12911
12912If there is only one argument, it must be a dictionary mapping Unicode
12913ordinals (integers) or characters to Unicode ordinals, strings or None.
12914Character keys will be then converted to ordinals.
12915If there are two arguments, they must be strings of equal length, and
12916in the resulting dictionary, each character in x will be mapped to the
12917character at the same position in y. If there is a third argument, it
12918must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012919[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012920
12921PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012922"maketrans(x, y=None, z=None, /)\n"
12923"--\n"
12924"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012925"Return a translation table usable for str.translate().\n"
12926"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012927"If there is only one argument, it must be a dictionary mapping Unicode\n"
12928"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12929"Character keys will be then converted to ordinals.\n"
12930"If there are two arguments, they must be strings of equal length, and\n"
12931"in the resulting dictionary, each character in x will be mapped to the\n"
12932"character at the same position in y. If there is a third argument, it\n"
12933"must be a string, whose characters will be mapped to None in the result.");
12934
12935#define UNICODE_MAKETRANS_METHODDEF \
12936 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12937
12938static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012939unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012940
12941static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012942unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012943{
Larry Hastings31826802013-10-19 00:09:25 -070012944 PyObject *return_value = NULL;
12945 PyObject *x;
12946 PyObject *y = NULL;
12947 PyObject *z = NULL;
12948
12949 if (!PyArg_ParseTuple(args,
12950 "O|UU:maketrans",
12951 &x, &y, &z))
12952 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012953 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012954
12955exit:
12956 return return_value;
12957}
12958
12959static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012960unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012961/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012962{
Georg Brandlceee0772007-11-27 23:48:05 +000012963 PyObject *new = NULL, *key, *value;
12964 Py_ssize_t i = 0;
12965 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012966
Georg Brandlceee0772007-11-27 23:48:05 +000012967 new = PyDict_New();
12968 if (!new)
12969 return NULL;
12970 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012971 int x_kind, y_kind, z_kind;
12972 void *x_data, *y_data, *z_data;
12973
Georg Brandlceee0772007-11-27 23:48:05 +000012974 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012975 if (!PyUnicode_Check(x)) {
12976 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12977 "be a string if there is a second argument");
12978 goto err;
12979 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012981 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12982 "arguments must have equal length");
12983 goto err;
12984 }
12985 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012986 x_kind = PyUnicode_KIND(x);
12987 y_kind = PyUnicode_KIND(y);
12988 x_data = PyUnicode_DATA(x);
12989 y_data = PyUnicode_DATA(y);
12990 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12991 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012992 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012993 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012994 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012995 if (!value) {
12996 Py_DECREF(key);
12997 goto err;
12998 }
Georg Brandlceee0772007-11-27 23:48:05 +000012999 res = PyDict_SetItem(new, key, value);
13000 Py_DECREF(key);
13001 Py_DECREF(value);
13002 if (res < 0)
13003 goto err;
13004 }
13005 /* create entries for deleting chars in z */
13006 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 z_kind = PyUnicode_KIND(z);
13008 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013009 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013011 if (!key)
13012 goto err;
13013 res = PyDict_SetItem(new, key, Py_None);
13014 Py_DECREF(key);
13015 if (res < 0)
13016 goto err;
13017 }
13018 }
13019 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013020 int kind;
13021 void *data;
13022
Georg Brandlceee0772007-11-27 23:48:05 +000013023 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013024 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013025 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13026 "to maketrans it must be a dict");
13027 goto err;
13028 }
13029 /* copy entries into the new dict, converting string keys to int keys */
13030 while (PyDict_Next(x, &i, &key, &value)) {
13031 if (PyUnicode_Check(key)) {
13032 /* convert string keys to integer keys */
13033 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013034 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013035 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13036 "table must be of length 1");
13037 goto err;
13038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 kind = PyUnicode_KIND(key);
13040 data = PyUnicode_DATA(key);
13041 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013042 if (!newkey)
13043 goto err;
13044 res = PyDict_SetItem(new, newkey, value);
13045 Py_DECREF(newkey);
13046 if (res < 0)
13047 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013048 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013049 /* just keep integer keys */
13050 if (PyDict_SetItem(new, key, value) < 0)
13051 goto err;
13052 } else {
13053 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13054 "be strings or integers");
13055 goto err;
13056 }
13057 }
13058 }
13059 return new;
13060 err:
13061 Py_DECREF(new);
13062 return NULL;
13063}
13064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013065PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013066 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067\n\
13068Return a copy of the string S, where all characters have been mapped\n\
13069through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013070Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013071Unmapped characters are left untouched. Characters mapped to None\n\
13072are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013073
13074static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013075unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013076{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013077 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078}
13079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013080PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013082\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013083Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084
13085static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013086unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013088 if (PyUnicode_READY(self) == -1)
13089 return NULL;
13090 if (PyUnicode_IS_ASCII(self))
13091 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013092 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093}
13094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013095PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013098Pad a numeric string S with zeros on the left, to fill a field\n\
13099of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100
13101static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013102unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013104 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013105 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013106 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 int kind;
13108 void *data;
13109 Py_UCS4 chr;
13110
Martin v. Löwis18e16552006-02-15 17:27:45 +000013111 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112 return NULL;
13113
Benjamin Petersonbac79492012-01-14 13:34:47 -050013114 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013115 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116
Victor Stinnerc4b49542011-12-11 22:44:26 +010013117 if (PyUnicode_GET_LENGTH(self) >= width)
13118 return unicode_result_unchanged(self);
13119
13120 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121
13122 u = pad(self, fill, 0, '0');
13123
Walter Dörwald068325e2002-04-15 13:36:47 +000013124 if (u == NULL)
13125 return NULL;
13126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 kind = PyUnicode_KIND(u);
13128 data = PyUnicode_DATA(u);
13129 chr = PyUnicode_READ(kind, data, fill);
13130
13131 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 PyUnicode_WRITE(kind, data, 0, chr);
13134 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135 }
13136
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013137 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013138 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013139}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140
13141#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013142static PyObject *
13143unicode__decimal2ascii(PyObject *self)
13144{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013146}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147#endif
13148
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013149PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013150 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013152Return True if S starts with the specified prefix, False otherwise.\n\
13153With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013154With optional end, stop comparing S at that position.\n\
13155prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156
13157static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013158unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013159 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013160{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013161 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013162 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013163 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013164 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013165 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166
Jesus Ceaac451502011-04-20 17:09:23 +020013167 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013168 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013169 if (PyTuple_Check(subobj)) {
13170 Py_ssize_t i;
13171 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013172 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013173 if (substring == NULL)
13174 return NULL;
13175 result = tailmatch(self, substring, start, end, -1);
13176 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013177 if (result == -1)
13178 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013179 if (result) {
13180 Py_RETURN_TRUE;
13181 }
13182 }
13183 /* nothing matched */
13184 Py_RETURN_FALSE;
13185 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013186 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013187 if (substring == NULL) {
13188 if (PyErr_ExceptionMatches(PyExc_TypeError))
13189 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13190 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013191 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013192 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013193 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013195 if (result == -1)
13196 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013197 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198}
13199
13200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013201PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013204Return True if S ends with the specified suffix, False otherwise.\n\
13205With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013206With optional end, stop comparing S at that position.\n\
13207suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208
13209static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013210unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013211 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013213 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013214 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013215 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013216 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013217 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218
Jesus Ceaac451502011-04-20 17:09:23 +020013219 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013220 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013221 if (PyTuple_Check(subobj)) {
13222 Py_ssize_t i;
13223 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013224 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013225 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013226 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013227 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013228 result = tailmatch(self, substring, start, end, +1);
13229 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013230 if (result == -1)
13231 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013232 if (result) {
13233 Py_RETURN_TRUE;
13234 }
13235 }
13236 Py_RETURN_FALSE;
13237 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013238 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013239 if (substring == NULL) {
13240 if (PyErr_ExceptionMatches(PyExc_TypeError))
13241 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13242 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013244 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013245 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013246 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013247 if (result == -1)
13248 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013249 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250}
13251
Victor Stinner202fdca2012-05-07 12:47:02 +020013252Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013253_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013254{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013255 if (!writer->readonly)
13256 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13257 else {
13258 /* Copy-on-write mode: set buffer size to 0 so
13259 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13260 * next write. */
13261 writer->size = 0;
13262 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013263 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13264 writer->data = PyUnicode_DATA(writer->buffer);
13265 writer->kind = PyUnicode_KIND(writer->buffer);
13266}
13267
Victor Stinnerd3f08822012-05-29 12:57:52 +020013268void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013269_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013270{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013271 memset(writer, 0, sizeof(*writer));
13272#ifdef Py_DEBUG
13273 writer->kind = 5; /* invalid kind */
13274#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013275 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013276}
13277
Victor Stinnerd3f08822012-05-29 12:57:52 +020013278int
13279_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13280 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013281{
Victor Stinner6989ba02013-11-18 21:08:39 +010013282#ifdef MS_WINDOWS
13283 /* On Windows, overallocate by 50% is the best factor */
13284# define OVERALLOCATE_FACTOR 2
13285#else
13286 /* On Linux, overallocate by 25% is the best factor */
13287# define OVERALLOCATE_FACTOR 4
13288#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013289 Py_ssize_t newlen;
13290 PyObject *newbuffer;
13291
Victor Stinnerd3f08822012-05-29 12:57:52 +020013292 assert(length > 0);
13293
Victor Stinner202fdca2012-05-07 12:47:02 +020013294 if (length > PY_SSIZE_T_MAX - writer->pos) {
13295 PyErr_NoMemory();
13296 return -1;
13297 }
13298 newlen = writer->pos + length;
13299
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013300 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013301
Victor Stinnerd3f08822012-05-29 12:57:52 +020013302 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013303 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013304 if (writer->overallocate
13305 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13306 /* overallocate to limit the number of realloc() */
13307 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013308 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013309 if (newlen < writer->min_length)
13310 newlen = writer->min_length;
13311
Victor Stinnerd3f08822012-05-29 12:57:52 +020013312 writer->buffer = PyUnicode_New(newlen, maxchar);
13313 if (writer->buffer == NULL)
13314 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013315 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013316 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013317 if (writer->overallocate
13318 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13319 /* overallocate to limit the number of realloc() */
13320 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013322 if (newlen < writer->min_length)
13323 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013324
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013325 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013326 /* resize + widen */
13327 newbuffer = PyUnicode_New(newlen, maxchar);
13328 if (newbuffer == NULL)
13329 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013330 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13331 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013332 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013333 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013334 }
13335 else {
13336 newbuffer = resize_compact(writer->buffer, newlen);
13337 if (newbuffer == NULL)
13338 return -1;
13339 }
13340 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013341 }
13342 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013343 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013344 newbuffer = PyUnicode_New(writer->size, maxchar);
13345 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013346 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013347 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13348 writer->buffer, 0, writer->pos);
13349 Py_DECREF(writer->buffer);
13350 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013351 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013352 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013353 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013354
13355#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013356}
13357
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013358Py_LOCAL_INLINE(int)
13359_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013360{
13361 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13362 return -1;
13363 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13364 writer->pos++;
13365 return 0;
13366}
13367
13368int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013369_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13370{
13371 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13372}
13373
13374int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013375_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13376{
13377 Py_UCS4 maxchar;
13378 Py_ssize_t len;
13379
13380 if (PyUnicode_READY(str) == -1)
13381 return -1;
13382 len = PyUnicode_GET_LENGTH(str);
13383 if (len == 0)
13384 return 0;
13385 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13386 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013387 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013388 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013389 Py_INCREF(str);
13390 writer->buffer = str;
13391 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013392 writer->pos += len;
13393 return 0;
13394 }
13395 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13396 return -1;
13397 }
13398 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13399 str, 0, len);
13400 writer->pos += len;
13401 return 0;
13402}
13403
Victor Stinnere215d962012-10-06 23:03:36 +020013404int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013405_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13406 Py_ssize_t start, Py_ssize_t end)
13407{
13408 Py_UCS4 maxchar;
13409 Py_ssize_t len;
13410
13411 if (PyUnicode_READY(str) == -1)
13412 return -1;
13413
13414 assert(0 <= start);
13415 assert(end <= PyUnicode_GET_LENGTH(str));
13416 assert(start <= end);
13417
13418 if (end == 0)
13419 return 0;
13420
13421 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13422 return _PyUnicodeWriter_WriteStr(writer, str);
13423
13424 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13425 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13426 else
13427 maxchar = writer->maxchar;
13428 len = end - start;
13429
13430 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13431 return -1;
13432
13433 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13434 str, start, len);
13435 writer->pos += len;
13436 return 0;
13437}
13438
13439int
Victor Stinner4a587072013-11-19 12:54:53 +010013440_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13441 const char *ascii, Py_ssize_t len)
13442{
13443 if (len == -1)
13444 len = strlen(ascii);
13445
13446 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13447
13448 if (writer->buffer == NULL && !writer->overallocate) {
13449 PyObject *str;
13450
13451 str = _PyUnicode_FromASCII(ascii, len);
13452 if (str == NULL)
13453 return -1;
13454
13455 writer->readonly = 1;
13456 writer->buffer = str;
13457 _PyUnicodeWriter_Update(writer);
13458 writer->pos += len;
13459 return 0;
13460 }
13461
13462 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13463 return -1;
13464
13465 switch (writer->kind)
13466 {
13467 case PyUnicode_1BYTE_KIND:
13468 {
13469 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13470 Py_UCS1 *data = writer->data;
13471
13472 Py_MEMCPY(data + writer->pos, str, len);
13473 break;
13474 }
13475 case PyUnicode_2BYTE_KIND:
13476 {
13477 _PyUnicode_CONVERT_BYTES(
13478 Py_UCS1, Py_UCS2,
13479 ascii, ascii + len,
13480 (Py_UCS2 *)writer->data + writer->pos);
13481 break;
13482 }
13483 case PyUnicode_4BYTE_KIND:
13484 {
13485 _PyUnicode_CONVERT_BYTES(
13486 Py_UCS1, Py_UCS4,
13487 ascii, ascii + len,
13488 (Py_UCS4 *)writer->data + writer->pos);
13489 break;
13490 }
13491 default:
13492 assert(0);
13493 }
13494
13495 writer->pos += len;
13496 return 0;
13497}
13498
13499int
13500_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13501 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013502{
13503 Py_UCS4 maxchar;
13504
13505 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13506 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13507 return -1;
13508 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13509 writer->pos += len;
13510 return 0;
13511}
13512
Victor Stinnerd3f08822012-05-29 12:57:52 +020013513PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013514_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013515{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013516 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013518 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013519 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013520 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013521 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013522 str = writer->buffer;
13523 writer->buffer = NULL;
13524 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13525 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013526 }
13527 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13528 PyObject *newbuffer;
13529 newbuffer = resize_compact(writer->buffer, writer->pos);
13530 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013531 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013532 return NULL;
13533 }
13534 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013535 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013536 str = writer->buffer;
13537 writer->buffer = NULL;
13538 assert(_PyUnicode_CheckConsistency(str, 1));
13539 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013540}
13541
Victor Stinnerd3f08822012-05-29 12:57:52 +020013542void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013543_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013544{
13545 Py_CLEAR(writer->buffer);
13546}
13547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013548#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013549
13550PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013552\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013553Return a formatted version of S, using substitutions from args and kwargs.\n\
13554The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013555
Eric Smith27bbca62010-11-04 17:06:58 +000013556PyDoc_STRVAR(format_map__doc__,
13557 "S.format_map(mapping) -> str\n\
13558\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013559Return a formatted version of S, using substitutions from mapping.\n\
13560The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013561
Eric Smith4a7d76d2008-05-30 18:10:19 +000013562static PyObject *
13563unicode__format__(PyObject* self, PyObject* args)
13564{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013565 PyObject *format_spec;
13566 _PyUnicodeWriter writer;
13567 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013568
13569 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13570 return NULL;
13571
Victor Stinnerd3f08822012-05-29 12:57:52 +020013572 if (PyUnicode_READY(self) == -1)
13573 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013574 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013575 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13576 self, format_spec, 0,
13577 PyUnicode_GET_LENGTH(format_spec));
13578 if (ret == -1) {
13579 _PyUnicodeWriter_Dealloc(&writer);
13580 return NULL;
13581 }
13582 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013583}
13584
Eric Smith8c663262007-08-25 02:26:07 +000013585PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013587\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013588Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013589
13590static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013591unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013593 Py_ssize_t size;
13594
13595 /* If it's a compact object, account for base structure +
13596 character data. */
13597 if (PyUnicode_IS_COMPACT_ASCII(v))
13598 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13599 else if (PyUnicode_IS_COMPACT(v))
13600 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013601 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013602 else {
13603 /* If it is a two-block object, account for base object, and
13604 for character block if present. */
13605 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013606 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013607 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013608 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013609 }
13610 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013611 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013612 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013614 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013615 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013616
13617 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013618}
13619
13620PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013622
13623static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013624unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013625{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013626 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013627 if (!copy)
13628 return NULL;
13629 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013630}
13631
Guido van Rossumd57fd912000-03-10 22:53:23 +000013632static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013633 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013634 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013635 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13636 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013637 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13638 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013639 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013640 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13641 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13642 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013643 {"expandtabs", (PyCFunction) unicode_expandtabs,
13644 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013645 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013646 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013647 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13648 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13649 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013650 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013651 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13652 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13653 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013654 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013655 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013656 {"splitlines", (PyCFunction) unicode_splitlines,
13657 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013658 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013659 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13660 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13661 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13662 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13663 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13664 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13665 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13666 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13667 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13668 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13669 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13670 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13671 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13672 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013673 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013674 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013675 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013676 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013677 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013678 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013679 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013680 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013681#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013682 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013683 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013684#endif
13685
Benjamin Peterson14339b62009-01-31 16:36:08 +000013686 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013687 {NULL, NULL}
13688};
13689
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013690static PyObject *
13691unicode_mod(PyObject *v, PyObject *w)
13692{
Brian Curtindfc80e32011-08-10 20:28:54 -050013693 if (!PyUnicode_Check(v))
13694 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013696}
13697
13698static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013699 0, /*nb_add*/
13700 0, /*nb_subtract*/
13701 0, /*nb_multiply*/
13702 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013703};
13704
Guido van Rossumd57fd912000-03-10 22:53:23 +000013705static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013706 (lenfunc) unicode_length, /* sq_length */
13707 PyUnicode_Concat, /* sq_concat */
13708 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13709 (ssizeargfunc) unicode_getitem, /* sq_item */
13710 0, /* sq_slice */
13711 0, /* sq_ass_item */
13712 0, /* sq_ass_slice */
13713 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013714};
13715
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013716static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013717unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013718{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013719 if (PyUnicode_READY(self) == -1)
13720 return NULL;
13721
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013722 if (PyIndex_Check(item)) {
13723 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013724 if (i == -1 && PyErr_Occurred())
13725 return NULL;
13726 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013727 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013728 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013729 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013730 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013731 PyObject *result;
13732 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013733 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013734 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013736 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013737 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013738 return NULL;
13739 }
13740
13741 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013742 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013743 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013744 slicelength == PyUnicode_GET_LENGTH(self)) {
13745 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013746 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013747 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013748 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013749 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013750 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013751 src_kind = PyUnicode_KIND(self);
13752 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013753 if (!PyUnicode_IS_ASCII(self)) {
13754 kind_limit = kind_maxchar_limit(src_kind);
13755 max_char = 0;
13756 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13757 ch = PyUnicode_READ(src_kind, src_data, cur);
13758 if (ch > max_char) {
13759 max_char = ch;
13760 if (max_char >= kind_limit)
13761 break;
13762 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013763 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013764 }
Victor Stinner55c99112011-10-13 01:17:06 +020013765 else
13766 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013767 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013768 if (result == NULL)
13769 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013770 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013771 dest_data = PyUnicode_DATA(result);
13772
13773 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013774 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13775 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013776 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013777 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013778 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013779 } else {
13780 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13781 return NULL;
13782 }
13783}
13784
13785static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013786 (lenfunc)unicode_length, /* mp_length */
13787 (binaryfunc)unicode_subscript, /* mp_subscript */
13788 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013789};
13790
Guido van Rossumd57fd912000-03-10 22:53:23 +000013791
Guido van Rossumd57fd912000-03-10 22:53:23 +000013792/* Helpers for PyUnicode_Format() */
13793
Victor Stinnera47082312012-10-04 02:19:54 +020013794struct unicode_formatter_t {
13795 PyObject *args;
13796 int args_owned;
13797 Py_ssize_t arglen, argidx;
13798 PyObject *dict;
13799
13800 enum PyUnicode_Kind fmtkind;
13801 Py_ssize_t fmtcnt, fmtpos;
13802 void *fmtdata;
13803 PyObject *fmtstr;
13804
13805 _PyUnicodeWriter writer;
13806};
13807
13808struct unicode_format_arg_t {
13809 Py_UCS4 ch;
13810 int flags;
13811 Py_ssize_t width;
13812 int prec;
13813 int sign;
13814};
13815
Guido van Rossumd57fd912000-03-10 22:53:23 +000013816static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013817unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013818{
Victor Stinnera47082312012-10-04 02:19:54 +020013819 Py_ssize_t argidx = ctx->argidx;
13820
13821 if (argidx < ctx->arglen) {
13822 ctx->argidx++;
13823 if (ctx->arglen < 0)
13824 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013825 else
Victor Stinnera47082312012-10-04 02:19:54 +020013826 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827 }
13828 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013829 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830 return NULL;
13831}
13832
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013833/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013834
Victor Stinnera47082312012-10-04 02:19:54 +020013835/* Format a float into the writer if the writer is not NULL, or into *p_output
13836 otherwise.
13837
13838 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013839static int
Victor Stinnera47082312012-10-04 02:19:54 +020013840formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13841 PyObject **p_output,
13842 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013843{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013844 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013845 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013846 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013847 int prec;
13848 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013849
Guido van Rossumd57fd912000-03-10 22:53:23 +000013850 x = PyFloat_AsDouble(v);
13851 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013852 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013853
Victor Stinnera47082312012-10-04 02:19:54 +020013854 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013855 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013856 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013857
Victor Stinnera47082312012-10-04 02:19:54 +020013858 if (arg->flags & F_ALT)
13859 dtoa_flags = Py_DTSF_ALT;
13860 else
13861 dtoa_flags = 0;
13862 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013863 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013864 return -1;
13865 len = strlen(p);
13866 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013867 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013868 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013869 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013870 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013871 }
13872 else
13873 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013874 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013875 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013876}
13877
Victor Stinnerd0880d52012-04-27 23:40:13 +020013878/* formatlong() emulates the format codes d, u, o, x and X, and
13879 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13880 * Python's regular ints.
13881 * Return value: a new PyUnicodeObject*, or NULL if error.
13882 * The output string is of the form
13883 * "-"? ("0x" | "0X")? digit+
13884 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13885 * set in flags. The case of hex digits will be correct,
13886 * There will be at least prec digits, zero-filled on the left if
13887 * necessary to get that many.
13888 * val object to be converted
13889 * flags bitmask of format flags; only F_ALT is looked at
13890 * prec minimum number of digits; 0-fill on left if needed
13891 * type a character in [duoxX]; u acts the same as d
13892 *
13893 * CAUTION: o, x and X conversions on regular ints can never
13894 * produce a '-' sign, but can for Python's unbounded ints.
13895 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013896static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013897formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013898{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013899 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013900 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013901 Py_ssize_t i;
13902 int sign; /* 1 if '-', else 0 */
13903 int len; /* number of characters */
13904 Py_ssize_t llen;
13905 int numdigits; /* len == numnondigits + numdigits */
13906 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013907 int prec = arg->prec;
13908 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013909
Victor Stinnerd0880d52012-04-27 23:40:13 +020013910 /* Avoid exceeding SSIZE_T_MAX */
13911 if (prec > INT_MAX-3) {
13912 PyErr_SetString(PyExc_OverflowError,
13913 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013914 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013915 }
13916
13917 assert(PyLong_Check(val));
13918
13919 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013920 default:
13921 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013922 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013923 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013924 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013925 /* int and int subclasses should print numerically when a numeric */
13926 /* format code is used (see issue18780) */
13927 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013928 break;
13929 case 'o':
13930 numnondigits = 2;
13931 result = PyNumber_ToBase(val, 8);
13932 break;
13933 case 'x':
13934 case 'X':
13935 numnondigits = 2;
13936 result = PyNumber_ToBase(val, 16);
13937 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013938 }
13939 if (!result)
13940 return NULL;
13941
13942 assert(unicode_modifiable(result));
13943 assert(PyUnicode_IS_READY(result));
13944 assert(PyUnicode_IS_ASCII(result));
13945
13946 /* To modify the string in-place, there can only be one reference. */
13947 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013948 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013949 PyErr_BadInternalCall();
13950 return NULL;
13951 }
13952 buf = PyUnicode_DATA(result);
13953 llen = PyUnicode_GET_LENGTH(result);
13954 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013955 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013956 PyErr_SetString(PyExc_ValueError,
13957 "string too large in _PyBytes_FormatLong");
13958 return NULL;
13959 }
13960 len = (int)llen;
13961 sign = buf[0] == '-';
13962 numnondigits += sign;
13963 numdigits = len - numnondigits;
13964 assert(numdigits > 0);
13965
13966 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013967 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013968 (type == 'o' || type == 'x' || type == 'X'))) {
13969 assert(buf[sign] == '0');
13970 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13971 buf[sign+1] == 'o');
13972 numnondigits -= 2;
13973 buf += 2;
13974 len -= 2;
13975 if (sign)
13976 buf[0] = '-';
13977 assert(len == numnondigits + numdigits);
13978 assert(numdigits > 0);
13979 }
13980
13981 /* Fill with leading zeroes to meet minimum width. */
13982 if (prec > numdigits) {
13983 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13984 numnondigits + prec);
13985 char *b1;
13986 if (!r1) {
13987 Py_DECREF(result);
13988 return NULL;
13989 }
13990 b1 = PyBytes_AS_STRING(r1);
13991 for (i = 0; i < numnondigits; ++i)
13992 *b1++ = *buf++;
13993 for (i = 0; i < prec - numdigits; i++)
13994 *b1++ = '0';
13995 for (i = 0; i < numdigits; i++)
13996 *b1++ = *buf++;
13997 *b1 = '\0';
13998 Py_DECREF(result);
13999 result = r1;
14000 buf = PyBytes_AS_STRING(result);
14001 len = numnondigits + prec;
14002 }
14003
14004 /* Fix up case for hex conversions. */
14005 if (type == 'X') {
14006 /* Need to convert all lower case letters to upper case.
14007 and need to convert 0x to 0X (and -0x to -0X). */
14008 for (i = 0; i < len; i++)
14009 if (buf[i] >= 'a' && buf[i] <= 'x')
14010 buf[i] -= 'a'-'A';
14011 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014012 if (!PyUnicode_Check(result)
14013 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014014 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014015 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014016 Py_DECREF(result);
14017 result = unicode;
14018 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014019 else if (len != PyUnicode_GET_LENGTH(result)) {
14020 if (PyUnicode_Resize(&result, len) < 0)
14021 Py_CLEAR(result);
14022 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014024}
14025
Ethan Furmandf3ed242014-01-05 06:50:30 -080014026/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014027 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014028 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014029 * -1 and raise an exception on error */
14030static int
Victor Stinnera47082312012-10-04 02:19:54 +020014031mainformatlong(PyObject *v,
14032 struct unicode_format_arg_t *arg,
14033 PyObject **p_output,
14034 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014035{
14036 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014037 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014038
14039 if (!PyNumber_Check(v))
14040 goto wrongtype;
14041
Ethan Furman9ab74802014-03-21 06:38:46 -070014042 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014043 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014044 if (type == 'o' || type == 'x' || type == 'X') {
14045 iobj = PyNumber_Index(v);
14046 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014047 if (PyErr_ExceptionMatches(PyExc_TypeError))
14048 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014049 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014050 }
14051 }
14052 else {
14053 iobj = PyNumber_Long(v);
14054 if (iobj == NULL ) {
14055 if (PyErr_ExceptionMatches(PyExc_TypeError))
14056 goto wrongtype;
14057 return -1;
14058 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014059 }
14060 assert(PyLong_Check(iobj));
14061 }
14062 else {
14063 iobj = v;
14064 Py_INCREF(iobj);
14065 }
14066
14067 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014068 && arg->width == -1 && arg->prec == -1
14069 && !(arg->flags & (F_SIGN | F_BLANK))
14070 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014071 {
14072 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014073 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014074 int base;
14075
Victor Stinnera47082312012-10-04 02:19:54 +020014076 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014077 {
14078 default:
14079 assert(0 && "'type' not in [diuoxX]");
14080 case 'd':
14081 case 'i':
14082 case 'u':
14083 base = 10;
14084 break;
14085 case 'o':
14086 base = 8;
14087 break;
14088 case 'x':
14089 case 'X':
14090 base = 16;
14091 break;
14092 }
14093
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014094 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14095 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014096 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014097 }
14098 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014099 return 1;
14100 }
14101
Victor Stinnera47082312012-10-04 02:19:54 +020014102 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014103 Py_DECREF(iobj);
14104 if (res == NULL)
14105 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014106 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014107 return 0;
14108
14109wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014110 switch(type)
14111 {
14112 case 'o':
14113 case 'x':
14114 case 'X':
14115 PyErr_Format(PyExc_TypeError,
14116 "%%%c format: an integer is required, "
14117 "not %.200s",
14118 type, Py_TYPE(v)->tp_name);
14119 break;
14120 default:
14121 PyErr_Format(PyExc_TypeError,
14122 "%%%c format: a number is required, "
14123 "not %.200s",
14124 type, Py_TYPE(v)->tp_name);
14125 break;
14126 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014127 return -1;
14128}
14129
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014130static Py_UCS4
14131formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014132{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014133 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014134 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014135 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014136 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014137 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014138 goto onError;
14139 }
14140 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014141 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014142 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014143 /* make sure number is a type of integer */
14144 if (!PyLong_Check(v)) {
14145 iobj = PyNumber_Index(v);
14146 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014147 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014148 }
14149 v = iobj;
14150 Py_DECREF(iobj);
14151 }
14152 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014153 x = PyLong_AsLong(v);
14154 if (x == -1 && PyErr_Occurred())
14155 goto onError;
14156
Victor Stinner8faf8212011-12-08 22:14:11 +010014157 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014158 PyErr_SetString(PyExc_OverflowError,
14159 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014160 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014161 }
14162
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014163 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014164 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014165
Benjamin Peterson29060642009-01-31 22:14:21 +000014166 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014167 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014168 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014169 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014170}
14171
Victor Stinnera47082312012-10-04 02:19:54 +020014172/* Parse options of an argument: flags, width, precision.
14173 Handle also "%(name)" syntax.
14174
14175 Return 0 if the argument has been formatted into arg->str.
14176 Return 1 if the argument has been written into ctx->writer,
14177 Raise an exception and return -1 on error. */
14178static int
14179unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14180 struct unicode_format_arg_t *arg)
14181{
14182#define FORMAT_READ(ctx) \
14183 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14184
14185 PyObject *v;
14186
Victor Stinnera47082312012-10-04 02:19:54 +020014187 if (arg->ch == '(') {
14188 /* Get argument value from a dictionary. Example: "%(name)s". */
14189 Py_ssize_t keystart;
14190 Py_ssize_t keylen;
14191 PyObject *key;
14192 int pcount = 1;
14193
14194 if (ctx->dict == NULL) {
14195 PyErr_SetString(PyExc_TypeError,
14196 "format requires a mapping");
14197 return -1;
14198 }
14199 ++ctx->fmtpos;
14200 --ctx->fmtcnt;
14201 keystart = ctx->fmtpos;
14202 /* Skip over balanced parentheses */
14203 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14204 arg->ch = FORMAT_READ(ctx);
14205 if (arg->ch == ')')
14206 --pcount;
14207 else if (arg->ch == '(')
14208 ++pcount;
14209 ctx->fmtpos++;
14210 }
14211 keylen = ctx->fmtpos - keystart - 1;
14212 if (ctx->fmtcnt < 0 || pcount > 0) {
14213 PyErr_SetString(PyExc_ValueError,
14214 "incomplete format key");
14215 return -1;
14216 }
14217 key = PyUnicode_Substring(ctx->fmtstr,
14218 keystart, keystart + keylen);
14219 if (key == NULL)
14220 return -1;
14221 if (ctx->args_owned) {
14222 Py_DECREF(ctx->args);
14223 ctx->args_owned = 0;
14224 }
14225 ctx->args = PyObject_GetItem(ctx->dict, key);
14226 Py_DECREF(key);
14227 if (ctx->args == NULL)
14228 return -1;
14229 ctx->args_owned = 1;
14230 ctx->arglen = -1;
14231 ctx->argidx = -2;
14232 }
14233
14234 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014235 while (--ctx->fmtcnt >= 0) {
14236 arg->ch = FORMAT_READ(ctx);
14237 ctx->fmtpos++;
14238 switch (arg->ch) {
14239 case '-': arg->flags |= F_LJUST; continue;
14240 case '+': arg->flags |= F_SIGN; continue;
14241 case ' ': arg->flags |= F_BLANK; continue;
14242 case '#': arg->flags |= F_ALT; continue;
14243 case '0': arg->flags |= F_ZERO; continue;
14244 }
14245 break;
14246 }
14247
14248 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014249 if (arg->ch == '*') {
14250 v = unicode_format_getnextarg(ctx);
14251 if (v == NULL)
14252 return -1;
14253 if (!PyLong_Check(v)) {
14254 PyErr_SetString(PyExc_TypeError,
14255 "* wants int");
14256 return -1;
14257 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014258 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014259 if (arg->width == -1 && PyErr_Occurred())
14260 return -1;
14261 if (arg->width < 0) {
14262 arg->flags |= F_LJUST;
14263 arg->width = -arg->width;
14264 }
14265 if (--ctx->fmtcnt >= 0) {
14266 arg->ch = FORMAT_READ(ctx);
14267 ctx->fmtpos++;
14268 }
14269 }
14270 else if (arg->ch >= '0' && arg->ch <= '9') {
14271 arg->width = arg->ch - '0';
14272 while (--ctx->fmtcnt >= 0) {
14273 arg->ch = FORMAT_READ(ctx);
14274 ctx->fmtpos++;
14275 if (arg->ch < '0' || arg->ch > '9')
14276 break;
14277 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14278 mixing signed and unsigned comparison. Since arg->ch is between
14279 '0' and '9', casting to int is safe. */
14280 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14281 PyErr_SetString(PyExc_ValueError,
14282 "width too big");
14283 return -1;
14284 }
14285 arg->width = arg->width*10 + (arg->ch - '0');
14286 }
14287 }
14288
14289 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014290 if (arg->ch == '.') {
14291 arg->prec = 0;
14292 if (--ctx->fmtcnt >= 0) {
14293 arg->ch = FORMAT_READ(ctx);
14294 ctx->fmtpos++;
14295 }
14296 if (arg->ch == '*') {
14297 v = unicode_format_getnextarg(ctx);
14298 if (v == NULL)
14299 return -1;
14300 if (!PyLong_Check(v)) {
14301 PyErr_SetString(PyExc_TypeError,
14302 "* wants int");
14303 return -1;
14304 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014305 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014306 if (arg->prec == -1 && PyErr_Occurred())
14307 return -1;
14308 if (arg->prec < 0)
14309 arg->prec = 0;
14310 if (--ctx->fmtcnt >= 0) {
14311 arg->ch = FORMAT_READ(ctx);
14312 ctx->fmtpos++;
14313 }
14314 }
14315 else if (arg->ch >= '0' && arg->ch <= '9') {
14316 arg->prec = arg->ch - '0';
14317 while (--ctx->fmtcnt >= 0) {
14318 arg->ch = FORMAT_READ(ctx);
14319 ctx->fmtpos++;
14320 if (arg->ch < '0' || arg->ch > '9')
14321 break;
14322 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14323 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014324 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014325 return -1;
14326 }
14327 arg->prec = arg->prec*10 + (arg->ch - '0');
14328 }
14329 }
14330 }
14331
14332 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14333 if (ctx->fmtcnt >= 0) {
14334 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14335 if (--ctx->fmtcnt >= 0) {
14336 arg->ch = FORMAT_READ(ctx);
14337 ctx->fmtpos++;
14338 }
14339 }
14340 }
14341 if (ctx->fmtcnt < 0) {
14342 PyErr_SetString(PyExc_ValueError,
14343 "incomplete format");
14344 return -1;
14345 }
14346 return 0;
14347
14348#undef FORMAT_READ
14349}
14350
14351/* Format one argument. Supported conversion specifiers:
14352
14353 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014354 - "i", "d", "u": int or float
14355 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014356 - "e", "E", "f", "F", "g", "G": float
14357 - "c": int or str (1 character)
14358
Victor Stinner8dbd4212012-12-04 09:30:24 +010014359 When possible, the output is written directly into the Unicode writer
14360 (ctx->writer). A string is created when padding is required.
14361
Victor Stinnera47082312012-10-04 02:19:54 +020014362 Return 0 if the argument has been formatted into *p_str,
14363 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014364 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014365static int
14366unicode_format_arg_format(struct unicode_formatter_t *ctx,
14367 struct unicode_format_arg_t *arg,
14368 PyObject **p_str)
14369{
14370 PyObject *v;
14371 _PyUnicodeWriter *writer = &ctx->writer;
14372
14373 if (ctx->fmtcnt == 0)
14374 ctx->writer.overallocate = 0;
14375
14376 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014377 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014378 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014379 return 1;
14380 }
14381
14382 v = unicode_format_getnextarg(ctx);
14383 if (v == NULL)
14384 return -1;
14385
Victor Stinnera47082312012-10-04 02:19:54 +020014386
14387 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014388 case 's':
14389 case 'r':
14390 case 'a':
14391 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14392 /* Fast path */
14393 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14394 return -1;
14395 return 1;
14396 }
14397
14398 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14399 *p_str = v;
14400 Py_INCREF(*p_str);
14401 }
14402 else {
14403 if (arg->ch == 's')
14404 *p_str = PyObject_Str(v);
14405 else if (arg->ch == 'r')
14406 *p_str = PyObject_Repr(v);
14407 else
14408 *p_str = PyObject_ASCII(v);
14409 }
14410 break;
14411
14412 case 'i':
14413 case 'd':
14414 case 'u':
14415 case 'o':
14416 case 'x':
14417 case 'X':
14418 {
14419 int ret = mainformatlong(v, arg, p_str, writer);
14420 if (ret != 0)
14421 return ret;
14422 arg->sign = 1;
14423 break;
14424 }
14425
14426 case 'e':
14427 case 'E':
14428 case 'f':
14429 case 'F':
14430 case 'g':
14431 case 'G':
14432 if (arg->width == -1 && arg->prec == -1
14433 && !(arg->flags & (F_SIGN | F_BLANK)))
14434 {
14435 /* Fast path */
14436 if (formatfloat(v, arg, NULL, writer) == -1)
14437 return -1;
14438 return 1;
14439 }
14440
14441 arg->sign = 1;
14442 if (formatfloat(v, arg, p_str, NULL) == -1)
14443 return -1;
14444 break;
14445
14446 case 'c':
14447 {
14448 Py_UCS4 ch = formatchar(v);
14449 if (ch == (Py_UCS4) -1)
14450 return -1;
14451 if (arg->width == -1 && arg->prec == -1) {
14452 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014453 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014454 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014455 return 1;
14456 }
14457 *p_str = PyUnicode_FromOrdinal(ch);
14458 break;
14459 }
14460
14461 default:
14462 PyErr_Format(PyExc_ValueError,
14463 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014464 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014465 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14466 (int)arg->ch,
14467 ctx->fmtpos - 1);
14468 return -1;
14469 }
14470 if (*p_str == NULL)
14471 return -1;
14472 assert (PyUnicode_Check(*p_str));
14473 return 0;
14474}
14475
14476static int
14477unicode_format_arg_output(struct unicode_formatter_t *ctx,
14478 struct unicode_format_arg_t *arg,
14479 PyObject *str)
14480{
14481 Py_ssize_t len;
14482 enum PyUnicode_Kind kind;
14483 void *pbuf;
14484 Py_ssize_t pindex;
14485 Py_UCS4 signchar;
14486 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014487 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014488 Py_ssize_t sublen;
14489 _PyUnicodeWriter *writer = &ctx->writer;
14490 Py_UCS4 fill;
14491
14492 fill = ' ';
14493 if (arg->sign && arg->flags & F_ZERO)
14494 fill = '0';
14495
14496 if (PyUnicode_READY(str) == -1)
14497 return -1;
14498
14499 len = PyUnicode_GET_LENGTH(str);
14500 if ((arg->width == -1 || arg->width <= len)
14501 && (arg->prec == -1 || arg->prec >= len)
14502 && !(arg->flags & (F_SIGN | F_BLANK)))
14503 {
14504 /* Fast path */
14505 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14506 return -1;
14507 return 0;
14508 }
14509
14510 /* Truncate the string for "s", "r" and "a" formats
14511 if the precision is set */
14512 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14513 if (arg->prec >= 0 && len > arg->prec)
14514 len = arg->prec;
14515 }
14516
14517 /* Adjust sign and width */
14518 kind = PyUnicode_KIND(str);
14519 pbuf = PyUnicode_DATA(str);
14520 pindex = 0;
14521 signchar = '\0';
14522 if (arg->sign) {
14523 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14524 if (ch == '-' || ch == '+') {
14525 signchar = ch;
14526 len--;
14527 pindex++;
14528 }
14529 else if (arg->flags & F_SIGN)
14530 signchar = '+';
14531 else if (arg->flags & F_BLANK)
14532 signchar = ' ';
14533 else
14534 arg->sign = 0;
14535 }
14536 if (arg->width < len)
14537 arg->width = len;
14538
14539 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014540 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014541 if (!(arg->flags & F_LJUST)) {
14542 if (arg->sign) {
14543 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014544 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014545 }
14546 else {
14547 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014548 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014549 }
14550 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014551 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14552 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014553 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014554 }
14555
Victor Stinnera47082312012-10-04 02:19:54 +020014556 buflen = arg->width;
14557 if (arg->sign && len == arg->width)
14558 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014559 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014560 return -1;
14561
14562 /* Write the sign if needed */
14563 if (arg->sign) {
14564 if (fill != ' ') {
14565 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14566 writer->pos += 1;
14567 }
14568 if (arg->width > len)
14569 arg->width--;
14570 }
14571
14572 /* Write the numeric prefix for "x", "X" and "o" formats
14573 if the alternate form is used.
14574 For example, write "0x" for the "%#x" format. */
14575 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14576 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14577 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14578 if (fill != ' ') {
14579 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14580 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14581 writer->pos += 2;
14582 pindex += 2;
14583 }
14584 arg->width -= 2;
14585 if (arg->width < 0)
14586 arg->width = 0;
14587 len -= 2;
14588 }
14589
14590 /* Pad left with the fill character if needed */
14591 if (arg->width > len && !(arg->flags & F_LJUST)) {
14592 sublen = arg->width - len;
14593 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14594 writer->pos += sublen;
14595 arg->width = len;
14596 }
14597
14598 /* If padding with spaces: write sign if needed and/or numeric prefix if
14599 the alternate form is used */
14600 if (fill == ' ') {
14601 if (arg->sign) {
14602 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14603 writer->pos += 1;
14604 }
14605 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14606 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14607 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14608 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14609 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14610 writer->pos += 2;
14611 pindex += 2;
14612 }
14613 }
14614
14615 /* Write characters */
14616 if (len) {
14617 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14618 str, pindex, len);
14619 writer->pos += len;
14620 }
14621
14622 /* Pad right with the fill character if needed */
14623 if (arg->width > len) {
14624 sublen = arg->width - len;
14625 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14626 writer->pos += sublen;
14627 }
14628 return 0;
14629}
14630
14631/* Helper of PyUnicode_Format(): format one arg.
14632 Return 0 on success, raise an exception and return -1 on error. */
14633static int
14634unicode_format_arg(struct unicode_formatter_t *ctx)
14635{
14636 struct unicode_format_arg_t arg;
14637 PyObject *str;
14638 int ret;
14639
Victor Stinner8dbd4212012-12-04 09:30:24 +010014640 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14641 arg.flags = 0;
14642 arg.width = -1;
14643 arg.prec = -1;
14644 arg.sign = 0;
14645 str = NULL;
14646
Victor Stinnera47082312012-10-04 02:19:54 +020014647 ret = unicode_format_arg_parse(ctx, &arg);
14648 if (ret == -1)
14649 return -1;
14650
14651 ret = unicode_format_arg_format(ctx, &arg, &str);
14652 if (ret == -1)
14653 return -1;
14654
14655 if (ret != 1) {
14656 ret = unicode_format_arg_output(ctx, &arg, str);
14657 Py_DECREF(str);
14658 if (ret == -1)
14659 return -1;
14660 }
14661
14662 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14663 PyErr_SetString(PyExc_TypeError,
14664 "not all arguments converted during string formatting");
14665 return -1;
14666 }
14667 return 0;
14668}
14669
Alexander Belopolsky40018472011-02-26 01:02:56 +000014670PyObject *
14671PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014672{
Victor Stinnera47082312012-10-04 02:19:54 +020014673 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014674
Guido van Rossumd57fd912000-03-10 22:53:23 +000014675 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014676 PyErr_BadInternalCall();
14677 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014678 }
Victor Stinnera47082312012-10-04 02:19:54 +020014679
14680 ctx.fmtstr = PyUnicode_FromObject(format);
14681 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014682 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014683 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14684 Py_DECREF(ctx.fmtstr);
14685 return NULL;
14686 }
14687 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14688 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14689 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14690 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014691
Victor Stinner8f674cc2013-04-17 23:02:17 +020014692 _PyUnicodeWriter_Init(&ctx.writer);
14693 ctx.writer.min_length = ctx.fmtcnt + 100;
14694 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014695
Guido van Rossumd57fd912000-03-10 22:53:23 +000014696 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014697 ctx.arglen = PyTuple_Size(args);
14698 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014699 }
14700 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014701 ctx.arglen = -1;
14702 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014703 }
Victor Stinnera47082312012-10-04 02:19:54 +020014704 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014705 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014706 ctx.dict = args;
14707 else
14708 ctx.dict = NULL;
14709 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014710
Victor Stinnera47082312012-10-04 02:19:54 +020014711 while (--ctx.fmtcnt >= 0) {
14712 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014713 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014714
14715 nonfmtpos = ctx.fmtpos++;
14716 while (ctx.fmtcnt >= 0 &&
14717 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14718 ctx.fmtpos++;
14719 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014720 }
Victor Stinnera47082312012-10-04 02:19:54 +020014721 if (ctx.fmtcnt < 0) {
14722 ctx.fmtpos--;
14723 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014724 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014725
Victor Stinnercfc4c132013-04-03 01:48:39 +020014726 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14727 nonfmtpos, ctx.fmtpos) < 0)
14728 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014729 }
14730 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014731 ctx.fmtpos++;
14732 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014733 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014734 }
14735 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014736
Victor Stinnera47082312012-10-04 02:19:54 +020014737 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014738 PyErr_SetString(PyExc_TypeError,
14739 "not all arguments converted during string formatting");
14740 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014741 }
14742
Victor Stinnera47082312012-10-04 02:19:54 +020014743 if (ctx.args_owned) {
14744 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014745 }
Victor Stinnera47082312012-10-04 02:19:54 +020014746 Py_DECREF(ctx.fmtstr);
14747 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014748
Benjamin Peterson29060642009-01-31 22:14:21 +000014749 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014750 Py_DECREF(ctx.fmtstr);
14751 _PyUnicodeWriter_Dealloc(&ctx.writer);
14752 if (ctx.args_owned) {
14753 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014754 }
14755 return NULL;
14756}
14757
Jeremy Hylton938ace62002-07-17 16:30:39 +000014758static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014759unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14760
Tim Peters6d6c1a32001-08-02 04:15:00 +000014761static PyObject *
14762unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14763{
Benjamin Peterson29060642009-01-31 22:14:21 +000014764 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014765 static char *kwlist[] = {"object", "encoding", "errors", 0};
14766 char *encoding = NULL;
14767 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014768
Benjamin Peterson14339b62009-01-31 16:36:08 +000014769 if (type != &PyUnicode_Type)
14770 return unicode_subtype_new(type, args, kwds);
14771 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014772 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014773 return NULL;
14774 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014775 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014776 if (encoding == NULL && errors == NULL)
14777 return PyObject_Str(x);
14778 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014779 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014780}
14781
Guido van Rossume023fe02001-08-30 03:12:59 +000014782static PyObject *
14783unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14784{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014785 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014786 Py_ssize_t length, char_size;
14787 int share_wstr, share_utf8;
14788 unsigned int kind;
14789 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014790
Benjamin Peterson14339b62009-01-31 16:36:08 +000014791 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014792
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014793 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014794 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014795 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014796 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014797 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014798 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014799 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014800 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014801
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014802 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014803 if (self == NULL) {
14804 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014805 return NULL;
14806 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014807 kind = PyUnicode_KIND(unicode);
14808 length = PyUnicode_GET_LENGTH(unicode);
14809
14810 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014811#ifdef Py_DEBUG
14812 _PyUnicode_HASH(self) = -1;
14813#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014814 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014815#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014816 _PyUnicode_STATE(self).interned = 0;
14817 _PyUnicode_STATE(self).kind = kind;
14818 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014819 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014820 _PyUnicode_STATE(self).ready = 1;
14821 _PyUnicode_WSTR(self) = NULL;
14822 _PyUnicode_UTF8_LENGTH(self) = 0;
14823 _PyUnicode_UTF8(self) = NULL;
14824 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014825 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014826
14827 share_utf8 = 0;
14828 share_wstr = 0;
14829 if (kind == PyUnicode_1BYTE_KIND) {
14830 char_size = 1;
14831 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14832 share_utf8 = 1;
14833 }
14834 else if (kind == PyUnicode_2BYTE_KIND) {
14835 char_size = 2;
14836 if (sizeof(wchar_t) == 2)
14837 share_wstr = 1;
14838 }
14839 else {
14840 assert(kind == PyUnicode_4BYTE_KIND);
14841 char_size = 4;
14842 if (sizeof(wchar_t) == 4)
14843 share_wstr = 1;
14844 }
14845
14846 /* Ensure we won't overflow the length. */
14847 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14848 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014849 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014850 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014851 data = PyObject_MALLOC((length + 1) * char_size);
14852 if (data == NULL) {
14853 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014854 goto onError;
14855 }
14856
Victor Stinnerc3c74152011-10-02 20:39:55 +020014857 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014858 if (share_utf8) {
14859 _PyUnicode_UTF8_LENGTH(self) = length;
14860 _PyUnicode_UTF8(self) = data;
14861 }
14862 if (share_wstr) {
14863 _PyUnicode_WSTR_LENGTH(self) = length;
14864 _PyUnicode_WSTR(self) = (wchar_t *)data;
14865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014866
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014867 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014868 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014869 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014870#ifdef Py_DEBUG
14871 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14872#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014873 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014874 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014875
14876onError:
14877 Py_DECREF(unicode);
14878 Py_DECREF(self);
14879 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014880}
14881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014882PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014883"str(object='') -> str\n\
14884str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014885\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014886Create a new string object from the given object. If encoding or\n\
14887errors is specified, then the object must expose a data buffer\n\
14888that will be decoded using the given encoding and error handler.\n\
14889Otherwise, returns the result of object.__str__() (if defined)\n\
14890or repr(object).\n\
14891encoding defaults to sys.getdefaultencoding().\n\
14892errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014893
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014894static PyObject *unicode_iter(PyObject *seq);
14895
Guido van Rossumd57fd912000-03-10 22:53:23 +000014896PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014897 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014898 "str", /* tp_name */
14899 sizeof(PyUnicodeObject), /* tp_size */
14900 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014901 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014902 (destructor)unicode_dealloc, /* tp_dealloc */
14903 0, /* tp_print */
14904 0, /* tp_getattr */
14905 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014906 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014907 unicode_repr, /* tp_repr */
14908 &unicode_as_number, /* tp_as_number */
14909 &unicode_as_sequence, /* tp_as_sequence */
14910 &unicode_as_mapping, /* tp_as_mapping */
14911 (hashfunc) unicode_hash, /* tp_hash*/
14912 0, /* tp_call*/
14913 (reprfunc) unicode_str, /* tp_str */
14914 PyObject_GenericGetAttr, /* tp_getattro */
14915 0, /* tp_setattro */
14916 0, /* tp_as_buffer */
14917 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014918 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014919 unicode_doc, /* tp_doc */
14920 0, /* tp_traverse */
14921 0, /* tp_clear */
14922 PyUnicode_RichCompare, /* tp_richcompare */
14923 0, /* tp_weaklistoffset */
14924 unicode_iter, /* tp_iter */
14925 0, /* tp_iternext */
14926 unicode_methods, /* tp_methods */
14927 0, /* tp_members */
14928 0, /* tp_getset */
14929 &PyBaseObject_Type, /* tp_base */
14930 0, /* tp_dict */
14931 0, /* tp_descr_get */
14932 0, /* tp_descr_set */
14933 0, /* tp_dictoffset */
14934 0, /* tp_init */
14935 0, /* tp_alloc */
14936 unicode_new, /* tp_new */
14937 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014938};
14939
14940/* Initialize the Unicode implementation */
14941
Victor Stinner3a50e702011-10-18 21:21:00 +020014942int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014943{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014944 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014945 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014946 0x000A, /* LINE FEED */
14947 0x000D, /* CARRIAGE RETURN */
14948 0x001C, /* FILE SEPARATOR */
14949 0x001D, /* GROUP SEPARATOR */
14950 0x001E, /* RECORD SEPARATOR */
14951 0x0085, /* NEXT LINE */
14952 0x2028, /* LINE SEPARATOR */
14953 0x2029, /* PARAGRAPH SEPARATOR */
14954 };
14955
Fred Drakee4315f52000-05-09 19:53:39 +000014956 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014957 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014958 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014959 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014960 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014961
Guido van Rossumcacfc072002-05-24 19:01:59 +000014962 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014963 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014964
14965 /* initialize the linebreak bloom filter */
14966 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014967 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014968 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014969
Christian Heimes26532f72013-07-20 14:57:16 +020014970 if (PyType_Ready(&EncodingMapType) < 0)
14971 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014972
Benjamin Petersonc4311282012-10-30 23:21:10 -040014973 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14974 Py_FatalError("Can't initialize field name iterator type");
14975
14976 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14977 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014978
Victor Stinner3a50e702011-10-18 21:21:00 +020014979#ifdef HAVE_MBCS
14980 winver.dwOSVersionInfoSize = sizeof(winver);
14981 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14982 PyErr_SetFromWindowsErr(0);
14983 return -1;
14984 }
14985#endif
14986 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014987}
14988
14989/* Finalize the Unicode implementation */
14990
Christian Heimesa156e092008-02-16 07:38:31 +000014991int
14992PyUnicode_ClearFreeList(void)
14993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014994 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014995}
14996
Guido van Rossumd57fd912000-03-10 22:53:23 +000014997void
Thomas Wouters78890102000-07-22 19:25:51 +000014998_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014999{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015000 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015001
Serhiy Storchaka05997252013-01-26 12:14:02 +020015002 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015003
Serhiy Storchaka05997252013-01-26 12:14:02 +020015004 for (i = 0; i < 256; i++)
15005 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015006 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015007 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015008}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015009
Walter Dörwald16807132007-05-25 13:52:07 +000015010void
15011PyUnicode_InternInPlace(PyObject **p)
15012{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015013 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015014 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015015#ifdef Py_DEBUG
15016 assert(s != NULL);
15017 assert(_PyUnicode_CHECK(s));
15018#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015019 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015020 return;
15021#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015022 /* If it's a subclass, we don't really know what putting
15023 it in the interned dict might do. */
15024 if (!PyUnicode_CheckExact(s))
15025 return;
15026 if (PyUnicode_CHECK_INTERNED(s))
15027 return;
15028 if (interned == NULL) {
15029 interned = PyDict_New();
15030 if (interned == NULL) {
15031 PyErr_Clear(); /* Don't leave an exception */
15032 return;
15033 }
15034 }
15035 /* It might be that the GetItem call fails even
15036 though the key is present in the dictionary,
15037 namely when this happens during a stack overflow. */
15038 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015039 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015040 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015041
Victor Stinnerf0335102013-04-14 19:13:03 +020015042 if (t) {
15043 Py_INCREF(t);
15044 Py_DECREF(*p);
15045 *p = t;
15046 return;
15047 }
Walter Dörwald16807132007-05-25 13:52:07 +000015048
Benjamin Peterson14339b62009-01-31 16:36:08 +000015049 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015050 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015051 PyErr_Clear();
15052 PyThreadState_GET()->recursion_critical = 0;
15053 return;
15054 }
15055 PyThreadState_GET()->recursion_critical = 0;
15056 /* The two references in interned are not counted by refcnt.
15057 The deallocator will take care of this */
15058 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015059 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015060}
15061
15062void
15063PyUnicode_InternImmortal(PyObject **p)
15064{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015065 PyUnicode_InternInPlace(p);
15066 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015067 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015068 Py_INCREF(*p);
15069 }
Walter Dörwald16807132007-05-25 13:52:07 +000015070}
15071
15072PyObject *
15073PyUnicode_InternFromString(const char *cp)
15074{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015075 PyObject *s = PyUnicode_FromString(cp);
15076 if (s == NULL)
15077 return NULL;
15078 PyUnicode_InternInPlace(&s);
15079 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015080}
15081
Alexander Belopolsky40018472011-02-26 01:02:56 +000015082void
15083_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015084{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015085 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015086 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 Py_ssize_t i, n;
15088 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015089
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 if (interned == NULL || !PyDict_Check(interned))
15091 return;
15092 keys = PyDict_Keys(interned);
15093 if (keys == NULL || !PyList_Check(keys)) {
15094 PyErr_Clear();
15095 return;
15096 }
Walter Dörwald16807132007-05-25 13:52:07 +000015097
Benjamin Peterson14339b62009-01-31 16:36:08 +000015098 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15099 detector, interned unicode strings are not forcibly deallocated;
15100 rather, we give them their stolen references back, and then clear
15101 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015102
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 n = PyList_GET_SIZE(keys);
15104 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015105 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015106 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015107 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015108 if (PyUnicode_READY(s) == -1) {
15109 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015110 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015112 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015113 case SSTATE_NOT_INTERNED:
15114 /* XXX Shouldn't happen */
15115 break;
15116 case SSTATE_INTERNED_IMMORTAL:
15117 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015118 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015119 break;
15120 case SSTATE_INTERNED_MORTAL:
15121 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015122 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 break;
15124 default:
15125 Py_FatalError("Inconsistent interned string state.");
15126 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015127 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 }
15129 fprintf(stderr, "total size of all interned strings: "
15130 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15131 "mortal/immortal\n", mortal_size, immortal_size);
15132 Py_DECREF(keys);
15133 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015134 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015135}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015136
15137
15138/********************* Unicode Iterator **************************/
15139
15140typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 PyObject_HEAD
15142 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015143 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015144} unicodeiterobject;
15145
15146static void
15147unicodeiter_dealloc(unicodeiterobject *it)
15148{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015149 _PyObject_GC_UNTRACK(it);
15150 Py_XDECREF(it->it_seq);
15151 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015152}
15153
15154static int
15155unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15156{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015157 Py_VISIT(it->it_seq);
15158 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015159}
15160
15161static PyObject *
15162unicodeiter_next(unicodeiterobject *it)
15163{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015164 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015165
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 assert(it != NULL);
15167 seq = it->it_seq;
15168 if (seq == NULL)
15169 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015170 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015172 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15173 int kind = PyUnicode_KIND(seq);
15174 void *data = PyUnicode_DATA(seq);
15175 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15176 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 if (item != NULL)
15178 ++it->it_index;
15179 return item;
15180 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015181
Benjamin Peterson14339b62009-01-31 16:36:08 +000015182 Py_DECREF(seq);
15183 it->it_seq = NULL;
15184 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015185}
15186
15187static PyObject *
15188unicodeiter_len(unicodeiterobject *it)
15189{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015190 Py_ssize_t len = 0;
15191 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015192 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015193 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015194}
15195
15196PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15197
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015198static PyObject *
15199unicodeiter_reduce(unicodeiterobject *it)
15200{
15201 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015202 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015203 it->it_seq, it->it_index);
15204 } else {
15205 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15206 if (u == NULL)
15207 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015208 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015209 }
15210}
15211
15212PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15213
15214static PyObject *
15215unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15216{
15217 Py_ssize_t index = PyLong_AsSsize_t(state);
15218 if (index == -1 && PyErr_Occurred())
15219 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015220 if (it->it_seq != NULL) {
15221 if (index < 0)
15222 index = 0;
15223 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15224 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15225 it->it_index = index;
15226 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015227 Py_RETURN_NONE;
15228}
15229
15230PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15231
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015232static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015233 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015234 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015235 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15236 reduce_doc},
15237 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15238 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015239 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015240};
15241
15242PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015243 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15244 "str_iterator", /* tp_name */
15245 sizeof(unicodeiterobject), /* tp_basicsize */
15246 0, /* tp_itemsize */
15247 /* methods */
15248 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15249 0, /* tp_print */
15250 0, /* tp_getattr */
15251 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015252 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 0, /* tp_repr */
15254 0, /* tp_as_number */
15255 0, /* tp_as_sequence */
15256 0, /* tp_as_mapping */
15257 0, /* tp_hash */
15258 0, /* tp_call */
15259 0, /* tp_str */
15260 PyObject_GenericGetAttr, /* tp_getattro */
15261 0, /* tp_setattro */
15262 0, /* tp_as_buffer */
15263 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15264 0, /* tp_doc */
15265 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15266 0, /* tp_clear */
15267 0, /* tp_richcompare */
15268 0, /* tp_weaklistoffset */
15269 PyObject_SelfIter, /* tp_iter */
15270 (iternextfunc)unicodeiter_next, /* tp_iternext */
15271 unicodeiter_methods, /* tp_methods */
15272 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015273};
15274
15275static PyObject *
15276unicode_iter(PyObject *seq)
15277{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015278 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015279
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 if (!PyUnicode_Check(seq)) {
15281 PyErr_BadInternalCall();
15282 return NULL;
15283 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015284 if (PyUnicode_READY(seq) == -1)
15285 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15287 if (it == NULL)
15288 return NULL;
15289 it->it_index = 0;
15290 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015291 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015292 _PyObject_GC_TRACK(it);
15293 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015294}
15295
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015296
15297size_t
15298Py_UNICODE_strlen(const Py_UNICODE *u)
15299{
15300 int res = 0;
15301 while(*u++)
15302 res++;
15303 return res;
15304}
15305
15306Py_UNICODE*
15307Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15308{
15309 Py_UNICODE *u = s1;
15310 while ((*u++ = *s2++));
15311 return s1;
15312}
15313
15314Py_UNICODE*
15315Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15316{
15317 Py_UNICODE *u = s1;
15318 while ((*u++ = *s2++))
15319 if (n-- == 0)
15320 break;
15321 return s1;
15322}
15323
15324Py_UNICODE*
15325Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15326{
15327 Py_UNICODE *u1 = s1;
15328 u1 += Py_UNICODE_strlen(u1);
15329 Py_UNICODE_strcpy(u1, s2);
15330 return s1;
15331}
15332
15333int
15334Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15335{
15336 while (*s1 && *s2 && *s1 == *s2)
15337 s1++, s2++;
15338 if (*s1 && *s2)
15339 return (*s1 < *s2) ? -1 : +1;
15340 if (*s1)
15341 return 1;
15342 if (*s2)
15343 return -1;
15344 return 0;
15345}
15346
15347int
15348Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15349{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015350 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015351 for (; n != 0; n--) {
15352 u1 = *s1;
15353 u2 = *s2;
15354 if (u1 != u2)
15355 return (u1 < u2) ? -1 : +1;
15356 if (u1 == '\0')
15357 return 0;
15358 s1++;
15359 s2++;
15360 }
15361 return 0;
15362}
15363
15364Py_UNICODE*
15365Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15366{
15367 const Py_UNICODE *p;
15368 for (p = s; *p; p++)
15369 if (*p == c)
15370 return (Py_UNICODE*)p;
15371 return NULL;
15372}
15373
15374Py_UNICODE*
15375Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15376{
15377 const Py_UNICODE *p;
15378 p = s + Py_UNICODE_strlen(s);
15379 while (p != s) {
15380 p--;
15381 if (*p == c)
15382 return (Py_UNICODE*)p;
15383 }
15384 return NULL;
15385}
Victor Stinner331ea922010-08-10 16:37:20 +000015386
Victor Stinner71133ff2010-09-01 23:43:53 +000015387Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015388PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015389{
Victor Stinner577db2c2011-10-11 22:12:48 +020015390 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015391 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015393 if (!PyUnicode_Check(unicode)) {
15394 PyErr_BadArgument();
15395 return NULL;
15396 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015397 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015398 if (u == NULL)
15399 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015400 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015401 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015402 PyErr_NoMemory();
15403 return NULL;
15404 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015405 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015406 size *= sizeof(Py_UNICODE);
15407 copy = PyMem_Malloc(size);
15408 if (copy == NULL) {
15409 PyErr_NoMemory();
15410 return NULL;
15411 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015412 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015413 return copy;
15414}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015415
Georg Brandl66c221e2010-10-14 07:04:07 +000015416/* A _string module, to export formatter_parser and formatter_field_name_split
15417 to the string.Formatter class implemented in Python. */
15418
15419static PyMethodDef _string_methods[] = {
15420 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15421 METH_O, PyDoc_STR("split the argument as a field name")},
15422 {"formatter_parser", (PyCFunction) formatter_parser,
15423 METH_O, PyDoc_STR("parse the argument as a format string")},
15424 {NULL, NULL}
15425};
15426
15427static struct PyModuleDef _string_module = {
15428 PyModuleDef_HEAD_INIT,
15429 "_string",
15430 PyDoc_STR("string helper module"),
15431 0,
15432 _string_methods,
15433 NULL,
15434 NULL,
15435 NULL,
15436 NULL
15437};
15438
15439PyMODINIT_FUNC
15440PyInit__string(void)
15441{
15442 return PyModule_Create(&_string_module);
15443}
15444
15445
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015446#ifdef __cplusplus
15447}
15448#endif