blob: 72272c70528b65b856553e7d51c2911c8ceb06bd [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Larry Hastings61272b72014-01-07 12:41:53 -080050/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080051class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080052[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080053/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080054
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055/* --- Globals ------------------------------------------------------------
56
Serhiy Storchaka05997252013-01-26 12:14:02 +020057NOTE: In the interpreter's initialization phase, some globals are currently
58 initialized dynamically as needed. In the process Unicode objects may
59 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000060
61*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64#ifdef __cplusplus
65extern "C" {
66#endif
67
Victor Stinner8faf8212011-12-08 22:14:11 +010068/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
69#define MAX_UNICODE 0x10ffff
70
Victor Stinner910337b2011-10-03 03:20:16 +020071#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020072# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020073#else
74# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
75#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020076
Victor Stinnere90fe6a2011-10-01 16:48:13 +020077#define _PyUnicode_UTF8(op) \
78 (((PyCompactUnicodeObject*)(op))->utf8)
79#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020080 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 assert(PyUnicode_IS_READY(op)), \
82 PyUnicode_IS_COMPACT_ASCII(op) ? \
83 ((char*)((PyASCIIObject*)(op) + 1)) : \
84 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020085#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020086 (((PyCompactUnicodeObject*)(op))->utf8_length)
87#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020088 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 assert(PyUnicode_IS_READY(op)), \
90 PyUnicode_IS_COMPACT_ASCII(op) ? \
91 ((PyASCIIObject*)(op))->length : \
92 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020093#define _PyUnicode_WSTR(op) \
94 (((PyASCIIObject*)(op))->wstr)
95#define _PyUnicode_WSTR_LENGTH(op) \
96 (((PyCompactUnicodeObject*)(op))->wstr_length)
97#define _PyUnicode_LENGTH(op) \
98 (((PyASCIIObject *)(op))->length)
99#define _PyUnicode_STATE(op) \
100 (((PyASCIIObject *)(op))->state)
101#define _PyUnicode_HASH(op) \
102 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200103#define _PyUnicode_KIND(op) \
104 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200105 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_GET_LENGTH(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_DATA_ANY(op) \
110 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200130 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200131 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200132 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
133
Victor Stinner03490912011-10-03 23:45:12 +0200134/* true if the Unicode object has an allocated wstr memory block
135 (not shared with other data) */
136#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200137 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100148 to_type *_to = (to_type *)(to); \
149 const from_type *_iter = (from_type *)(begin); \
150 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200153 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Walter Dörwald16807132007-05-25 13:52:07 +0000165/* This dictionary holds all interned unicode strings. Note that references
166 to strings in this dictionary are *not* counted in the string's ob_refcnt.
167 When the interned string reaches a refcnt of 0 the string deallocation
168 function will delete the reference from this dictionary.
169
170 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000171 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000172*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200173static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000174
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000175/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200176static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200177
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179 do { \
180 if (unicode_empty != NULL) \
181 Py_INCREF(unicode_empty); \
182 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183 unicode_empty = PyUnicode_New(0, 0); \
184 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200185 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
187 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191#define _Py_RETURN_UNICODE_EMPTY() \
192 do { \
193 _Py_INCREF_UNICODE_EMPTY(); \
194 return unicode_empty; \
195 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200197/* Forward declaration */
198Py_LOCAL_INLINE(int)
199_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
200
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200206static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100242static int unicode_modifiable(PyObject *unicode);
243
Victor Stinnerfe226c02011-10-03 03:52:20 +0200244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100246_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200247static PyObject *
248_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
249static PyObject *
250_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
251
252static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100255 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
257
Alexander Belopolsky40018472011-02-26 01:02:56 +0000258static void
259raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300260 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100261 PyObject *unicode,
262 Py_ssize_t startpos, Py_ssize_t endpos,
263 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Same for linebreaks */
266static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000268/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* 0x000B, * LINE TABULATION */
270/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x001C, * FILE SEPARATOR */
275/* 0x001D, * GROUP SEPARATOR */
276/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 1, 1, 1, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000282
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000291};
292
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300293/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
294 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000296PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000298#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 /* This is actually an illegal character, so it should
302 not be passed to unichr. */
303 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000304#endif
305}
306
Victor Stinner910337b2011-10-03 03:20:16 +0200307#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200308int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100309_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200310{
311 PyASCIIObject *ascii;
312 unsigned int kind;
313
314 assert(PyUnicode_Check(op));
315
316 ascii = (PyASCIIObject *)op;
317 kind = ascii->state.kind;
318
Victor Stinnera3b334d2011-10-03 13:53:37 +0200319 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200325 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200326
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 if (ascii->state.compact == 1) {
328 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(kind == PyUnicode_1BYTE_KIND
330 || kind == PyUnicode_2BYTE_KIND
331 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200333 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100335 }
336 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
338
339 data = unicode->data.any;
340 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->length == 0);
342 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100346 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200347 assert(ascii->wstr != NULL);
348 assert(data == NULL);
349 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200391 void *data;
392 Py_UCS4 ch;
393
394 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 for (i=0; i < ascii->length; i++)
396 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 if (ch > maxchar)
399 maxchar = ch;
400 }
401 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100402 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 255);
405 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 else
407 assert(maxchar < 128);
408 }
Victor Stinner77faf692011-11-20 18:56:05 +0100409 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 assert(maxchar <= 0xFFFF);
412 }
413 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200414 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100415 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100416 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200417 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200418 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100423static PyObject*
424unicode_result_wchar(PyObject *unicode)
425{
426#ifndef Py_DEBUG
427 Py_ssize_t len;
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 len = _PyUnicode_WSTR_LENGTH(unicode);
430 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200432 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 }
434
435 if (len == 1) {
436 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100437 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
439 Py_DECREF(unicode);
440 return latin1_char;
441 }
442 }
443
444 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200445 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 return NULL;
447 }
448#else
Victor Stinneraa771272012-10-04 02:32:58 +0200449 assert(Py_REFCNT(unicode) == 1);
450
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100451 /* don't make the result ready in debug mode to ensure that the caller
452 makes the string ready before using it */
453 assert(_PyUnicode_CheckConsistency(unicode, 1));
454#endif
455 return unicode;
456}
457
458static PyObject*
459unicode_result_ready(PyObject *unicode)
460{
461 Py_ssize_t length;
462
463 length = PyUnicode_GET_LENGTH(unicode);
464 if (length == 0) {
465 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200467 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 }
469 return unicode_empty;
470 }
471
472 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200473 void *data = PyUnicode_DATA(unicode);
474 int kind = PyUnicode_KIND(unicode);
475 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 if (ch < 256) {
477 PyObject *latin1_char = unicode_latin1[ch];
478 if (latin1_char != NULL) {
479 if (unicode != latin1_char) {
480 Py_INCREF(latin1_char);
481 Py_DECREF(unicode);
482 }
483 return latin1_char;
484 }
485 else {
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 Py_INCREF(unicode);
488 unicode_latin1[ch] = unicode;
489 return unicode;
490 }
491 }
492 }
493
494 assert(_PyUnicode_CheckConsistency(unicode, 1));
495 return unicode;
496}
497
498static PyObject*
499unicode_result(PyObject *unicode)
500{
501 assert(_PyUnicode_CHECK(unicode));
502 if (PyUnicode_IS_READY(unicode))
503 return unicode_result_ready(unicode);
504 else
505 return unicode_result_wchar(unicode);
506}
507
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508static PyObject*
509unicode_result_unchanged(PyObject *unicode)
510{
511 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500512 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100513 return NULL;
514 Py_INCREF(unicode);
515 return unicode;
516 }
517 else
518 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100519 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100520}
521
Victor Stinner3a50e702011-10-18 21:21:00 +0200522#ifdef HAVE_MBCS
523static OSVERSIONINFOEX winver;
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526/* --- Bloom Filters ----------------------------------------------------- */
527
528/* stuff to implement simple "bloom filters" for Unicode characters.
529 to keep things simple, we use a single bitmask, using the least 5
530 bits from each unicode characters as the bit index. */
531
532/* the linebreak mask is set up by Unicode_Init below */
533
Antoine Pitrouf068f942010-01-13 14:19:12 +0000534#if LONG_BIT >= 128
535#define BLOOM_WIDTH 128
536#elif LONG_BIT >= 64
537#define BLOOM_WIDTH 64
538#elif LONG_BIT >= 32
539#define BLOOM_WIDTH 32
540#else
541#error "LONG_BIT is smaller than 32"
542#endif
543
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544#define BLOOM_MASK unsigned long
545
Serhiy Storchaka05997252013-01-26 12:14:02 +0200546static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Antoine Pitrouf068f942010-01-13 14:19:12 +0000548#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Benjamin Peterson29060642009-01-31 22:14:21 +0000550#define BLOOM_LINEBREAK(ch) \
551 ((ch) < 128U ? ascii_linebreak[(ch)] : \
552 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
Alexander Belopolsky40018472011-02-26 01:02:56 +0000554Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556{
Victor Stinnera85af502013-04-09 21:53:54 +0200557#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
558 do { \
559 TYPE *data = (TYPE *)PTR; \
560 TYPE *end = data + LEN; \
561 Py_UCS4 ch; \
562 for (; data != end; data++) { \
563 ch = *data; \
564 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
565 } \
566 break; \
567 } while (0)
568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 /* calculate simple bloom-style bitmask for a given unicode string */
570
Antoine Pitrouf068f942010-01-13 14:19:12 +0000571 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200574 switch (kind) {
575 case PyUnicode_1BYTE_KIND:
576 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
577 break;
578 case PyUnicode_2BYTE_KIND:
579 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
580 break;
581 case PyUnicode_4BYTE_KIND:
582 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
583 break;
584 default:
585 assert(0);
586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200588
589#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590}
591
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200592/* Compilation of templated routines */
593
594#include "stringlib/asciilib.h"
595#include "stringlib/fastsearch.h"
596#include "stringlib/partition.h"
597#include "stringlib/split.h"
598#include "stringlib/count.h"
599#include "stringlib/find.h"
600#include "stringlib/find_max_char.h"
601#include "stringlib/localeutil.h"
602#include "stringlib/undef.h"
603
604#include "stringlib/ucs1lib.h"
605#include "stringlib/fastsearch.h"
606#include "stringlib/partition.h"
607#include "stringlib/split.h"
608#include "stringlib/count.h"
609#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300610#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200611#include "stringlib/find_max_char.h"
612#include "stringlib/localeutil.h"
613#include "stringlib/undef.h"
614
615#include "stringlib/ucs2lib.h"
616#include "stringlib/fastsearch.h"
617#include "stringlib/partition.h"
618#include "stringlib/split.h"
619#include "stringlib/count.h"
620#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300621#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200622#include "stringlib/find_max_char.h"
623#include "stringlib/localeutil.h"
624#include "stringlib/undef.h"
625
626#include "stringlib/ucs4lib.h"
627#include "stringlib/fastsearch.h"
628#include "stringlib/partition.h"
629#include "stringlib/split.h"
630#include "stringlib/count.h"
631#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300632#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200633#include "stringlib/find_max_char.h"
634#include "stringlib/localeutil.h"
635#include "stringlib/undef.h"
636
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637#include "stringlib/unicodedefs.h"
638#include "stringlib/fastsearch.h"
639#include "stringlib/count.h"
640#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100641#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* --- Unicode Object ----------------------------------------------------- */
644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200646fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
649 Py_ssize_t size, Py_UCS4 ch,
650 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200652 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
653
654 switch (kind) {
655 case PyUnicode_1BYTE_KIND:
656 {
657 Py_UCS1 ch1 = (Py_UCS1) ch;
658 if (ch1 == ch)
659 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
660 else
661 return -1;
662 }
663 case PyUnicode_2BYTE_KIND:
664 {
665 Py_UCS2 ch2 = (Py_UCS2) ch;
666 if (ch2 == ch)
667 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
668 else
669 return -1;
670 }
671 case PyUnicode_4BYTE_KIND:
672 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
673 default:
674 assert(0);
675 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677}
678
Victor Stinnerafffce42012-10-03 23:03:17 +0200679#ifdef Py_DEBUG
680/* Fill the data of an Unicode string with invalid characters to detect bugs
681 earlier.
682
683 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
684 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
685 invalid character in Unicode 6.0. */
686static void
687unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
688{
689 int kind = PyUnicode_KIND(unicode);
690 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
691 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
692 if (length <= old_length)
693 return;
694 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
695}
696#endif
697
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698static PyObject*
699resize_compact(PyObject *unicode, Py_ssize_t length)
700{
701 Py_ssize_t char_size;
702 Py_ssize_t struct_size;
703 Py_ssize_t new_size;
704 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100705 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200706#ifdef Py_DEBUG
707 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
708#endif
709
Victor Stinner79891572012-05-03 13:43:07 +0200710 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100712 assert(PyUnicode_IS_COMPACT(unicode));
713
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200714 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100715 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 struct_size = sizeof(PyASCIIObject);
717 else
718 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200719 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
722 PyErr_NoMemory();
723 return NULL;
724 }
725 new_size = (struct_size + (length + 1) * char_size);
726
Victor Stinner84def372011-12-11 20:04:56 +0100727 _Py_DEC_REFTOTAL;
728 _Py_ForgetReference(unicode);
729
730 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
731 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100732 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733 PyErr_NoMemory();
734 return NULL;
735 }
Victor Stinner84def372011-12-11 20:04:56 +0100736 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100738
Victor Stinnerfe226c02011-10-03 03:52:20 +0200739 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200740 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100742 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200743 _PyUnicode_WSTR_LENGTH(unicode) = length;
744 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100745 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
746 PyObject_DEL(_PyUnicode_WSTR(unicode));
747 _PyUnicode_WSTR(unicode) = NULL;
748 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200749#ifdef Py_DEBUG
750 unicode_fill_invalid(unicode, old_length);
751#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200752 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
753 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200754 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200755 return unicode;
756}
757
Alexander Belopolsky40018472011-02-26 01:02:56 +0000758static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200759resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000760{
Victor Stinner95663112011-10-04 01:03:50 +0200761 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100762 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000765
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 if (PyUnicode_IS_READY(unicode)) {
767 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200768 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200770#ifdef Py_DEBUG
771 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
772#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773
774 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200775 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200776 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
777 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200778
779 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
780 PyErr_NoMemory();
781 return -1;
782 }
783 new_size = (length + 1) * char_size;
784
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
786 {
787 PyObject_DEL(_PyUnicode_UTF8(unicode));
788 _PyUnicode_UTF8(unicode) = NULL;
789 _PyUnicode_UTF8_LENGTH(unicode) = 0;
790 }
791
Victor Stinnerfe226c02011-10-03 03:52:20 +0200792 data = (PyObject *)PyObject_REALLOC(data, new_size);
793 if (data == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200798 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200799 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 _PyUnicode_WSTR_LENGTH(unicode) = length;
801 }
802 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200803 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200804 _PyUnicode_UTF8_LENGTH(unicode) = length;
805 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806 _PyUnicode_LENGTH(unicode) = length;
807 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200808#ifdef Py_DEBUG
809 unicode_fill_invalid(unicode, old_length);
810#endif
Victor Stinner95663112011-10-04 01:03:50 +0200811 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200812 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200814 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200815 }
Victor Stinner95663112011-10-04 01:03:50 +0200816 assert(_PyUnicode_WSTR(unicode) != NULL);
817
818 /* check for integer overflow */
819 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
820 PyErr_NoMemory();
821 return -1;
822 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100823 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200824 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100825 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200826 if (!wstr) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 _PyUnicode_WSTR(unicode) = wstr;
831 _PyUnicode_WSTR(unicode)[length] = 0;
832 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200833 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000834 return 0;
835}
836
Victor Stinnerfe226c02011-10-03 03:52:20 +0200837static PyObject*
838resize_copy(PyObject *unicode, Py_ssize_t length)
839{
840 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100841 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100843
Benjamin Petersonbac79492012-01-14 13:34:47 -0500844 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100845 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200846
847 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
848 if (copy == NULL)
849 return NULL;
850
851 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200852 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200853 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200854 }
855 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200856 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100857
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200858 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200859 if (w == NULL)
860 return NULL;
861 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
862 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200863 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
864 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200865 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200866 }
867}
868
Guido van Rossumd57fd912000-03-10 22:53:23 +0000869/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000870 Ux0000 terminated; some code (e.g. new_identifier)
871 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000872
873 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000874 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875
876*/
877
Alexander Belopolsky40018472011-02-26 01:02:56 +0000878static PyUnicodeObject *
879_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200881 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200882 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885 if (length == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888 }
889
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000890 /* Ensure we won't overflow the size. */
891 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
892 return (PyUnicodeObject *)PyErr_NoMemory();
893 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894 if (length < 0) {
895 PyErr_SetString(PyExc_SystemError,
896 "Negative size passed to _PyUnicode_New");
897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000898 }
899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
901 if (unicode == NULL)
902 return NULL;
903 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100904
905 _PyUnicode_WSTR_LENGTH(unicode) = length;
906 _PyUnicode_HASH(unicode) = -1;
907 _PyUnicode_STATE(unicode).interned = 0;
908 _PyUnicode_STATE(unicode).kind = 0;
909 _PyUnicode_STATE(unicode).compact = 0;
910 _PyUnicode_STATE(unicode).ready = 0;
911 _PyUnicode_STATE(unicode).ascii = 0;
912 _PyUnicode_DATA_ANY(unicode) = NULL;
913 _PyUnicode_LENGTH(unicode) = 0;
914 _PyUnicode_UTF8(unicode) = NULL;
915 _PyUnicode_UTF8_LENGTH(unicode) = 0;
916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
918 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100919 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000920 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100921 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000922 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
Jeremy Hyltond8082792003-09-16 19:41:39 +0000924 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000925 * the caller fails before initializing str -- unicode_resize()
926 * reads str[0], and the Keep-Alive optimization can keep memory
927 * allocated for str alive across a call to unicode_dealloc(unicode).
928 * We don't want unicode_resize to read uninitialized memory in
929 * that case.
930 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 _PyUnicode_WSTR(unicode)[0] = 0;
932 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100933
Victor Stinner7931d9a2011-11-04 00:22:48 +0100934 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000935 return unicode;
936}
937
Victor Stinnerf42dc442011-10-02 23:33:16 +0200938static const char*
939unicode_kind_name(PyObject *unicode)
940{
Victor Stinner42dfd712011-10-03 14:41:45 +0200941 /* don't check consistency: unicode_kind_name() is called from
942 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 if (!PyUnicode_IS_COMPACT(unicode))
944 {
945 if (!PyUnicode_IS_READY(unicode))
946 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600947 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 {
949 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200951 return "legacy ascii";
952 else
953 return "legacy latin1";
954 case PyUnicode_2BYTE_KIND:
955 return "legacy UCS2";
956 case PyUnicode_4BYTE_KIND:
957 return "legacy UCS4";
958 default:
959 return "<legacy invalid kind>";
960 }
961 }
962 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600963 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200965 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200966 return "ascii";
967 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200972 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200973 default:
974 return "<invalid compact kind>";
975 }
976}
977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979/* Functions wrapping macros for use in debugger */
980char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200981 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982}
983
984void *_PyUnicode_compact_data(void *unicode) {
985 return _PyUnicode_COMPACT_DATA(unicode);
986}
987void *_PyUnicode_data(void *unicode){
988 printf("obj %p\n", unicode);
989 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
990 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
991 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
992 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
993 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
994 return PyUnicode_DATA(unicode);
995}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200996
997void
998_PyUnicode_Dump(PyObject *op)
999{
1000 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1002 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1003 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001004
Victor Stinnera849a4b2011-10-03 12:12:11 +02001005 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 {
1007 if (ascii->state.ascii)
1008 data = (ascii + 1);
1009 else
1010 data = (compact + 1);
1011 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001012 else
1013 data = unicode->data.any;
Victor 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) {
2242 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2243 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
Walter Dörwald346737f2007-05-31 10:44:43 +00002316static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002317makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002318 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002319{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002320 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002321 if (longflag)
2322 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002323 else if (longlongflag) {
2324 /* longlongflag should only ever be nonzero on machines with
2325 HAVE_LONG_LONG defined */
2326#ifdef HAVE_LONG_LONG
2327 char *f = PY_FORMAT_LONG_LONG;
2328 while (*f)
2329 *fmt++ = *f++;
2330#else
2331 /* we shouldn't ever get here */
2332 assert(0);
2333 *fmt++ = 'l';
2334#endif
2335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002336 else if (size_tflag) {
2337 char *f = PY_FORMAT_SIZE_T;
2338 while (*f)
2339 *fmt++ = *f++;
2340 }
2341 *fmt++ = c;
2342 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002343}
2344
Victor Stinner15a11362012-10-06 23:48:20 +02002345/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002346 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2347 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2348#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002349
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002350static int
2351unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2352 Py_ssize_t width, Py_ssize_t precision)
2353{
2354 Py_ssize_t length, fill, arglen;
2355 Py_UCS4 maxchar;
2356
2357 if (PyUnicode_READY(str) == -1)
2358 return -1;
2359
2360 length = PyUnicode_GET_LENGTH(str);
2361 if ((precision == -1 || precision >= length)
2362 && width <= length)
2363 return _PyUnicodeWriter_WriteStr(writer, str);
2364
2365 if (precision != -1)
2366 length = Py_MIN(precision, length);
2367
2368 arglen = Py_MAX(length, width);
2369 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2370 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2371 else
2372 maxchar = writer->maxchar;
2373
2374 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2375 return -1;
2376
2377 if (width > length) {
2378 fill = width - length;
2379 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2380 return -1;
2381 writer->pos += fill;
2382 }
2383
2384 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2385 str, 0, length);
2386 writer->pos += length;
2387 return 0;
2388}
2389
2390static int
2391unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2392 Py_ssize_t width, Py_ssize_t precision)
2393{
2394 /* UTF-8 */
2395 Py_ssize_t length;
2396 PyObject *unicode;
2397 int res;
2398
2399 length = strlen(str);
2400 if (precision != -1)
2401 length = Py_MIN(length, precision);
2402 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2403 if (unicode == NULL)
2404 return -1;
2405
2406 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2407 Py_DECREF(unicode);
2408 return res;
2409}
2410
Victor Stinner96865452011-03-01 23:44:09 +00002411static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002412unicode_fromformat_arg(_PyUnicodeWriter *writer,
2413 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002414{
Victor Stinnere215d962012-10-06 23:03:36 +02002415 const char *p;
2416 Py_ssize_t len;
2417 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002418 Py_ssize_t width;
2419 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002420 int longflag;
2421 int longlongflag;
2422 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002423 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002424
2425 p = f;
2426 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002427 zeropad = 0;
2428 if (*f == '0') {
2429 zeropad = 1;
2430 f++;
2431 }
Victor Stinner96865452011-03-01 23:44:09 +00002432
2433 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002434 width = -1;
2435 if (Py_ISDIGIT((unsigned)*f)) {
2436 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002437 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002438 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002440 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002441 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002442 return NULL;
2443 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002444 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002445 f++;
2446 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002447 }
2448 precision = -1;
2449 if (*f == '.') {
2450 f++;
2451 if (Py_ISDIGIT((unsigned)*f)) {
2452 precision = (*f - '0');
2453 f++;
2454 while (Py_ISDIGIT((unsigned)*f)) {
2455 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2456 PyErr_SetString(PyExc_ValueError,
2457 "precision too big");
2458 return NULL;
2459 }
2460 precision = (precision * 10) + (*f - '0');
2461 f++;
2462 }
2463 }
Victor Stinner96865452011-03-01 23:44:09 +00002464 if (*f == '%') {
2465 /* "%.3%s" => f points to "3" */
2466 f--;
2467 }
2468 }
2469 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002470 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002471 f--;
2472 }
Victor Stinner96865452011-03-01 23:44:09 +00002473
2474 /* Handle %ld, %lu, %lld and %llu. */
2475 longflag = 0;
2476 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002477 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002478 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002479 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002480 longflag = 1;
2481 ++f;
2482 }
2483#ifdef HAVE_LONG_LONG
2484 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002485 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002486 longlongflag = 1;
2487 f += 2;
2488 }
2489#endif
2490 }
2491 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002492 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002493 size_tflag = 1;
2494 ++f;
2495 }
Victor Stinnere215d962012-10-06 23:03:36 +02002496
2497 if (f[1] == '\0')
2498 writer->overallocate = 0;
2499
2500 switch (*f) {
2501 case 'c':
2502 {
2503 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002504 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002505 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002506 "character argument not in range(0x110000)");
2507 return NULL;
2508 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002509 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002510 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002511 break;
2512 }
2513
2514 case 'i':
2515 case 'd':
2516 case 'u':
2517 case 'x':
2518 {
2519 /* used by sprintf */
2520 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002521 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002522 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002523
2524 if (*f == 'u') {
2525 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2526
2527 if (longflag)
2528 len = sprintf(buffer, fmt,
2529 va_arg(*vargs, unsigned long));
2530#ifdef HAVE_LONG_LONG
2531 else if (longlongflag)
2532 len = sprintf(buffer, fmt,
2533 va_arg(*vargs, unsigned PY_LONG_LONG));
2534#endif
2535 else if (size_tflag)
2536 len = sprintf(buffer, fmt,
2537 va_arg(*vargs, size_t));
2538 else
2539 len = sprintf(buffer, fmt,
2540 va_arg(*vargs, unsigned int));
2541 }
2542 else if (*f == 'x') {
2543 makefmt(fmt, 0, 0, 0, 'x');
2544 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2545 }
2546 else {
2547 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2548
2549 if (longflag)
2550 len = sprintf(buffer, fmt,
2551 va_arg(*vargs, long));
2552#ifdef HAVE_LONG_LONG
2553 else if (longlongflag)
2554 len = sprintf(buffer, fmt,
2555 va_arg(*vargs, PY_LONG_LONG));
2556#endif
2557 else if (size_tflag)
2558 len = sprintf(buffer, fmt,
2559 va_arg(*vargs, Py_ssize_t));
2560 else
2561 len = sprintf(buffer, fmt,
2562 va_arg(*vargs, int));
2563 }
2564 assert(len >= 0);
2565
Victor Stinnere215d962012-10-06 23:03:36 +02002566 if (precision < len)
2567 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002568
2569 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002570 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2571 return NULL;
2572
Victor Stinnere215d962012-10-06 23:03:36 +02002573 if (width > precision) {
2574 Py_UCS4 fillchar;
2575 fill = width - precision;
2576 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002577 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2578 return NULL;
2579 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002580 }
Victor Stinner15a11362012-10-06 23:48:20 +02002581 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002582 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002583 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2584 return NULL;
2585 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002586 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002587
Victor Stinner4a587072013-11-19 12:54:53 +01002588 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2589 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002590 break;
2591 }
2592
2593 case 'p':
2594 {
2595 char number[MAX_LONG_LONG_CHARS];
2596
2597 len = sprintf(number, "%p", va_arg(*vargs, void*));
2598 assert(len >= 0);
2599
2600 /* %p is ill-defined: ensure leading 0x. */
2601 if (number[1] == 'X')
2602 number[1] = 'x';
2603 else if (number[1] != 'x') {
2604 memmove(number + 2, number,
2605 strlen(number) + 1);
2606 number[0] = '0';
2607 number[1] = 'x';
2608 len += 2;
2609 }
2610
Victor Stinner4a587072013-11-19 12:54:53 +01002611 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002612 return NULL;
2613 break;
2614 }
2615
2616 case 's':
2617 {
2618 /* UTF-8 */
2619 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002620 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002621 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002622 break;
2623 }
2624
2625 case 'U':
2626 {
2627 PyObject *obj = va_arg(*vargs, PyObject *);
2628 assert(obj && _PyUnicode_CHECK(obj));
2629
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002630 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002631 return NULL;
2632 break;
2633 }
2634
2635 case 'V':
2636 {
2637 PyObject *obj = va_arg(*vargs, PyObject *);
2638 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002639 if (obj) {
2640 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002642 return NULL;
2643 }
2644 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002645 assert(str != NULL);
2646 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002647 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002648 }
2649 break;
2650 }
2651
2652 case 'S':
2653 {
2654 PyObject *obj = va_arg(*vargs, PyObject *);
2655 PyObject *str;
2656 assert(obj);
2657 str = PyObject_Str(obj);
2658 if (!str)
2659 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002660 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002661 Py_DECREF(str);
2662 return NULL;
2663 }
2664 Py_DECREF(str);
2665 break;
2666 }
2667
2668 case 'R':
2669 {
2670 PyObject *obj = va_arg(*vargs, PyObject *);
2671 PyObject *repr;
2672 assert(obj);
2673 repr = PyObject_Repr(obj);
2674 if (!repr)
2675 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002676 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002677 Py_DECREF(repr);
2678 return NULL;
2679 }
2680 Py_DECREF(repr);
2681 break;
2682 }
2683
2684 case 'A':
2685 {
2686 PyObject *obj = va_arg(*vargs, PyObject *);
2687 PyObject *ascii;
2688 assert(obj);
2689 ascii = PyObject_ASCII(obj);
2690 if (!ascii)
2691 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002692 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 Py_DECREF(ascii);
2694 return NULL;
2695 }
2696 Py_DECREF(ascii);
2697 break;
2698 }
2699
2700 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002701 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002702 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002703 break;
2704
2705 default:
2706 /* if we stumble upon an unknown formatting code, copy the rest
2707 of the format string to the output string. (we cannot just
2708 skip the code, since there's no way to know what's in the
2709 argument list) */
2710 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002711 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002712 return NULL;
2713 f = p+len;
2714 return f;
2715 }
2716
2717 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002718 return f;
2719}
2720
Walter Dörwaldd2034312007-05-18 16:29:38 +00002721PyObject *
2722PyUnicode_FromFormatV(const char *format, va_list vargs)
2723{
Victor Stinnere215d962012-10-06 23:03:36 +02002724 va_list vargs2;
2725 const char *f;
2726 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002727
Victor Stinner8f674cc2013-04-17 23:02:17 +02002728 _PyUnicodeWriter_Init(&writer);
2729 writer.min_length = strlen(format) + 100;
2730 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002731
2732 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2733 Copy it to be able to pass a reference to a subfunction. */
2734 Py_VA_COPY(vargs2, vargs);
2735
2736 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002737 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002738 f = unicode_fromformat_arg(&writer, f, &vargs2);
2739 if (f == NULL)
2740 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002743 const char *p;
2744 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002745
Victor Stinnere215d962012-10-06 23:03:36 +02002746 p = f;
2747 do
2748 {
2749 if ((unsigned char)*p > 127) {
2750 PyErr_Format(PyExc_ValueError,
2751 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2752 "string, got a non-ASCII byte: 0x%02x",
2753 (unsigned char)*p);
2754 return NULL;
2755 }
2756 p++;
2757 }
2758 while (*p != '\0' && *p != '%');
2759 len = p - f;
2760
2761 if (*p == '\0')
2762 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002763
2764 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002765 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002766
2767 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 }
Victor Stinnere215d962012-10-06 23:03:36 +02002770 return _PyUnicodeWriter_Finish(&writer);
2771
2772 fail:
2773 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002774 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002775}
2776
Walter Dörwaldd2034312007-05-18 16:29:38 +00002777PyObject *
2778PyUnicode_FromFormat(const char *format, ...)
2779{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 PyObject* ret;
2781 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782
2783#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002784 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002785#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002786 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002787#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002788 ret = PyUnicode_FromFormatV(format, vargs);
2789 va_end(vargs);
2790 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002791}
2792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793#ifdef HAVE_WCHAR_H
2794
Victor Stinner5593d8a2010-10-02 11:11:27 +00002795/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2796 convert a Unicode object to a wide character string.
2797
Victor Stinnerd88d9832011-09-06 02:00:05 +02002798 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 character) required to convert the unicode object. Ignore size argument.
2800
Victor Stinnerd88d9832011-09-06 02:00:05 +02002801 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002802 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002803 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002804static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002805unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002806 wchar_t *w,
2807 Py_ssize_t size)
2808{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002809 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 const wchar_t *wstr;
2811
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002812 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 if (wstr == NULL)
2814 return -1;
2815
Victor Stinner5593d8a2010-10-02 11:11:27 +00002816 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002817 if (size > res)
2818 size = res + 1;
2819 else
2820 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002822 return res;
2823 }
2824 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002826}
2827
2828Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002829PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002830 wchar_t *w,
2831 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832{
2833 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002834 PyErr_BadInternalCall();
2835 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002836 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002837 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002838}
2839
Victor Stinner137c34c2010-09-29 10:25:54 +00002840wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002841PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002842 Py_ssize_t *size)
2843{
2844 wchar_t* buffer;
2845 Py_ssize_t buflen;
2846
2847 if (unicode == NULL) {
2848 PyErr_BadInternalCall();
2849 return NULL;
2850 }
2851
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002852 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002853 if (buflen == -1)
2854 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002855 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002856 PyErr_NoMemory();
2857 return NULL;
2858 }
2859
Victor Stinner137c34c2010-09-29 10:25:54 +00002860 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2861 if (buffer == NULL) {
2862 PyErr_NoMemory();
2863 return NULL;
2864 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002865 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002866 if (buflen == -1) {
2867 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002869 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002870 if (size != NULL)
2871 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002872 return buffer;
2873}
2874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002875#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002879{
Victor Stinner8faf8212011-12-08 22:14:11 +01002880 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 PyErr_SetString(PyExc_ValueError,
2882 "chr() arg not in range(0x110000)");
2883 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002884 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002885
Victor Stinner985a82a2014-01-03 12:53:47 +01002886 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002887}
2888
Alexander Belopolsky40018472011-02-26 01:02:56 +00002889PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002890PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002892 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002893 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002895 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002896 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002897 Py_INCREF(obj);
2898 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002899 }
2900 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002901 /* For a Unicode subtype that's not a Unicode object,
2902 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002903 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002904 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002905 PyErr_Format(PyExc_TypeError,
2906 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002907 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002908 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002909}
2910
Alexander Belopolsky40018472011-02-26 01:02:56 +00002911PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002912PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002913 const char *encoding,
2914 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002915{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002916 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002917 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002918
Guido van Rossumd57fd912000-03-10 22:53:23 +00002919 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 PyErr_BadInternalCall();
2921 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002923
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002924 /* Decoding bytes objects is the most common case and should be fast */
2925 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002926 if (PyBytes_GET_SIZE(obj) == 0)
2927 _Py_RETURN_UNICODE_EMPTY();
2928 v = PyUnicode_Decode(
2929 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2930 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002931 return v;
2932 }
2933
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002934 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002935 PyErr_SetString(PyExc_TypeError,
2936 "decoding str is not supported");
2937 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002939
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002940 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2941 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2942 PyErr_Format(PyExc_TypeError,
2943 "coercing to str: need bytes, bytearray "
2944 "or buffer-like object, %.80s found",
2945 Py_TYPE(obj)->tp_name);
2946 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002947 }
Tim Petersced69f82003-09-16 20:30:58 +00002948
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002949 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002950 PyBuffer_Release(&buffer);
2951 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002953
Serhiy Storchaka05997252013-01-26 12:14:02 +02002954 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002955 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002956 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957}
2958
Victor Stinner600d3be2010-06-10 12:00:55 +00002959/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002960 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2961 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002962int
2963_Py_normalize_encoding(const char *encoding,
2964 char *lower,
2965 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002967 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002968 char *l;
2969 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002970
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002971 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002972 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002973 if (lower_len < 6)
2974 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002975 strcpy(lower, "utf-8");
2976 return 1;
2977 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002978 e = encoding;
2979 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002980 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002981 while (*e) {
2982 if (l == l_end)
2983 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002984 if (Py_ISUPPER(*e)) {
2985 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002986 }
2987 else if (*e == '_') {
2988 *l++ = '-';
2989 e++;
2990 }
2991 else {
2992 *l++ = *e++;
2993 }
2994 }
2995 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002996 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002997}
2998
Alexander Belopolsky40018472011-02-26 01:02:56 +00002999PyObject *
3000PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003001 Py_ssize_t size,
3002 const char *encoding,
3003 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003004{
3005 PyObject *buffer = NULL, *unicode;
3006 Py_buffer info;
3007 char lower[11]; /* Enough for any encoding shortcut */
3008
Fred Drakee4315f52000-05-09 19:53:39 +00003009 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003010 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003011 if ((strcmp(lower, "utf-8") == 0) ||
3012 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003013 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003014 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003015 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003016 (strcmp(lower, "iso-8859-1") == 0) ||
3017 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003018 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003019#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003020 else if (strcmp(lower, "mbcs") == 0)
3021 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003022#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003023 else if (strcmp(lower, "ascii") == 0)
3024 return PyUnicode_DecodeASCII(s, size, errors);
3025 else if (strcmp(lower, "utf-16") == 0)
3026 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3027 else if (strcmp(lower, "utf-32") == 0)
3028 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030
3031 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003032 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003033 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003034 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003035 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003036 if (buffer == NULL)
3037 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003038 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003039 if (unicode == NULL)
3040 goto onError;
3041 if (!PyUnicode_Check(unicode)) {
3042 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003043 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3044 "use codecs.decode() to decode to arbitrary types",
3045 encoding,
3046 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003047 Py_DECREF(unicode);
3048 goto onError;
3049 }
3050 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003051 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003052
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003054 Py_XDECREF(buffer);
3055 return NULL;
3056}
3057
Alexander Belopolsky40018472011-02-26 01:02:56 +00003058PyObject *
3059PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003060 const char *encoding,
3061 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003062{
3063 PyObject *v;
3064
3065 if (!PyUnicode_Check(unicode)) {
3066 PyErr_BadArgument();
3067 goto onError;
3068 }
3069
3070 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003072
3073 /* Decode via the codec registry */
3074 v = PyCodec_Decode(unicode, encoding, errors);
3075 if (v == NULL)
3076 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003077 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003078
Benjamin Peterson29060642009-01-31 22:14:21 +00003079 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003080 return NULL;
3081}
3082
Alexander Belopolsky40018472011-02-26 01:02:56 +00003083PyObject *
3084PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003085 const char *encoding,
3086 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003087{
3088 PyObject *v;
3089
3090 if (!PyUnicode_Check(unicode)) {
3091 PyErr_BadArgument();
3092 goto onError;
3093 }
3094
3095 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003096 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003097
3098 /* Decode via the codec registry */
3099 v = PyCodec_Decode(unicode, encoding, errors);
3100 if (v == NULL)
3101 goto onError;
3102 if (!PyUnicode_Check(v)) {
3103 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003104 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3105 "use codecs.decode() to decode to arbitrary types",
3106 encoding,
3107 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003108 Py_DECREF(v);
3109 goto onError;
3110 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003111 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003112
Benjamin Peterson29060642009-01-31 22:14:21 +00003113 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003114 return NULL;
3115}
3116
Alexander Belopolsky40018472011-02-26 01:02:56 +00003117PyObject *
3118PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003119 Py_ssize_t size,
3120 const char *encoding,
3121 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003122{
3123 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003124
Guido van Rossumd57fd912000-03-10 22:53:23 +00003125 unicode = PyUnicode_FromUnicode(s, size);
3126 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003128 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3129 Py_DECREF(unicode);
3130 return v;
3131}
3132
Alexander Belopolsky40018472011-02-26 01:02:56 +00003133PyObject *
3134PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003135 const char *encoding,
3136 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003137{
3138 PyObject *v;
3139
3140 if (!PyUnicode_Check(unicode)) {
3141 PyErr_BadArgument();
3142 goto onError;
3143 }
3144
3145 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003147
3148 /* Encode via the codec registry */
3149 v = PyCodec_Encode(unicode, encoding, errors);
3150 if (v == NULL)
3151 goto onError;
3152 return v;
3153
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003155 return NULL;
3156}
3157
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003158static size_t
3159wcstombs_errorpos(const wchar_t *wstr)
3160{
3161 size_t len;
3162#if SIZEOF_WCHAR_T == 2
3163 wchar_t buf[3];
3164#else
3165 wchar_t buf[2];
3166#endif
3167 char outbuf[MB_LEN_MAX];
3168 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003169
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003170#if SIZEOF_WCHAR_T == 2
3171 buf[2] = 0;
3172#else
3173 buf[1] = 0;
3174#endif
3175 start = wstr;
3176 while (*wstr != L'\0')
3177 {
3178 previous = wstr;
3179#if SIZEOF_WCHAR_T == 2
3180 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3181 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3182 {
3183 buf[0] = wstr[0];
3184 buf[1] = wstr[1];
3185 wstr += 2;
3186 }
3187 else {
3188 buf[0] = *wstr;
3189 buf[1] = 0;
3190 wstr++;
3191 }
3192#else
3193 buf[0] = *wstr;
3194 wstr++;
3195#endif
3196 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003197 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003199 }
3200
3201 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003202 return 0;
3203}
3204
Victor Stinner1b579672011-12-17 05:47:23 +01003205static int
3206locale_error_handler(const char *errors, int *surrogateescape)
3207{
3208 if (errors == NULL) {
3209 *surrogateescape = 0;
3210 return 0;
3211 }
3212
3213 if (strcmp(errors, "strict") == 0) {
3214 *surrogateescape = 0;
3215 return 0;
3216 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003217 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003218 *surrogateescape = 1;
3219 return 0;
3220 }
3221 PyErr_Format(PyExc_ValueError,
3222 "only 'strict' and 'surrogateescape' error handlers "
3223 "are supported, not '%s'",
3224 errors);
3225 return -1;
3226}
3227
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003228PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003229PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003230{
3231 Py_ssize_t wlen, wlen2;
3232 wchar_t *wstr;
3233 PyObject *bytes = NULL;
3234 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003235 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236 PyObject *exc;
3237 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003238 int surrogateescape;
3239
3240 if (locale_error_handler(errors, &surrogateescape) < 0)
3241 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003242
3243 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3244 if (wstr == NULL)
3245 return NULL;
3246
3247 wlen2 = wcslen(wstr);
3248 if (wlen2 != wlen) {
3249 PyMem_Free(wstr);
3250 PyErr_SetString(PyExc_TypeError, "embedded null character");
3251 return NULL;
3252 }
3253
3254 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003255 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003256 char *str;
3257
3258 str = _Py_wchar2char(wstr, &error_pos);
3259 if (str == NULL) {
3260 if (error_pos == (size_t)-1) {
3261 PyErr_NoMemory();
3262 PyMem_Free(wstr);
3263 return NULL;
3264 }
3265 else {
3266 goto encode_error;
3267 }
3268 }
3269 PyMem_Free(wstr);
3270
3271 bytes = PyBytes_FromString(str);
3272 PyMem_Free(str);
3273 }
3274 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003275 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276 size_t len, len2;
3277
3278 len = wcstombs(NULL, wstr, 0);
3279 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003280 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003281 goto encode_error;
3282 }
3283
3284 bytes = PyBytes_FromStringAndSize(NULL, len);
3285 if (bytes == NULL) {
3286 PyMem_Free(wstr);
3287 return NULL;
3288 }
3289
3290 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3291 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003292 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 goto encode_error;
3294 }
3295 PyMem_Free(wstr);
3296 }
3297 return bytes;
3298
3299encode_error:
3300 errmsg = strerror(errno);
3301 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003302
3303 if (error_pos == (size_t)-1)
3304 error_pos = wcstombs_errorpos(wstr);
3305
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306 PyMem_Free(wstr);
3307 Py_XDECREF(bytes);
3308
Victor Stinner2f197072011-12-17 07:08:30 +01003309 if (errmsg != NULL) {
3310 size_t errlen;
3311 wstr = _Py_char2wchar(errmsg, &errlen);
3312 if (wstr != NULL) {
3313 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003314 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003315 } else
3316 errmsg = NULL;
3317 }
3318 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003319 reason = PyUnicode_FromString(
3320 "wcstombs() encountered an unencodable "
3321 "wide character");
3322 if (reason == NULL)
3323 return NULL;
3324
3325 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3326 "locale", unicode,
3327 (Py_ssize_t)error_pos,
3328 (Py_ssize_t)(error_pos+1),
3329 reason);
3330 Py_DECREF(reason);
3331 if (exc != NULL) {
3332 PyCodec_StrictErrors(exc);
3333 Py_XDECREF(exc);
3334 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003335 return NULL;
3336}
3337
Victor Stinnerad158722010-10-27 00:25:46 +00003338PyObject *
3339PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003340{
Victor Stinner99b95382011-07-04 14:23:54 +02003341#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003342 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003343#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003344 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003345#else
Victor Stinner793b5312011-04-27 00:24:21 +02003346 PyInterpreterState *interp = PyThreadState_GET()->interp;
3347 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3348 cannot use it to encode and decode filenames before it is loaded. Load
3349 the Python codec requires to encode at least its own filename. Use the C
3350 version of the locale codec until the codec registry is initialized and
3351 the Python codec is loaded.
3352
3353 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3354 cannot only rely on it: check also interp->fscodec_initialized for
3355 subinterpreters. */
3356 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003357 return PyUnicode_AsEncodedString(unicode,
3358 Py_FileSystemDefaultEncoding,
3359 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003360 }
3361 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003362 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003363 }
Victor Stinnerad158722010-10-27 00:25:46 +00003364#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003365}
3366
Alexander Belopolsky40018472011-02-26 01:02:56 +00003367PyObject *
3368PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003369 const char *encoding,
3370 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003371{
3372 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003373 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003374
Guido van Rossumd57fd912000-03-10 22:53:23 +00003375 if (!PyUnicode_Check(unicode)) {
3376 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003378 }
Fred Drakee4315f52000-05-09 19:53:39 +00003379
Fred Drakee4315f52000-05-09 19:53:39 +00003380 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003381 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003382 if ((strcmp(lower, "utf-8") == 0) ||
3383 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003384 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003385 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003387 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003389 }
Victor Stinner37296e82010-06-10 13:36:23 +00003390 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003391 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003392 (strcmp(lower, "iso-8859-1") == 0) ||
3393 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003395#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003396 else if (strcmp(lower, "mbcs") == 0)
3397 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003398#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003399 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003400 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003402
3403 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003404 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003405 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003406 return NULL;
3407
3408 /* The normal path */
3409 if (PyBytes_Check(v))
3410 return v;
3411
3412 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003414 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003415 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003416
3417 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003418 "encoder %s returned bytearray instead of bytes; "
3419 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003420 encoding);
3421 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003422 Py_DECREF(v);
3423 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003425
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003426 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3427 Py_DECREF(v);
3428 return b;
3429 }
3430
3431 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003432 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3433 "use codecs.encode() to encode to arbitrary types",
3434 encoding,
3435 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003436 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003437 return NULL;
3438}
3439
Alexander Belopolsky40018472011-02-26 01:02:56 +00003440PyObject *
3441PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003442 const char *encoding,
3443 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003444{
3445 PyObject *v;
3446
3447 if (!PyUnicode_Check(unicode)) {
3448 PyErr_BadArgument();
3449 goto onError;
3450 }
3451
3452 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003453 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003454
3455 /* Encode via the codec registry */
3456 v = PyCodec_Encode(unicode, encoding, errors);
3457 if (v == NULL)
3458 goto onError;
3459 if (!PyUnicode_Check(v)) {
3460 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003461 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3462 "use codecs.encode() to encode to arbitrary types",
3463 encoding,
3464 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003465 Py_DECREF(v);
3466 goto onError;
3467 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003469
Benjamin Peterson29060642009-01-31 22:14:21 +00003470 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003471 return NULL;
3472}
3473
Victor Stinner2f197072011-12-17 07:08:30 +01003474static size_t
3475mbstowcs_errorpos(const char *str, size_t len)
3476{
3477#ifdef HAVE_MBRTOWC
3478 const char *start = str;
3479 mbstate_t mbs;
3480 size_t converted;
3481 wchar_t ch;
3482
3483 memset(&mbs, 0, sizeof mbs);
3484 while (len)
3485 {
3486 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3487 if (converted == 0)
3488 /* Reached end of string */
3489 break;
3490 if (converted == (size_t)-1 || converted == (size_t)-2) {
3491 /* Conversion error or incomplete character */
3492 return str - start;
3493 }
3494 else {
3495 str += converted;
3496 len -= converted;
3497 }
3498 }
3499 /* failed to find the undecodable byte sequence */
3500 return 0;
3501#endif
3502 return 0;
3503}
3504
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003505PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003507 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003508{
3509 wchar_t smallbuf[256];
3510 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3511 wchar_t *wstr;
3512 size_t wlen, wlen2;
3513 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003514 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003515 size_t error_pos;
3516 char *errmsg;
3517 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003518
3519 if (locale_error_handler(errors, &surrogateescape) < 0)
3520 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003521
3522 if (str[len] != '\0' || len != strlen(str)) {
3523 PyErr_SetString(PyExc_TypeError, "embedded null character");
3524 return NULL;
3525 }
3526
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003527 if (surrogateescape) {
3528 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003529 wstr = _Py_char2wchar(str, &wlen);
3530 if (wstr == NULL) {
3531 if (wlen == (size_t)-1)
3532 PyErr_NoMemory();
3533 else
3534 PyErr_SetFromErrno(PyExc_OSError);
3535 return NULL;
3536 }
3537
3538 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003539 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003540 }
3541 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003542 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003543#ifndef HAVE_BROKEN_MBSTOWCS
3544 wlen = mbstowcs(NULL, str, 0);
3545#else
3546 wlen = len;
3547#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003548 if (wlen == (size_t)-1)
3549 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003550 if (wlen+1 <= smallbuf_len) {
3551 wstr = smallbuf;
3552 }
3553 else {
3554 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3555 return PyErr_NoMemory();
3556
3557 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3558 if (!wstr)
3559 return PyErr_NoMemory();
3560 }
3561
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003562 wlen2 = mbstowcs(wstr, str, wlen+1);
3563 if (wlen2 == (size_t)-1) {
3564 if (wstr != smallbuf)
3565 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003566 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003567 }
3568#ifdef HAVE_BROKEN_MBSTOWCS
3569 assert(wlen2 == wlen);
3570#endif
3571 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3572 if (wstr != smallbuf)
3573 PyMem_Free(wstr);
3574 }
3575 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003576
3577decode_error:
3578 errmsg = strerror(errno);
3579 assert(errmsg != NULL);
3580
3581 error_pos = mbstowcs_errorpos(str, len);
3582 if (errmsg != NULL) {
3583 size_t errlen;
3584 wstr = _Py_char2wchar(errmsg, &errlen);
3585 if (wstr != NULL) {
3586 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003587 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003588 } else
3589 errmsg = NULL;
3590 }
3591 if (errmsg == NULL)
3592 reason = PyUnicode_FromString(
3593 "mbstowcs() encountered an invalid multibyte sequence");
3594 if (reason == NULL)
3595 return NULL;
3596
3597 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3598 "locale", str, len,
3599 (Py_ssize_t)error_pos,
3600 (Py_ssize_t)(error_pos+1),
3601 reason);
3602 Py_DECREF(reason);
3603 if (exc != NULL) {
3604 PyCodec_StrictErrors(exc);
3605 Py_XDECREF(exc);
3606 }
3607 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003608}
3609
3610PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003611PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003612{
3613 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003614 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003615}
3616
3617
3618PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003619PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003621 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3622}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003623
Christian Heimes5894ba72007-11-04 11:43:14 +00003624PyObject*
3625PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3626{
Victor Stinner99b95382011-07-04 14:23:54 +02003627#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003628 return PyUnicode_DecodeMBCS(s, size, NULL);
3629#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003630 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003631#else
Victor Stinner793b5312011-04-27 00:24:21 +02003632 PyInterpreterState *interp = PyThreadState_GET()->interp;
3633 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3634 cannot use it to encode and decode filenames before it is loaded. Load
3635 the Python codec requires to encode at least its own filename. Use the C
3636 version of the locale codec until the codec registry is initialized and
3637 the Python codec is loaded.
3638
3639 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3640 cannot only rely on it: check also interp->fscodec_initialized for
3641 subinterpreters. */
3642 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003643 return PyUnicode_Decode(s, size,
3644 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003645 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003646 }
3647 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003648 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003649 }
Victor Stinnerad158722010-10-27 00:25:46 +00003650#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003651}
3652
Martin v. Löwis011e8422009-05-05 04:43:17 +00003653
3654int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003655_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003656{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003657 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003658
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003659 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003660 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003661 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3662 PyUnicode_GET_LENGTH(str), '\0', 1);
3663 if (pos == -1)
3664 return 0;
3665 else
3666 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003667}
3668
Antoine Pitrou13348842012-01-29 18:36:34 +01003669int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003670PyUnicode_FSConverter(PyObject* arg, void* addr)
3671{
3672 PyObject *output = NULL;
3673 Py_ssize_t size;
3674 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 if (arg == NULL) {
3676 Py_DECREF(*(PyObject**)addr);
3677 return 1;
3678 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003679 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003680 output = arg;
3681 Py_INCREF(output);
3682 }
3683 else {
3684 arg = PyUnicode_FromObject(arg);
3685 if (!arg)
3686 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003687 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003688 Py_DECREF(arg);
3689 if (!output)
3690 return 0;
3691 if (!PyBytes_Check(output)) {
3692 Py_DECREF(output);
3693 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3694 return 0;
3695 }
3696 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003697 size = PyBytes_GET_SIZE(output);
3698 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003699 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003700 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003701 Py_DECREF(output);
3702 return 0;
3703 }
3704 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003705 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003706}
3707
3708
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003709int
3710PyUnicode_FSDecoder(PyObject* arg, void* addr)
3711{
3712 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003713 if (arg == NULL) {
3714 Py_DECREF(*(PyObject**)addr);
3715 return 1;
3716 }
3717 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003718 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003720 output = arg;
3721 Py_INCREF(output);
3722 }
3723 else {
3724 arg = PyBytes_FromObject(arg);
3725 if (!arg)
3726 return 0;
3727 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3728 PyBytes_GET_SIZE(arg));
3729 Py_DECREF(arg);
3730 if (!output)
3731 return 0;
3732 if (!PyUnicode_Check(output)) {
3733 Py_DECREF(output);
3734 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3735 return 0;
3736 }
3737 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003738 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003739 Py_DECREF(output);
3740 return 0;
3741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003743 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003744 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3745 Py_DECREF(output);
3746 return 0;
3747 }
3748 *(PyObject**)addr = output;
3749 return Py_CLEANUP_SUPPORTED;
3750}
3751
3752
Martin v. Löwis5b222132007-06-10 09:51:05 +00003753char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003754PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003755{
Christian Heimesf3863112007-11-22 07:46:41 +00003756 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003757
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003758 if (!PyUnicode_Check(unicode)) {
3759 PyErr_BadArgument();
3760 return NULL;
3761 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003762 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003763 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003765 if (PyUnicode_UTF8(unicode) == NULL) {
3766 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3768 if (bytes == NULL)
3769 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003770 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3771 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003772 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773 Py_DECREF(bytes);
3774 return NULL;
3775 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3777 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3778 PyBytes_AS_STRING(bytes),
3779 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780 Py_DECREF(bytes);
3781 }
3782
3783 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003784 *psize = PyUnicode_UTF8_LENGTH(unicode);
3785 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003786}
3787
3788char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003790{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3792}
3793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003794Py_UNICODE *
3795PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003797 const unsigned char *one_byte;
3798#if SIZEOF_WCHAR_T == 4
3799 const Py_UCS2 *two_bytes;
3800#else
3801 const Py_UCS4 *four_bytes;
3802 const Py_UCS4 *ucs4_end;
3803 Py_ssize_t num_surrogates;
3804#endif
3805 wchar_t *w;
3806 wchar_t *wchar_end;
3807
3808 if (!PyUnicode_Check(unicode)) {
3809 PyErr_BadArgument();
3810 return NULL;
3811 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003812 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 assert(_PyUnicode_KIND(unicode) != 0);
3815 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003817 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003819 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3820 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003821 num_surrogates = 0;
3822
3823 for (; four_bytes < ucs4_end; ++four_bytes) {
3824 if (*four_bytes > 0xFFFF)
3825 ++num_surrogates;
3826 }
3827
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003828 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3829 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3830 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003831 PyErr_NoMemory();
3832 return NULL;
3833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003835
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003836 w = _PyUnicode_WSTR(unicode);
3837 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3838 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3840 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003841 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003843 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3844 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 }
3846 else
3847 *w = *four_bytes;
3848
3849 if (w > wchar_end) {
3850 assert(0 && "Miscalculated string end");
3851 }
3852 }
3853 *w = 0;
3854#else
3855 /* sizeof(wchar_t) == 4 */
3856 Py_FatalError("Impossible unicode object state, wstr and str "
3857 "should share memory already.");
3858 return NULL;
3859#endif
3860 }
3861 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003862 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3863 (_PyUnicode_LENGTH(unicode) + 1));
3864 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 PyErr_NoMemory();
3866 return NULL;
3867 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003868 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3869 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3870 w = _PyUnicode_WSTR(unicode);
3871 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3874 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 for (; w < wchar_end; ++one_byte, ++w)
3876 *w = *one_byte;
3877 /* null-terminate the wstr */
3878 *w = 0;
3879 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003880 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003883 for (; w < wchar_end; ++two_bytes, ++w)
3884 *w = *two_bytes;
3885 /* null-terminate the wstr */
3886 *w = 0;
3887#else
3888 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003889 PyObject_FREE(_PyUnicode_WSTR(unicode));
3890 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003891 Py_FatalError("Impossible unicode object state, wstr "
3892 "and str should share memory already.");
3893 return NULL;
3894#endif
3895 }
3896 else {
3897 assert(0 && "This should never happen.");
3898 }
3899 }
3900 }
3901 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003902 *size = PyUnicode_WSTR_LENGTH(unicode);
3903 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003904}
3905
Alexander Belopolsky40018472011-02-26 01:02:56 +00003906Py_UNICODE *
3907PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003910}
3911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912
Alexander Belopolsky40018472011-02-26 01:02:56 +00003913Py_ssize_t
3914PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003915{
3916 if (!PyUnicode_Check(unicode)) {
3917 PyErr_BadArgument();
3918 goto onError;
3919 }
3920 return PyUnicode_GET_SIZE(unicode);
3921
Benjamin Peterson29060642009-01-31 22:14:21 +00003922 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003923 return -1;
3924}
3925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926Py_ssize_t
3927PyUnicode_GetLength(PyObject *unicode)
3928{
Victor Stinner07621332012-06-16 04:53:46 +02003929 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 PyErr_BadArgument();
3931 return -1;
3932 }
Victor Stinner07621332012-06-16 04:53:46 +02003933 if (PyUnicode_READY(unicode) == -1)
3934 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935 return PyUnicode_GET_LENGTH(unicode);
3936}
3937
3938Py_UCS4
3939PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3940{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003941 void *data;
3942 int kind;
3943
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003944 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3945 PyErr_BadArgument();
3946 return (Py_UCS4)-1;
3947 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003948 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003949 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950 return (Py_UCS4)-1;
3951 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003952 data = PyUnicode_DATA(unicode);
3953 kind = PyUnicode_KIND(unicode);
3954 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955}
3956
3957int
3958PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3959{
3960 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003961 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962 return -1;
3963 }
Victor Stinner488fa492011-12-12 00:01:39 +01003964 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003965 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003966 PyErr_SetString(PyExc_IndexError, "string index out of range");
3967 return -1;
3968 }
Victor Stinner488fa492011-12-12 00:01:39 +01003969 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003970 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003971 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3972 PyErr_SetString(PyExc_ValueError, "character out of range");
3973 return -1;
3974 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3976 index, ch);
3977 return 0;
3978}
3979
Alexander Belopolsky40018472011-02-26 01:02:56 +00003980const char *
3981PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003982{
Victor Stinner42cb4622010-09-01 19:39:01 +00003983 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003984}
3985
Victor Stinner554f3f02010-06-16 23:33:54 +00003986/* create or adjust a UnicodeDecodeError */
3987static void
3988make_decode_exception(PyObject **exceptionObject,
3989 const char *encoding,
3990 const char *input, Py_ssize_t length,
3991 Py_ssize_t startpos, Py_ssize_t endpos,
3992 const char *reason)
3993{
3994 if (*exceptionObject == NULL) {
3995 *exceptionObject = PyUnicodeDecodeError_Create(
3996 encoding, input, length, startpos, endpos, reason);
3997 }
3998 else {
3999 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4000 goto onError;
4001 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4002 goto onError;
4003 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4004 goto onError;
4005 }
4006 return;
4007
4008onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004009 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004010}
4011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013/* error handling callback helper:
4014 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004015 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 and adjust various state variables.
4017 return 0 on success, -1 on error
4018*/
4019
Alexander Belopolsky40018472011-02-26 01:02:56 +00004020static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004021unicode_decode_call_errorhandler_wchar(
4022 const char *errors, PyObject **errorHandler,
4023 const char *encoding, const char *reason,
4024 const char **input, const char **inend, Py_ssize_t *startinpos,
4025 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4026 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004028 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029
4030 PyObject *restuple = NULL;
4031 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004032 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004033 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004034 Py_ssize_t requiredsize;
4035 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004036 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004037 wchar_t *repwstr;
4038 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004040 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4041 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004042
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004043 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 *errorHandler = PyCodec_LookupError(errors);
4045 if (*errorHandler == NULL)
4046 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004047 }
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049 make_decode_exception(exceptionObject,
4050 encoding,
4051 *input, *inend - *input,
4052 *startinpos, *endinpos,
4053 reason);
4054 if (*exceptionObject == NULL)
4055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056
4057 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4058 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004061 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004062 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 }
4064 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004066
4067 /* Copy back the bytes variables, which might have been modified by the
4068 callback */
4069 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4070 if (!inputobj)
4071 goto onError;
4072 if (!PyBytes_Check(inputobj)) {
4073 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4074 }
4075 *input = PyBytes_AS_STRING(inputobj);
4076 insize = PyBytes_GET_SIZE(inputobj);
4077 *inend = *input + insize;
4078 /* we can DECREF safely, as the exception has another reference,
4079 so the object won't go away. */
4080 Py_DECREF(inputobj);
4081
4082 if (newpos<0)
4083 newpos = insize+newpos;
4084 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004085 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 goto onError;
4087 }
4088
4089 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4090 if (repwstr == NULL)
4091 goto onError;
4092 /* need more space? (at least enough for what we
4093 have+the replacement+the rest of the string (starting
4094 at the new input position), so we won't have to check space
4095 when there are no errors in the rest of the string) */
4096 requiredsize = *outpos + repwlen + insize-newpos;
4097 if (requiredsize > outsize) {
4098 if (requiredsize < 2*outsize)
4099 requiredsize = 2*outsize;
4100 if (unicode_resize(output, requiredsize) < 0)
4101 goto onError;
4102 }
4103 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4104 *outpos += repwlen;
4105
4106 *endinpos = newpos;
4107 *inptr = *input + newpos;
4108
4109 /* we made it! */
4110 Py_XDECREF(restuple);
4111 return 0;
4112
4113 onError:
4114 Py_XDECREF(restuple);
4115 return -1;
4116}
4117#endif /* HAVE_MBCS */
4118
4119static int
4120unicode_decode_call_errorhandler_writer(
4121 const char *errors, PyObject **errorHandler,
4122 const char *encoding, const char *reason,
4123 const char **input, const char **inend, Py_ssize_t *startinpos,
4124 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4125 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4126{
4127 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4128
4129 PyObject *restuple = NULL;
4130 PyObject *repunicode = NULL;
4131 Py_ssize_t insize;
4132 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004133 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004134 PyObject *inputobj = NULL;
4135
4136 if (*errorHandler == NULL) {
4137 *errorHandler = PyCodec_LookupError(errors);
4138 if (*errorHandler == NULL)
4139 goto onError;
4140 }
4141
4142 make_decode_exception(exceptionObject,
4143 encoding,
4144 *input, *inend - *input,
4145 *startinpos, *endinpos,
4146 reason);
4147 if (*exceptionObject == NULL)
4148 goto onError;
4149
4150 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4151 if (restuple == NULL)
4152 goto onError;
4153 if (!PyTuple_Check(restuple)) {
4154 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4155 goto onError;
4156 }
4157 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004158 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
4160 /* Copy back the bytes variables, which might have been modified by the
4161 callback */
4162 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4163 if (!inputobj)
4164 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004165 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004168 *input = PyBytes_AS_STRING(inputobj);
4169 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004170 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004171 /* we can DECREF safely, as the exception has another reference,
4172 so the object won't go away. */
4173 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004174
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004177 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004178 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004179 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004180 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181
Victor Stinner8f674cc2013-04-17 23:02:17 +02004182 if (PyUnicode_READY(repunicode) < 0)
4183 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004184 replen = PyUnicode_GET_LENGTH(repunicode);
4185 writer->min_length += replen;
4186 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004187 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004189 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004191 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004192 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004193
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004195 Py_XDECREF(restuple);
4196 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004200 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201}
4202
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004203/* --- UTF-7 Codec -------------------------------------------------------- */
4204
Antoine Pitrou244651a2009-05-04 18:56:13 +00004205/* See RFC2152 for details. We encode conservatively and decode liberally. */
4206
4207/* Three simple macros defining base-64. */
4208
4209/* Is c a base-64 character? */
4210
4211#define IS_BASE64(c) \
4212 (((c) >= 'A' && (c) <= 'Z') || \
4213 ((c) >= 'a' && (c) <= 'z') || \
4214 ((c) >= '0' && (c) <= '9') || \
4215 (c) == '+' || (c) == '/')
4216
4217/* given that c is a base-64 character, what is its base-64 value? */
4218
4219#define FROM_BASE64(c) \
4220 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4221 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4222 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4223 (c) == '+' ? 62 : 63)
4224
4225/* What is the base-64 character of the bottom 6 bits of n? */
4226
4227#define TO_BASE64(n) \
4228 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4229
4230/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4231 * decoded as itself. We are permissive on decoding; the only ASCII
4232 * byte not decoding to itself is the + which begins a base64
4233 * string. */
4234
4235#define DECODE_DIRECT(c) \
4236 ((c) <= 127 && (c) != '+')
4237
4238/* The UTF-7 encoder treats ASCII characters differently according to
4239 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4240 * the above). See RFC2152. This array identifies these different
4241 * sets:
4242 * 0 : "Set D"
4243 * alphanumeric and '(),-./:?
4244 * 1 : "Set O"
4245 * !"#$%&*;<=>@[]^_`{|}
4246 * 2 : "whitespace"
4247 * ht nl cr sp
4248 * 3 : special (must be base64 encoded)
4249 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4250 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251
Tim Petersced69f82003-09-16 20:30:58 +00004252static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253char utf7_category[128] = {
4254/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4255 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4256/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4257 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4258/* sp ! " # $ % & ' ( ) * + , - . / */
4259 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4260/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4261 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4262/* @ A B C D E F G H I J K L M N O */
4263 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4264/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4266/* ` a b c d e f g h i j k l m n o */
4267 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4268/* p q r s t u v w x y z { | } ~ del */
4269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004270};
4271
Antoine Pitrou244651a2009-05-04 18:56:13 +00004272/* ENCODE_DIRECT: this character should be encoded as itself. The
4273 * answer depends on whether we are encoding set O as itself, and also
4274 * on whether we are encoding whitespace as itself. RFC2152 makes it
4275 * clear that the answers to these questions vary between
4276 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004277
Antoine Pitrou244651a2009-05-04 18:56:13 +00004278#define ENCODE_DIRECT(c, directO, directWS) \
4279 ((c) < 128 && (c) > 0 && \
4280 ((utf7_category[(c)] == 0) || \
4281 (directWS && (utf7_category[(c)] == 2)) || \
4282 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283
Alexander Belopolsky40018472011-02-26 01:02:56 +00004284PyObject *
4285PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004286 Py_ssize_t size,
4287 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4290}
4291
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292/* The decoder. The only state we preserve is our read position,
4293 * i.e. how many characters we have consumed. So if we end in the
4294 * middle of a shift sequence we have to back off the read position
4295 * and the output to the beginning of the sequence, otherwise we lose
4296 * all the shift state (seen bits, number of bits seen, high
4297 * surrogate). */
4298
Alexander Belopolsky40018472011-02-26 01:02:56 +00004299PyObject *
4300PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004301 Py_ssize_t size,
4302 const char *errors,
4303 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004304{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004305 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t startinpos;
4307 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *errmsg = "";
4311 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004312 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313 unsigned int base64bits = 0;
4314 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004315 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 PyObject *errorHandler = NULL;
4317 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004319 if (size == 0) {
4320 if (consumed)
4321 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004322 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004323 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004326 _PyUnicodeWriter_Init(&writer);
4327 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328
4329 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 e = s + size;
4331
4332 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004335 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 if (inShift) { /* in a base-64 section */
4338 if (IS_BASE64(ch)) { /* consume a base-64 character */
4339 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4340 base64bits += 6;
4341 s++;
4342 if (base64bits >= 16) {
4343 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004344 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 base64bits -= 16;
4346 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004347 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 if (surrogate) {
4349 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004350 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4351 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004352 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004355 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 }
4357 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004358 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 }
4362 }
Victor Stinner551ac952011-11-29 22:58:13 +01004363 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 /* first surrogate */
4365 surrogate = outCh;
4366 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004368 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 }
4372 }
4373 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 inShift = 0;
4375 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004377 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004379 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (base64bits > 0) { /* left-over bits */
4382 if (base64bits >= 6) {
4383 /* We've seen at least one base-64 character */
4384 errmsg = "partial character in shift sequence";
4385 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004387 else {
4388 /* Some bits remain; they should be zero */
4389 if (base64buffer != 0) {
4390 errmsg = "non-zero padding bits in shift sequence";
4391 goto utf7Error;
4392 }
4393 }
4394 }
4395 if (ch != '-') {
4396 /* '-' is absorbed; other terminating
4397 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004398 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
4402 }
4403 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004404 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 s++; /* consume '+' */
4406 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004408 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 }
4411 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004413 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004415 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004419 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004420 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004448 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004452 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004462 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004463 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004464 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004465 writer.kind, writer.data, shiftOutStart);
4466 Py_XDECREF(errorHandler);
4467 Py_XDECREF(exc);
4468 _PyUnicodeWriter_Dealloc(&writer);
4469 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004470 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004471 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 }
4473 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004474 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004476 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004478 Py_XDECREF(errorHandler);
4479 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004480 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481
Benjamin Peterson29060642009-01-31 22:14:21 +00004482 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004483 Py_XDECREF(errorHandler);
4484 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004485 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486 return NULL;
4487}
4488
4489
Alexander Belopolsky40018472011-02-26 01:02:56 +00004490PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491_PyUnicode_EncodeUTF7(PyObject *str,
4492 int base64SetO,
4493 int base64WhiteSpace,
4494 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004496 int kind;
4497 void *data;
4498 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004499 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004501 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 unsigned int base64bits = 0;
4503 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504 char * out;
4505 char * start;
4506
Benjamin Petersonbac79492012-01-14 13:34:47 -05004507 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004508 return NULL;
4509 kind = PyUnicode_KIND(str);
4510 data = PyUnicode_DATA(str);
4511 len = PyUnicode_GET_LENGTH(str);
4512
4513 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004514 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004517 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004518 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004519 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520 if (v == NULL)
4521 return NULL;
4522
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004523 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004524 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004525 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 if (inShift) {
4528 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4529 /* shifting out */
4530 if (base64bits) { /* output remaining bits */
4531 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4532 base64buffer = 0;
4533 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534 }
4535 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536 /* Characters not in the BASE64 set implicitly unshift the sequence
4537 so no '-' is required, except if the character is itself a '-' */
4538 if (IS_BASE64(ch) || ch == '-') {
4539 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004541 *out++ = (char) ch;
4542 }
4543 else {
4544 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004545 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 else { /* not in a shift sequence */
4548 if (ch == '+') {
4549 *out++ = '+';
4550 *out++ = '-';
4551 }
4552 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4553 *out++ = (char) ch;
4554 }
4555 else {
4556 *out++ = '+';
4557 inShift = 1;
4558 goto encode_char;
4559 }
4560 }
4561 continue;
4562encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004563 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004564 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 /* code first surrogate */
4567 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004568 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 while (base64bits >= 6) {
4570 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4571 base64bits -= 6;
4572 }
4573 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004574 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 base64bits += 16;
4577 base64buffer = (base64buffer << 16) | ch;
4578 while (base64bits >= 6) {
4579 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4580 base64bits -= 6;
4581 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004582 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 if (base64bits)
4584 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4585 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004586 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004587 if (_PyBytes_Resize(&v, out - start) < 0)
4588 return NULL;
4589 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004590}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004591PyObject *
4592PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4593 Py_ssize_t size,
4594 int base64SetO,
4595 int base64WhiteSpace,
4596 const char *errors)
4597{
4598 PyObject *result;
4599 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4600 if (tmp == NULL)
4601 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004602 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004603 base64WhiteSpace, errors);
4604 Py_DECREF(tmp);
4605 return result;
4606}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004607
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608#undef IS_BASE64
4609#undef FROM_BASE64
4610#undef TO_BASE64
4611#undef DECODE_DIRECT
4612#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613
Guido van Rossumd57fd912000-03-10 22:53:23 +00004614/* --- UTF-8 Codec -------------------------------------------------------- */
4615
Alexander Belopolsky40018472011-02-26 01:02:56 +00004616PyObject *
4617PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004618 Py_ssize_t size,
4619 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004620{
Walter Dörwald69652032004-09-07 20:24:22 +00004621 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4622}
4623
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004624#include "stringlib/asciilib.h"
4625#include "stringlib/codecs.h"
4626#include "stringlib/undef.h"
4627
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004628#include "stringlib/ucs1lib.h"
4629#include "stringlib/codecs.h"
4630#include "stringlib/undef.h"
4631
4632#include "stringlib/ucs2lib.h"
4633#include "stringlib/codecs.h"
4634#include "stringlib/undef.h"
4635
4636#include "stringlib/ucs4lib.h"
4637#include "stringlib/codecs.h"
4638#include "stringlib/undef.h"
4639
Antoine Pitrouab868312009-01-10 15:40:25 +00004640/* Mask to quickly check whether a C 'long' contains a
4641 non-ASCII, UTF8-encoded char. */
4642#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004643# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004644#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004645# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004646#else
4647# error C 'long' size should be either 4 or 8!
4648#endif
4649
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004650static Py_ssize_t
4651ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004652{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004653 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004654 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004656 /*
4657 * Issue #17237: m68k is a bit different from most architectures in
4658 * that objects do not use "natural alignment" - for example, int and
4659 * long are only aligned at 2-byte boundaries. Therefore the assert()
4660 * won't work; also, tests have shown that skipping the "optimised
4661 * version" will even speed up m68k.
4662 */
4663#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004665 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4666 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 /* Fast path, see in STRINGLIB(utf8_decode) for
4668 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004669 /* Help allocation */
4670 const char *_p = p;
4671 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672 while (_p < aligned_end) {
4673 unsigned long value = *(const unsigned long *) _p;
4674 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004675 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 *((unsigned long *)q) = value;
4677 _p += SIZEOF_LONG;
4678 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004679 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 p = _p;
4681 while (p < end) {
4682 if ((unsigned char)*p & 0x80)
4683 break;
4684 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004686 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004689#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690 while (p < end) {
4691 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4692 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004693 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004694 /* Help allocation */
4695 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696 while (_p < aligned_end) {
4697 unsigned long value = *(unsigned long *) _p;
4698 if (value & ASCII_CHAR_MASK)
4699 break;
4700 _p += SIZEOF_LONG;
4701 }
4702 p = _p;
4703 if (_p == end)
4704 break;
4705 }
4706 if ((unsigned char)*p & 0x80)
4707 break;
4708 ++p;
4709 }
4710 memcpy(dest, start, p - start);
4711 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004712}
Antoine Pitrouab868312009-01-10 15:40:25 +00004713
Victor Stinner785938e2011-12-11 20:09:03 +01004714PyObject *
4715PyUnicode_DecodeUTF8Stateful(const char *s,
4716 Py_ssize_t size,
4717 const char *errors,
4718 Py_ssize_t *consumed)
4719{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004720 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004721 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004722 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723
4724 Py_ssize_t startinpos;
4725 Py_ssize_t endinpos;
4726 const char *errmsg = "";
4727 PyObject *errorHandler = NULL;
4728 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004729
4730 if (size == 0) {
4731 if (consumed)
4732 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004733 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004734 }
4735
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004736 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4737 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004738 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 *consumed = 1;
4740 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004741 }
4742
Victor Stinner8f674cc2013-04-17 23:02:17 +02004743 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004744 writer.min_length = size;
4745 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004746 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004747
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004748 writer.pos = ascii_decode(s, end, writer.data);
4749 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 while (s < end) {
4751 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004752 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 if (PyUnicode_IS_ASCII(writer.buffer))
4755 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004756 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004757 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004759 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760 } else {
4761 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 }
4764
4765 switch (ch) {
4766 case 0:
4767 if (s == end || consumed)
4768 goto End;
4769 errmsg = "unexpected end of data";
4770 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004771 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 break;
4773 case 1:
4774 errmsg = "invalid start byte";
4775 startinpos = s - starts;
4776 endinpos = startinpos + 1;
4777 break;
4778 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004779 case 3:
4780 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004781 errmsg = "invalid continuation byte";
4782 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004783 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784 break;
4785 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004786 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004787 goto onError;
4788 continue;
4789 }
4790
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004791 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 errors, &errorHandler,
4793 "utf-8", errmsg,
4794 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004795 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004797 }
4798
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 if (consumed)
4801 *consumed = s - starts;
4802
4803 Py_XDECREF(errorHandler);
4804 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004805 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806
4807onError:
4808 Py_XDECREF(errorHandler);
4809 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004810 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004812}
4813
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004814#ifdef __APPLE__
4815
4816/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004817 used to decode the command line arguments on Mac OS X.
4818
4819 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004820 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004821
4822wchar_t*
4823_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4824{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826 wchar_t *unicode;
4827 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004828
4829 /* Note: size will always be longer than the resulting Unicode
4830 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004831 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004833 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 if (!unicode)
4835 return NULL;
4836
4837 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 if (ch > 0xFF) {
4848#if SIZEOF_WCHAR_T == 4
4849 assert(0);
4850#else
4851 assert(Py_UNICODE_IS_SURROGATE(ch));
4852 /* compute and append the two surrogates: */
4853 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4854 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4855#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004856 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004857 else {
4858 if (!ch && s == e)
4859 break;
4860 /* surrogateescape */
4861 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4862 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004863 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 return unicode;
4866}
4867
4868#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004870/* Primary internal function which creates utf8 encoded bytes objects.
4871
4872 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004873 and allocate exactly as much space needed at the end. Else allocate the
4874 maximum possible needed (4 result bytes per Unicode character), and return
4875 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004876*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004877PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004878_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879{
Victor Stinner6099a032011-12-18 14:22:26 +01004880 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881 void *data;
4882 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884 if (!PyUnicode_Check(unicode)) {
4885 PyErr_BadArgument();
4886 return NULL;
4887 }
4888
4889 if (PyUnicode_READY(unicode) == -1)
4890 return NULL;
4891
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004892 if (PyUnicode_UTF8(unicode))
4893 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4894 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004895
4896 kind = PyUnicode_KIND(unicode);
4897 data = PyUnicode_DATA(unicode);
4898 size = PyUnicode_GET_LENGTH(unicode);
4899
Benjamin Petersonead6b532011-12-20 17:23:42 -06004900 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004901 default:
4902 assert(0);
4903 case PyUnicode_1BYTE_KIND:
4904 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4905 assert(!PyUnicode_IS_ASCII(unicode));
4906 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4907 case PyUnicode_2BYTE_KIND:
4908 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4909 case PyUnicode_4BYTE_KIND:
4910 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004911 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004912}
4913
Alexander Belopolsky40018472011-02-26 01:02:56 +00004914PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004915PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4916 Py_ssize_t size,
4917 const char *errors)
4918{
4919 PyObject *v, *unicode;
4920
4921 unicode = PyUnicode_FromUnicode(s, size);
4922 if (unicode == NULL)
4923 return NULL;
4924 v = _PyUnicode_AsUTF8String(unicode, errors);
4925 Py_DECREF(unicode);
4926 return v;
4927}
4928
4929PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004930PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004932 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933}
4934
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935/* --- UTF-32 Codec ------------------------------------------------------- */
4936
4937PyObject *
4938PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004939 Py_ssize_t size,
4940 const char *errors,
4941 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942{
4943 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4944}
4945
4946PyObject *
4947PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004948 Py_ssize_t size,
4949 const char *errors,
4950 int *byteorder,
4951 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004952{
4953 const char *starts = s;
4954 Py_ssize_t startinpos;
4955 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004956 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004957 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004958 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004959 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961 PyObject *errorHandler = NULL;
4962 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004963
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 q = (unsigned char *)s;
4965 e = q + size;
4966
4967 if (byteorder)
4968 bo = *byteorder;
4969
4970 /* Check for BOM marks (U+FEFF) in the input and adjust current
4971 byte order setting accordingly. In native mode, the leading BOM
4972 mark is skipped, in all other modes, it is copied to the output
4973 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004974 if (bo == 0 && size >= 4) {
4975 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4976 if (bom == 0x0000FEFF) {
4977 bo = -1;
4978 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004980 else if (bom == 0xFFFE0000) {
4981 bo = 1;
4982 q += 4;
4983 }
4984 if (byteorder)
4985 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986 }
4987
Victor Stinnere64322e2012-10-30 23:12:47 +01004988 if (q == e) {
4989 if (consumed)
4990 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004991 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992 }
4993
Victor Stinnere64322e2012-10-30 23:12:47 +01004994#ifdef WORDS_BIGENDIAN
4995 le = bo < 0;
4996#else
4997 le = bo <= 0;
4998#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004999 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005000
Victor Stinner8f674cc2013-04-17 23:02:17 +02005001 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005002 writer.min_length = (e - q + 3) / 4;
5003 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005004 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005005
Victor Stinnere64322e2012-10-30 23:12:47 +01005006 while (1) {
5007 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005009
Victor Stinnere64322e2012-10-30 23:12:47 +01005010 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005011 enum PyUnicode_Kind kind = writer.kind;
5012 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005013 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005014 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005015 if (le) {
5016 do {
5017 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5018 if (ch > maxch)
5019 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005020 if (kind != PyUnicode_1BYTE_KIND &&
5021 Py_UNICODE_IS_SURROGATE(ch))
5022 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005023 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 q += 4;
5025 } while (q <= last);
5026 }
5027 else {
5028 do {
5029 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5030 if (ch > maxch)
5031 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005032 if (kind != PyUnicode_1BYTE_KIND &&
5033 Py_UNICODE_IS_SURROGATE(ch))
5034 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005036 q += 4;
5037 } while (q <= last);
5038 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005039 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005040 }
5041
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005042 if (Py_UNICODE_IS_SURROGATE(ch)) {
5043 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5044 startinpos = ((const char *)q) - starts;
5045 endinpos = startinpos + 4;
5046 }
5047 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005050 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005052 startinpos = ((const char *)q) - starts;
5053 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005054 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005055 else {
5056 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005057 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005058 goto onError;
5059 q += 4;
5060 continue;
5061 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005063 startinpos = ((const char *)q) - starts;
5064 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005066
5067 /* The remaining input chars are ignored if the callback
5068 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005069 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005070 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005071 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005073 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005074 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 }
5076
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080 Py_XDECREF(errorHandler);
5081 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005082 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005085 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 Py_XDECREF(errorHandler);
5087 Py_XDECREF(exc);
5088 return NULL;
5089}
5090
5091PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005092_PyUnicode_EncodeUTF32(PyObject *str,
5093 const char *errors,
5094 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005096 int kind;
5097 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005099 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005100 unsigned char *p;
5101 Py_ssize_t nsize, i;
5102 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005103#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005106 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005108 const char *encoding;
5109 PyObject *errorHandler = NULL;
5110 PyObject *exc = NULL;
5111 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112
Serhiy Storchaka30793282014-01-04 22:44:01 +02005113#define STORECHAR(CH) \
5114 do { \
5115 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5116 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5117 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5118 p[iorder[0]] = (CH) & 0xff; \
5119 p += 4; \
5120 } while(0)
5121
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005122 if (!PyUnicode_Check(str)) {
5123 PyErr_BadArgument();
5124 return NULL;
5125 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005126 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005127 return NULL;
5128 kind = PyUnicode_KIND(str);
5129 data = PyUnicode_DATA(str);
5130 len = PyUnicode_GET_LENGTH(str);
5131
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005132 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005133 if (nsize > PY_SSIZE_T_MAX / 4)
5134 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005135 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136 if (v == NULL)
5137 return NULL;
5138
Serhiy Storchaka30793282014-01-04 22:44:01 +02005139 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005140 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005142 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005143 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144
Serhiy Storchaka30793282014-01-04 22:44:01 +02005145 if (byteorder == -1) {
5146 /* force LE */
5147 iorder[0] = 0;
5148 iorder[1] = 1;
5149 iorder[2] = 2;
5150 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005151 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005152 }
5153 else if (byteorder == 1) {
5154 /* force BE */
5155 iorder[0] = 3;
5156 iorder[1] = 2;
5157 iorder[2] = 1;
5158 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005159 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005160 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005161 else
5162 encoding = "utf-32";
5163
5164 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005165 for (i = 0; i < len; i++)
5166 STORECHAR(PyUnicode_READ(kind, data, i));
5167 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005168 }
5169
Serhiy Storchaka30793282014-01-04 22:44:01 +02005170 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005171 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005172 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5173 i++;
5174 assert(ch <= MAX_UNICODE);
5175 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5176 STORECHAR(ch);
5177 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005178 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005179
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005180 rep = unicode_encode_call_errorhandler(
5181 errors, &errorHandler,
5182 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005183 str, &exc, i-1, i, &i);
5184
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005185 if (!rep)
5186 goto error;
5187
5188 if (PyBytes_Check(rep)) {
5189 repsize = PyBytes_GET_SIZE(rep);
5190 if (repsize & 3) {
5191 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005192 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 "surrogates not allowed");
5194 goto error;
5195 }
5196 moreunits = repsize / 4;
5197 }
5198 else {
5199 assert(PyUnicode_Check(rep));
5200 if (PyUnicode_READY(rep) < 0)
5201 goto error;
5202 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5203 if (!PyUnicode_IS_ASCII(rep)) {
5204 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005205 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005206 "surrogates not allowed");
5207 goto error;
5208 }
5209 }
5210
5211 /* four bytes are reserved for each surrogate */
5212 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005213 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005214 Py_ssize_t morebytes = 4 * (moreunits - 1);
5215 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5216 /* integer overflow */
5217 PyErr_NoMemory();
5218 goto error;
5219 }
5220 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5221 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005222 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005223 }
5224
5225 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005226 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5227 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005228 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005229 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005230 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005231 repdata = PyUnicode_1BYTE_DATA(rep);
5232 while (repsize--) {
5233 Py_UCS4 ch = *repdata++;
5234 STORECHAR(ch);
5235 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005236 }
5237
5238 Py_CLEAR(rep);
5239 }
5240
5241 /* Cut back to size actually needed. This is necessary for, for example,
5242 encoding of a string containing isolated surrogates and the 'ignore'
5243 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005244 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005245 if (nsize != PyBytes_GET_SIZE(v))
5246 _PyBytes_Resize(&v, nsize);
5247 Py_XDECREF(errorHandler);
5248 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005249 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005250 error:
5251 Py_XDECREF(rep);
5252 Py_XDECREF(errorHandler);
5253 Py_XDECREF(exc);
5254 Py_XDECREF(v);
5255 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005256#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257}
5258
Alexander Belopolsky40018472011-02-26 01:02:56 +00005259PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005260PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5261 Py_ssize_t size,
5262 const char *errors,
5263 int byteorder)
5264{
5265 PyObject *result;
5266 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5267 if (tmp == NULL)
5268 return NULL;
5269 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5270 Py_DECREF(tmp);
5271 return result;
5272}
5273
5274PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005275PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
Victor Stinnerb960b342011-11-20 19:12:52 +01005277 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005278}
5279
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280/* --- UTF-16 Codec ------------------------------------------------------- */
5281
Tim Peters772747b2001-08-09 22:21:55 +00005282PyObject *
5283PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005284 Py_ssize_t size,
5285 const char *errors,
5286 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005287{
Walter Dörwald69652032004-09-07 20:24:22 +00005288 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5289}
5290
5291PyObject *
5292PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005293 Py_ssize_t size,
5294 const char *errors,
5295 int *byteorder,
5296 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005297{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005298 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005299 Py_ssize_t startinpos;
5300 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005302 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005303 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005304 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005305 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005306 PyObject *errorHandler = NULL;
5307 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005308 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005309
Tim Peters772747b2001-08-09 22:21:55 +00005310 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005311 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005312
5313 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005314 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005315
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005316 /* Check for BOM marks (U+FEFF) in the input and adjust current
5317 byte order setting accordingly. In native mode, the leading BOM
5318 mark is skipped, in all other modes, it is copied to the output
5319 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005320 if (bo == 0 && size >= 2) {
5321 const Py_UCS4 bom = (q[1] << 8) | q[0];
5322 if (bom == 0xFEFF) {
5323 q += 2;
5324 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 else if (bom == 0xFFFE) {
5327 q += 2;
5328 bo = 1;
5329 }
5330 if (byteorder)
5331 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005332 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005333
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 if (q == e) {
5335 if (consumed)
5336 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005337 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005338 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005339
Christian Heimes743e0cd2012-10-17 23:52:17 +02005340#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005341 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005342 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005343#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005344 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005345 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005346#endif
Tim Peters772747b2001-08-09 22:21:55 +00005347
Antoine Pitrou63065d72012-05-15 23:48:04 +02005348 /* Note: size will always be longer than the resulting Unicode
5349 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005350 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005351 writer.min_length = (e - q + 1) / 2;
5352 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005354
Antoine Pitrou63065d72012-05-15 23:48:04 +02005355 while (1) {
5356 Py_UCS4 ch = 0;
5357 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005358 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005359 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005360 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005361 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 native_ordering);
5364 else
5365 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 native_ordering);
5368 } else if (kind == PyUnicode_2BYTE_KIND) {
5369 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005370 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 native_ordering);
5372 } else {
5373 assert(kind == PyUnicode_4BYTE_KIND);
5374 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005375 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005376 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005377 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005378 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005379
Antoine Pitrou63065d72012-05-15 23:48:04 +02005380 switch (ch)
5381 {
5382 case 0:
5383 /* remaining byte at the end? (size should be even) */
5384 if (q == e || consumed)
5385 goto End;
5386 errmsg = "truncated data";
5387 startinpos = ((const char *)q) - starts;
5388 endinpos = ((const char *)e) - starts;
5389 break;
5390 /* The remaining input chars are ignored if the callback
5391 chooses to skip the input */
5392 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005393 q -= 2;
5394 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005395 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005396 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005397 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005398 endinpos = ((const char *)e) - starts;
5399 break;
5400 case 2:
5401 errmsg = "illegal encoding";
5402 startinpos = ((const char *)q) - 2 - starts;
5403 endinpos = startinpos + 2;
5404 break;
5405 case 3:
5406 errmsg = "illegal UTF-16 surrogate";
5407 startinpos = ((const char *)q) - 4 - starts;
5408 endinpos = startinpos + 2;
5409 break;
5410 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005411 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005412 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 continue;
5414 }
5415
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005416 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005417 errors,
5418 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005419 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005420 &starts,
5421 (const char **)&e,
5422 &startinpos,
5423 &endinpos,
5424 &exc,
5425 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005426 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005427 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 }
5429
Antoine Pitrou63065d72012-05-15 23:48:04 +02005430End:
Walter Dörwald69652032004-09-07 20:24:22 +00005431 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005433
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 Py_XDECREF(errorHandler);
5435 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005436 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005439 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005440 Py_XDECREF(errorHandler);
5441 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442 return NULL;
5443}
5444
Tim Peters772747b2001-08-09 22:21:55 +00005445PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005446_PyUnicode_EncodeUTF16(PyObject *str,
5447 const char *errors,
5448 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005449{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005450 enum PyUnicode_Kind kind;
5451 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005452 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005453 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005454 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005455 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005456#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005457 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005458#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005460#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005461 const char *encoding;
5462 Py_ssize_t nsize, pos;
5463 PyObject *errorHandler = NULL;
5464 PyObject *exc = NULL;
5465 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005466
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005467 if (!PyUnicode_Check(str)) {
5468 PyErr_BadArgument();
5469 return NULL;
5470 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005471 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005472 return NULL;
5473 kind = PyUnicode_KIND(str);
5474 data = PyUnicode_DATA(str);
5475 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005476
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005477 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005478 if (kind == PyUnicode_4BYTE_KIND) {
5479 const Py_UCS4 *in = (const Py_UCS4 *)data;
5480 const Py_UCS4 *end = in + len;
5481 while (in < end)
5482 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005483 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005484 }
5485 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005486 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 nsize = len + pairs + (byteorder == 0);
5488 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489 if (v == NULL)
5490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005492 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005493 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005494 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005496 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005497 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005498 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005499
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005500 if (kind == PyUnicode_1BYTE_KIND) {
5501 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5502 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005503 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005504
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005505 if (byteorder < 0)
5506 encoding = "utf-16-le";
5507 else if (byteorder > 0)
5508 encoding = "utf-16-be";
5509 else
5510 encoding = "utf-16";
5511
5512 pos = 0;
5513 while (pos < len) {
5514 Py_ssize_t repsize, moreunits;
5515
5516 if (kind == PyUnicode_2BYTE_KIND) {
5517 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5518 &out, native_ordering);
5519 }
5520 else {
5521 assert(kind == PyUnicode_4BYTE_KIND);
5522 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5523 &out, native_ordering);
5524 }
5525 if (pos == len)
5526 break;
5527
5528 rep = unicode_encode_call_errorhandler(
5529 errors, &errorHandler,
5530 encoding, "surrogates not allowed",
5531 str, &exc, pos, pos + 1, &pos);
5532 if (!rep)
5533 goto error;
5534
5535 if (PyBytes_Check(rep)) {
5536 repsize = PyBytes_GET_SIZE(rep);
5537 if (repsize & 1) {
5538 raise_encode_exception(&exc, encoding,
5539 str, pos - 1, pos,
5540 "surrogates not allowed");
5541 goto error;
5542 }
5543 moreunits = repsize / 2;
5544 }
5545 else {
5546 assert(PyUnicode_Check(rep));
5547 if (PyUnicode_READY(rep) < 0)
5548 goto error;
5549 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5550 if (!PyUnicode_IS_ASCII(rep)) {
5551 raise_encode_exception(&exc, encoding,
5552 str, pos - 1, pos,
5553 "surrogates not allowed");
5554 goto error;
5555 }
5556 }
5557
5558 /* two bytes are reserved for each surrogate */
5559 if (moreunits > 1) {
5560 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5561 Py_ssize_t morebytes = 2 * (moreunits - 1);
5562 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5563 /* integer overflow */
5564 PyErr_NoMemory();
5565 goto error;
5566 }
5567 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5568 goto error;
5569 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5570 }
5571
5572 if (PyBytes_Check(rep)) {
5573 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5574 out += moreunits;
5575 } else /* rep is unicode */ {
5576 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5577 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5578 &out, native_ordering);
5579 }
5580
5581 Py_CLEAR(rep);
5582 }
5583
5584 /* Cut back to size actually needed. This is necessary for, for example,
5585 encoding of a string containing isolated surrogates and the 'ignore' handler
5586 is used. */
5587 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5588 if (nsize != PyBytes_GET_SIZE(v))
5589 _PyBytes_Resize(&v, nsize);
5590 Py_XDECREF(errorHandler);
5591 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005592 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005593 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005594 error:
5595 Py_XDECREF(rep);
5596 Py_XDECREF(errorHandler);
5597 Py_XDECREF(exc);
5598 Py_XDECREF(v);
5599 return NULL;
5600#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601}
5602
Alexander Belopolsky40018472011-02-26 01:02:56 +00005603PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005604PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5605 Py_ssize_t size,
5606 const char *errors,
5607 int byteorder)
5608{
5609 PyObject *result;
5610 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5611 if (tmp == NULL)
5612 return NULL;
5613 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5614 Py_DECREF(tmp);
5615 return result;
5616}
5617
5618PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005619PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005621 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622}
5623
5624/* --- Unicode Escape Codec ----------------------------------------------- */
5625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005626/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5627 if all the escapes in the string make it still a valid ASCII string.
5628 Returns -1 if any escapes were found which cause the string to
5629 pop out of ASCII range. Otherwise returns the length of the
5630 required buffer to hold the string.
5631 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005632static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005633length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5634{
5635 const unsigned char *p = (const unsigned char *)s;
5636 const unsigned char *end = p + size;
5637 Py_ssize_t length = 0;
5638
5639 if (size < 0)
5640 return -1;
5641
5642 for (; p < end; ++p) {
5643 if (*p > 127) {
5644 /* Non-ASCII */
5645 return -1;
5646 }
5647 else if (*p != '\\') {
5648 /* Normal character */
5649 ++length;
5650 }
5651 else {
5652 /* Backslash-escape, check next char */
5653 ++p;
5654 /* Escape sequence reaches till end of string or
5655 non-ASCII follow-up. */
5656 if (p >= end || *p > 127)
5657 return -1;
5658 switch (*p) {
5659 case '\n':
5660 /* backslash + \n result in zero characters */
5661 break;
5662 case '\\': case '\'': case '\"':
5663 case 'b': case 'f': case 't':
5664 case 'n': case 'r': case 'v': case 'a':
5665 ++length;
5666 break;
5667 case '0': case '1': case '2': case '3':
5668 case '4': case '5': case '6': case '7':
5669 case 'x': case 'u': case 'U': case 'N':
5670 /* these do not guarantee ASCII characters */
5671 return -1;
5672 default:
5673 /* count the backslash + the other character */
5674 length += 2;
5675 }
5676 }
5677 }
5678 return length;
5679}
5680
Fredrik Lundh06d12682001-01-24 07:59:11 +00005681static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005682
Alexander Belopolsky40018472011-02-26 01:02:56 +00005683PyObject *
5684PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005685 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005686 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005688 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005689 Py_ssize_t startinpos;
5690 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005693 char* message;
5694 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005695 PyObject *errorHandler = NULL;
5696 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005697 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005698
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005699 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005700 if (len == 0)
5701 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005702
5703 /* After length_of_escaped_ascii_string() there are two alternatives,
5704 either the string is pure ASCII with named escapes like \n, etc.
5705 and we determined it's exact size (common case)
5706 or it contains \x, \u, ... escape sequences. then we create a
5707 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005708 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005709 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005710 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711 }
5712 else {
5713 /* Escaped strings will always be longer than the resulting
5714 Unicode string, so we start with size here and then reduce the
5715 length after conversion to the true value.
5716 (but if the error callback returns a long replacement string
5717 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005718 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005719 }
5720
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005722 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005724
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 while (s < end) {
5726 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005727 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005728 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729
5730 /* Non-escape characters are interpreted as Unicode ordinals */
5731 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005732 x = (unsigned char)*s;
5733 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005734 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005735 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 continue;
5737 }
5738
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005739 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 /* \ - Escapes */
5741 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005742 c = *s++;
5743 if (s > end)
5744 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005745
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005746 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005749#define WRITECHAR(ch) \
5750 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005751 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005752 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005753 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005754
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005756 case '\\': WRITECHAR('\\'); break;
5757 case '\'': WRITECHAR('\''); break;
5758 case '\"': WRITECHAR('\"'); break;
5759 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005761 case 'f': WRITECHAR('\014'); break;
5762 case 't': WRITECHAR('\t'); break;
5763 case 'n': WRITECHAR('\n'); break;
5764 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005765 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005766 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005768 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005769
Benjamin Peterson29060642009-01-31 22:14:21 +00005770 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771 case '0': case '1': case '2': case '3':
5772 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005773 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005774 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005775 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005776 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005777 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005779 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 break;
5781
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 /* hex escapes */
5783 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005785 digits = 2;
5786 message = "truncated \\xXX escape";
5787 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005788
Benjamin Peterson29060642009-01-31 22:14:21 +00005789 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005791 digits = 4;
5792 message = "truncated \\uXXXX escape";
5793 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794
Benjamin Peterson29060642009-01-31 22:14:21 +00005795 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005796 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 digits = 8;
5798 message = "truncated \\UXXXXXXXX escape";
5799 hexescape:
5800 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005801 if (end - s < digits) {
5802 /* count only hex digits */
5803 for (; s < end; ++s) {
5804 c = (unsigned char)*s;
5805 if (!Py_ISXDIGIT(c))
5806 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005807 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005808 goto error;
5809 }
5810 for (; digits--; ++s) {
5811 c = (unsigned char)*s;
5812 if (!Py_ISXDIGIT(c))
5813 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005814 chr = (chr<<4) & ~0xF;
5815 if (c >= '0' && c <= '9')
5816 chr += c - '0';
5817 else if (c >= 'a' && c <= 'f')
5818 chr += 10 + c - 'a';
5819 else
5820 chr += 10 + c - 'A';
5821 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005822 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005823 /* _decoding_error will have already written into the
5824 target buffer. */
5825 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005826 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005827 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005828 message = "illegal Unicode character";
5829 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005831 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005832 break;
5833
Benjamin Peterson29060642009-01-31 22:14:21 +00005834 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005835 case 'N':
5836 message = "malformed \\N character escape";
5837 if (ucnhash_CAPI == NULL) {
5838 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005839 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5840 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005841 if (ucnhash_CAPI == NULL)
5842 goto ucnhashError;
5843 }
5844 if (*s == '{') {
5845 const char *start = s+1;
5846 /* look for the closing brace */
5847 while (*s != '}' && s < end)
5848 s++;
5849 if (s > start && s < end && *s == '}') {
5850 /* found a name. look it up in the unicode database */
5851 message = "unknown Unicode character name";
5852 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005853 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005854 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005855 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005856 goto store;
5857 }
5858 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005859 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860
5861 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005862 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 message = "\\ at end of string";
5864 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005865 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005866 }
5867 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005868 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005869 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005871 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005873 continue;
5874
5875 error:
5876 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005877 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005878 errors, &errorHandler,
5879 "unicodeescape", message,
5880 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005881 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005882 goto onError;
5883 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005885#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005887 Py_XDECREF(errorHandler);
5888 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005889 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005890
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005892 PyErr_SetString(
5893 PyExc_UnicodeError,
5894 "\\N escapes not supported (can't load unicodedata module)"
5895 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005896 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005897 Py_XDECREF(errorHandler);
5898 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005899 return NULL;
5900
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005902 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 Py_XDECREF(errorHandler);
5904 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 return NULL;
5906}
5907
5908/* Return a Unicode-Escape string version of the Unicode object.
5909
5910 If quotes is true, the string is enclosed in u"" or u'' quotes as
5911 appropriate.
5912
5913*/
5914
Alexander Belopolsky40018472011-02-26 01:02:56 +00005915PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005918 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005919 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 int kind;
5922 void *data;
5923 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924
Ezio Melottie7f90372012-10-05 03:33:31 +03005925 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005926 escape.
5927
Ezio Melottie7f90372012-10-05 03:33:31 +03005928 For UCS1 strings it's '\xxx', 4 bytes per source character.
5929 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5930 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005931 */
5932
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005933 if (!PyUnicode_Check(unicode)) {
5934 PyErr_BadArgument();
5935 return NULL;
5936 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005937 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005938 return NULL;
5939 len = PyUnicode_GET_LENGTH(unicode);
5940 kind = PyUnicode_KIND(unicode);
5941 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005942 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005943 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5944 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5945 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5946 }
5947
5948 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005949 return PyBytes_FromStringAndSize(NULL, 0);
5950
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005953
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005954 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005956 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958 if (repr == NULL)
5959 return NULL;
5960
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005961 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005963 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005964 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005965
Walter Dörwald79e913e2007-05-12 11:08:06 +00005966 /* Escape backslashes */
5967 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 *p++ = '\\';
5969 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005970 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005971 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005972
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005973 /* Map 21-bit characters to '\U00xxxxxx' */
5974 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005975 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005976 *p++ = '\\';
5977 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005978 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5979 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5980 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5981 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5982 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5983 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5984 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5985 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005987 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005988
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005990 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 *p++ = '\\';
5992 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005993 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5994 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5995 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5996 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005998
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005999 /* Map special whitespace to '\t', \n', '\r' */
6000 else if (ch == '\t') {
6001 *p++ = '\\';
6002 *p++ = 't';
6003 }
6004 else if (ch == '\n') {
6005 *p++ = '\\';
6006 *p++ = 'n';
6007 }
6008 else if (ch == '\r') {
6009 *p++ = '\\';
6010 *p++ = 'r';
6011 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006012
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006013 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006014 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006016 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006017 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6018 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006019 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006020
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021 /* Copy everything else as-is */
6022 else
6023 *p++ = (char) ch;
6024 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006026 assert(p - PyBytes_AS_STRING(repr) > 0);
6027 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6028 return NULL;
6029 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030}
6031
Alexander Belopolsky40018472011-02-26 01:02:56 +00006032PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006033PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6034 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 PyObject *result;
6037 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6038 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006040 result = PyUnicode_AsUnicodeEscapeString(tmp);
6041 Py_DECREF(tmp);
6042 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043}
6044
6045/* --- Raw Unicode Escape Codec ------------------------------------------- */
6046
Alexander Belopolsky40018472011-02-26 01:02:56 +00006047PyObject *
6048PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006049 Py_ssize_t size,
6050 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006052 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006053 Py_ssize_t startinpos;
6054 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006055 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056 const char *end;
6057 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006058 PyObject *errorHandler = NULL;
6059 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006060
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006061 if (size == 0)
6062 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006063
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 /* Escaped strings will always be longer than the resulting
6065 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006066 length after conversion to the true value. (But decoding error
6067 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006068 _PyUnicodeWriter_Init(&writer);
6069 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006070
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071 end = s + size;
6072 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 unsigned char c;
6074 Py_UCS4 x;
6075 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006076 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 /* Non-escape characters are interpreted as Unicode ordinals */
6079 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006080 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006081 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006082 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006084 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 startinpos = s-starts;
6086
6087 /* \u-escapes are only interpreted iff the number of leading
6088 backslashes if odd */
6089 bs = s;
6090 for (;s < end;) {
6091 if (*s != '\\')
6092 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006093 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006094 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006095 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006096 }
6097 if (((s - bs) & 1) == 0 ||
6098 s >= end ||
6099 (*s != 'u' && *s != 'U')) {
6100 continue;
6101 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006102 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 count = *s=='u' ? 4 : 8;
6104 s++;
6105
6106 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 for (x = 0, i = 0; i < count; ++i, ++s) {
6108 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006109 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006111 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 errors, &errorHandler,
6113 "rawunicodeescape", "truncated \\uXXXX",
6114 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006115 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 goto onError;
6117 goto nextByte;
6118 }
6119 x = (x<<4) & ~0xF;
6120 if (c >= '0' && c <= '9')
6121 x += c - '0';
6122 else if (c >= 'a' && c <= 'f')
6123 x += 10 + c - 'a';
6124 else
6125 x += 10 + c - 'A';
6126 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006127 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006128 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006129 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006130 }
6131 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006132 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006133 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006134 errors, &errorHandler,
6135 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006136 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006137 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006139 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 nextByte:
6141 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006143 Py_XDECREF(errorHandler);
6144 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006145 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006146
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006148 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006149 Py_XDECREF(errorHandler);
6150 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 return NULL;
6152}
6153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154
Alexander Belopolsky40018472011-02-26 01:02:56 +00006155PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006158 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 char *p;
6160 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006161 Py_ssize_t expandsize, pos;
6162 int kind;
6163 void *data;
6164 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166 if (!PyUnicode_Check(unicode)) {
6167 PyErr_BadArgument();
6168 return NULL;
6169 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006170 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 return NULL;
6172 kind = PyUnicode_KIND(unicode);
6173 data = PyUnicode_DATA(unicode);
6174 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006175 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6176 bytes, and 1 byte characters 4. */
6177 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006178
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006181
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006182 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183 if (repr == NULL)
6184 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006185 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006186 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006188 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 for (pos = 0; pos < len; pos++) {
6190 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 /* Map 32-bit characters to '\Uxxxxxxxx' */
6192 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006193 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006194 *p++ = '\\';
6195 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006196 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6197 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6198 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6199 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6200 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6201 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6202 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6203 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006204 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207 *p++ = '\\';
6208 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006209 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6211 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6212 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006214 /* Copy everything else as-is */
6215 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 *p++ = (char) ch;
6217 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006218
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219 assert(p > q);
6220 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006221 return NULL;
6222 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006223}
6224
Alexander Belopolsky40018472011-02-26 01:02:56 +00006225PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6227 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229 PyObject *result;
6230 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6231 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006232 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006233 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6234 Py_DECREF(tmp);
6235 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236}
6237
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006238/* --- Unicode Internal Codec ------------------------------------------- */
6239
Alexander Belopolsky40018472011-02-26 01:02:56 +00006240PyObject *
6241_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006242 Py_ssize_t size,
6243 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006244{
6245 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006246 Py_ssize_t startinpos;
6247 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006248 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006249 const char *end;
6250 const char *reason;
6251 PyObject *errorHandler = NULL;
6252 PyObject *exc = NULL;
6253
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006254 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006255 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006256 1))
6257 return NULL;
6258
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006259 if (size == 0)
6260 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006261
Victor Stinner8f674cc2013-04-17 23:02:17 +02006262 _PyUnicodeWriter_Init(&writer);
6263 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6264 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006266 }
6267 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006268
Victor Stinner8f674cc2013-04-17 23:02:17 +02006269 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006271 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006272 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006273 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006274 endinpos = end-starts;
6275 reason = "truncated input";
6276 goto error;
6277 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006278 /* We copy the raw representation one byte at a time because the
6279 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006280 ((char *) &uch)[0] = s[0];
6281 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006282#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006283 ((char *) &uch)[2] = s[2];
6284 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006285#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006286 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006287#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006288 /* We have to sanity check the raw data, otherwise doom looms for
6289 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006290 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006291 endinpos = s - starts + Py_UNICODE_SIZE;
6292 reason = "illegal code point (> 0x10FFFF)";
6293 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006294 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006296 s += Py_UNICODE_SIZE;
6297#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006298 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006299 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006300 Py_UNICODE uch2;
6301 ((char *) &uch2)[0] = s[0];
6302 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006303 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006304 {
Victor Stinner551ac952011-11-29 22:58:13 +01006305 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006306 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006307 }
6308 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006309#endif
6310
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006311 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006313 continue;
6314
6315 error:
6316 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006317 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006318 errors, &errorHandler,
6319 "unicode_internal", reason,
6320 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006321 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006322 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323 }
6324
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325 Py_XDECREF(errorHandler);
6326 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006327 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328
Benjamin Peterson29060642009-01-31 22:14:21 +00006329 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006330 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331 Py_XDECREF(errorHandler);
6332 Py_XDECREF(exc);
6333 return NULL;
6334}
6335
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336/* --- Latin-1 Codec ------------------------------------------------------ */
6337
Alexander Belopolsky40018472011-02-26 01:02:56 +00006338PyObject *
6339PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006340 Py_ssize_t size,
6341 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006344 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345}
6346
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006347/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006348static void
6349make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006350 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006351 PyObject *unicode,
6352 Py_ssize_t startpos, Py_ssize_t endpos,
6353 const char *reason)
6354{
6355 if (*exceptionObject == NULL) {
6356 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006358 encoding, unicode, startpos, endpos, reason);
6359 }
6360 else {
6361 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6362 goto onError;
6363 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6364 goto onError;
6365 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6366 goto onError;
6367 return;
6368 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006369 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006370 }
6371}
6372
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006374static void
6375raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006376 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006377 PyObject *unicode,
6378 Py_ssize_t startpos, Py_ssize_t endpos,
6379 const char *reason)
6380{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006381 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006382 encoding, unicode, startpos, endpos, reason);
6383 if (*exceptionObject != NULL)
6384 PyCodec_StrictErrors(*exceptionObject);
6385}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386
6387/* error handling callback helper:
6388 build arguments, call the callback and check the arguments,
6389 put the result into newpos and return the replacement string, which
6390 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391static PyObject *
6392unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006393 PyObject **errorHandler,
6394 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006396 Py_ssize_t startpos, Py_ssize_t endpos,
6397 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006399 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006400 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401 PyObject *restuple;
6402 PyObject *resunicode;
6403
6404 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408 }
6409
Benjamin Petersonbac79492012-01-14 13:34:47 -05006410 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 return NULL;
6412 len = PyUnicode_GET_LENGTH(unicode);
6413
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006414 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418
6419 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006421 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006424 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 Py_DECREF(restuple);
6426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006428 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 &resunicode, newpos)) {
6430 Py_DECREF(restuple);
6431 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006433 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6434 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6435 Py_DECREF(restuple);
6436 return NULL;
6437 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 *newpos = len + *newpos;
6440 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006441 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006442 Py_DECREF(restuple);
6443 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006444 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 Py_INCREF(resunicode);
6446 Py_DECREF(restuple);
6447 return resunicode;
6448}
6449
Alexander Belopolsky40018472011-02-26 01:02:56 +00006450static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006452 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006453 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 /* input state */
6456 Py_ssize_t pos=0, size;
6457 int kind;
6458 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459 /* output object */
6460 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461 /* pointer into the output */
6462 char *str;
6463 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006464 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006465 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6466 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 PyObject *errorHandler = NULL;
6468 PyObject *exc = NULL;
6469 /* the following variable is used for caching string comparisons
6470 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6471 int known_errorHandler = -1;
6472
Benjamin Petersonbac79492012-01-14 13:34:47 -05006473 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 return NULL;
6475 size = PyUnicode_GET_LENGTH(unicode);
6476 kind = PyUnicode_KIND(unicode);
6477 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478 /* allocate enough for a simple encoding without
6479 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006480 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006481 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006482 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006484 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006485 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 ressize = size;
6487
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006488 while (pos < size) {
6489 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490
Benjamin Peterson29060642009-01-31 22:14:21 +00006491 /* can we encode this? */
6492 if (c<limit) {
6493 /* no overflow check, because we know that the space is enough */
6494 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006496 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 Py_ssize_t requiredsize;
6499 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006500 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 Py_ssize_t collstart = pos;
6503 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 ++collend;
6507 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6508 if (known_errorHandler==-1) {
6509 if ((errors==NULL) || (!strcmp(errors, "strict")))
6510 known_errorHandler = 1;
6511 else if (!strcmp(errors, "replace"))
6512 known_errorHandler = 2;
6513 else if (!strcmp(errors, "ignore"))
6514 known_errorHandler = 3;
6515 else if (!strcmp(errors, "xmlcharrefreplace"))
6516 known_errorHandler = 4;
6517 else
6518 known_errorHandler = 0;
6519 }
6520 switch (known_errorHandler) {
6521 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006522 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 goto onError;
6524 case 2: /* replace */
6525 while (collstart++<collend)
6526 *str++ = '?'; /* fall through */
6527 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006528 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 break;
6530 case 4: /* xmlcharrefreplace */
6531 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006532 /* determine replacement size */
6533 for (i = collstart, repsize = 0; i < collend; ++i) {
6534 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6535 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006537 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006547 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006548 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006550 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006552 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 if (requiredsize > ressize) {
6554 if (requiredsize<2*ressize)
6555 requiredsize = 2*ressize;
6556 if (_PyBytes_Resize(&res, requiredsize))
6557 goto onError;
6558 str = PyBytes_AS_STRING(res) + respos;
6559 ressize = requiredsize;
6560 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006561 /* generate replacement */
6562 for (i = collstart; i < collend; ++i) {
6563 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006565 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 break;
6567 default:
6568 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006569 encoding, reason, unicode, &exc,
6570 collstart, collend, &newpos);
6571 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006572 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006574 if (PyBytes_Check(repunicode)) {
6575 /* Directly copy bytes result to output. */
6576 repsize = PyBytes_Size(repunicode);
6577 if (repsize > 1) {
6578 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006579 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006580 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6581 Py_DECREF(repunicode);
6582 goto onError;
6583 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006584 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006585 ressize += repsize-1;
6586 }
6587 memcpy(str, PyBytes_AsString(repunicode), repsize);
6588 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006589 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006590 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006591 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006592 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 /* need more space? (at least enough for what we
6594 have+the replacement+the rest of the string, so
6595 we won't have to check space for encodable characters) */
6596 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006597 repsize = PyUnicode_GET_LENGTH(repunicode);
6598 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 if (requiredsize > ressize) {
6600 if (requiredsize<2*ressize)
6601 requiredsize = 2*ressize;
6602 if (_PyBytes_Resize(&res, requiredsize)) {
6603 Py_DECREF(repunicode);
6604 goto onError;
6605 }
6606 str = PyBytes_AS_STRING(res) + respos;
6607 ressize = requiredsize;
6608 }
6609 /* check if there is anything unencodable in the replacement
6610 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 for (i = 0; repsize-->0; ++i, ++str) {
6612 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006614 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006615 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 Py_DECREF(repunicode);
6617 goto onError;
6618 }
6619 *str = (char)c;
6620 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006622 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006624 }
6625 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006626 /* Resize if we allocated to much */
6627 size = str - PyBytes_AS_STRING(res);
6628 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006629 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006630 if (_PyBytes_Resize(&res, size) < 0)
6631 goto onError;
6632 }
6633
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 Py_XDECREF(errorHandler);
6635 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006636 return res;
6637
6638 onError:
6639 Py_XDECREF(res);
6640 Py_XDECREF(errorHandler);
6641 Py_XDECREF(exc);
6642 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006643}
6644
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006646PyObject *
6647PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006648 Py_ssize_t size,
6649 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 PyObject *result;
6652 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6653 if (unicode == NULL)
6654 return NULL;
6655 result = unicode_encode_ucs1(unicode, errors, 256);
6656 Py_DECREF(unicode);
6657 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658}
6659
Alexander Belopolsky40018472011-02-26 01:02:56 +00006660PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006661_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006662{
6663 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 PyErr_BadArgument();
6665 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006666 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006667 if (PyUnicode_READY(unicode) == -1)
6668 return NULL;
6669 /* Fast path: if it is a one-byte string, construct
6670 bytes object directly. */
6671 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6672 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6673 PyUnicode_GET_LENGTH(unicode));
6674 /* Non-Latin-1 characters present. Defer to above function to
6675 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006676 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006677}
6678
6679PyObject*
6680PyUnicode_AsLatin1String(PyObject *unicode)
6681{
6682 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006683}
6684
6685/* --- 7-bit ASCII Codec -------------------------------------------------- */
6686
Alexander Belopolsky40018472011-02-26 01:02:56 +00006687PyObject *
6688PyUnicode_DecodeASCII(const char *s,
6689 Py_ssize_t size,
6690 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006693 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006694 int kind;
6695 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006696 Py_ssize_t startinpos;
6697 Py_ssize_t endinpos;
6698 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 const char *e;
6700 PyObject *errorHandler = NULL;
6701 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006702
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006704 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006705
Guido van Rossumd57fd912000-03-10 22:53:23 +00006706 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006707 if (size == 1 && (unsigned char)s[0] < 128)
6708 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006709
Victor Stinner8f674cc2013-04-17 23:02:17 +02006710 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006711 writer.min_length = size;
6712 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006713 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006714
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006715 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006716 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006717 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006718 writer.pos = outpos;
6719 if (writer.pos == size)
6720 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006721
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006722 s += writer.pos;
6723 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006724 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006725 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006727 PyUnicode_WRITE(kind, data, writer.pos, c);
6728 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 ++s;
6730 }
6731 else {
6732 startinpos = s-starts;
6733 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006734 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 errors, &errorHandler,
6736 "ascii", "ordinal not in range(128)",
6737 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006738 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006740 kind = writer.kind;
6741 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 Py_XDECREF(errorHandler);
6745 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006746 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006747
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006749 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006750 Py_XDECREF(errorHandler);
6751 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752 return NULL;
6753}
6754
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006756PyObject *
6757PyUnicode_EncodeASCII(const Py_UNICODE *p,
6758 Py_ssize_t size,
6759 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006761 PyObject *result;
6762 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6763 if (unicode == NULL)
6764 return NULL;
6765 result = unicode_encode_ucs1(unicode, errors, 128);
6766 Py_DECREF(unicode);
6767 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768}
6769
Alexander Belopolsky40018472011-02-26 01:02:56 +00006770PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006771_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772{
6773 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 PyErr_BadArgument();
6775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777 if (PyUnicode_READY(unicode) == -1)
6778 return NULL;
6779 /* Fast path: if it is an ASCII-only string, construct bytes object
6780 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006781 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006782 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6783 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006785}
6786
6787PyObject *
6788PyUnicode_AsASCIIString(PyObject *unicode)
6789{
6790 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791}
6792
Victor Stinner99b95382011-07-04 14:23:54 +02006793#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006794
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006795/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006796
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006797#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006798#define NEED_RETRY
6799#endif
6800
Victor Stinner3a50e702011-10-18 21:21:00 +02006801#ifndef WC_ERR_INVALID_CHARS
6802# define WC_ERR_INVALID_CHARS 0x0080
6803#endif
6804
6805static char*
6806code_page_name(UINT code_page, PyObject **obj)
6807{
6808 *obj = NULL;
6809 if (code_page == CP_ACP)
6810 return "mbcs";
6811 if (code_page == CP_UTF7)
6812 return "CP_UTF7";
6813 if (code_page == CP_UTF8)
6814 return "CP_UTF8";
6815
6816 *obj = PyBytes_FromFormat("cp%u", code_page);
6817 if (*obj == NULL)
6818 return NULL;
6819 return PyBytes_AS_STRING(*obj);
6820}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006821
Victor Stinner3a50e702011-10-18 21:21:00 +02006822static DWORD
6823decode_code_page_flags(UINT code_page)
6824{
6825 if (code_page == CP_UTF7) {
6826 /* The CP_UTF7 decoder only supports flags=0 */
6827 return 0;
6828 }
6829 else
6830 return MB_ERR_INVALID_CHARS;
6831}
6832
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006833/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006834 * Decode a byte string from a Windows code page into unicode object in strict
6835 * mode.
6836 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006837 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6838 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006839 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006840static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006841decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006842 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006843 const char *in,
6844 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006845{
Victor Stinner3a50e702011-10-18 21:21:00 +02006846 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006847 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006848 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006849
6850 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006851 assert(insize > 0);
6852 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6853 if (outsize <= 0)
6854 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855
6856 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006858 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006859 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 if (*v == NULL)
6861 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006862 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006863 }
6864 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006866 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006867 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006868 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006869 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006870 }
6871
6872 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006873 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6874 if (outsize <= 0)
6875 goto error;
6876 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006877
Victor Stinner3a50e702011-10-18 21:21:00 +02006878error:
6879 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6880 return -2;
6881 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006882 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006883}
6884
Victor Stinner3a50e702011-10-18 21:21:00 +02006885/*
6886 * Decode a byte string from a code page into unicode object with an error
6887 * handler.
6888 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006889 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006890 * UnicodeDecodeError exception and returns -1 on error.
6891 */
6892static int
6893decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006894 PyObject **v,
6895 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006896 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006897{
6898 const char *startin = in;
6899 const char *endin = in + size;
6900 const DWORD flags = decode_code_page_flags(code_page);
6901 /* Ideally, we should get reason from FormatMessage. This is the Windows
6902 2000 English version of the message. */
6903 const char *reason = "No mapping for the Unicode character exists "
6904 "in the target code page.";
6905 /* each step cannot decode more than 1 character, but a character can be
6906 represented as a surrogate pair */
6907 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006908 int insize;
6909 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006910 PyObject *errorHandler = NULL;
6911 PyObject *exc = NULL;
6912 PyObject *encoding_obj = NULL;
6913 char *encoding;
6914 DWORD err;
6915 int ret = -1;
6916
6917 assert(size > 0);
6918
6919 encoding = code_page_name(code_page, &encoding_obj);
6920 if (encoding == NULL)
6921 return -1;
6922
Victor Stinner7d00cc12014-03-17 23:08:06 +01006923 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006924 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6925 UnicodeDecodeError. */
6926 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6927 if (exc != NULL) {
6928 PyCodec_StrictErrors(exc);
6929 Py_CLEAR(exc);
6930 }
6931 goto error;
6932 }
6933
6934 if (*v == NULL) {
6935 /* Create unicode object */
6936 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6937 PyErr_NoMemory();
6938 goto error;
6939 }
Victor Stinnerab595942011-12-17 04:59:06 +01006940 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006941 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006942 if (*v == NULL)
6943 goto error;
6944 startout = PyUnicode_AS_UNICODE(*v);
6945 }
6946 else {
6947 /* Extend unicode object */
6948 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6949 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6950 PyErr_NoMemory();
6951 goto error;
6952 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006953 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006954 goto error;
6955 startout = PyUnicode_AS_UNICODE(*v) + n;
6956 }
6957
6958 /* Decode the byte string character per character */
6959 out = startout;
6960 while (in < endin)
6961 {
6962 /* Decode a character */
6963 insize = 1;
6964 do
6965 {
6966 outsize = MultiByteToWideChar(code_page, flags,
6967 in, insize,
6968 buffer, Py_ARRAY_LENGTH(buffer));
6969 if (outsize > 0)
6970 break;
6971 err = GetLastError();
6972 if (err != ERROR_NO_UNICODE_TRANSLATION
6973 && err != ERROR_INSUFFICIENT_BUFFER)
6974 {
6975 PyErr_SetFromWindowsErr(0);
6976 goto error;
6977 }
6978 insize++;
6979 }
6980 /* 4=maximum length of a UTF-8 sequence */
6981 while (insize <= 4 && (in + insize) <= endin);
6982
6983 if (outsize <= 0) {
6984 Py_ssize_t startinpos, endinpos, outpos;
6985
Victor Stinner7d00cc12014-03-17 23:08:06 +01006986 /* last character in partial decode? */
6987 if (in + insize >= endin && !final)
6988 break;
6989
Victor Stinner3a50e702011-10-18 21:21:00 +02006990 startinpos = in - startin;
6991 endinpos = startinpos + 1;
6992 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006993 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006994 errors, &errorHandler,
6995 encoding, reason,
6996 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006997 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006998 {
6999 goto error;
7000 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007001 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007002 }
7003 else {
7004 in += insize;
7005 memcpy(out, buffer, outsize * sizeof(wchar_t));
7006 out += outsize;
7007 }
7008 }
7009
7010 /* write a NUL character at the end */
7011 *out = 0;
7012
7013 /* Extend unicode object */
7014 outsize = out - startout;
7015 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007016 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007018 /* (in - startin) <= size and size is an int */
7019 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007020
7021error:
7022 Py_XDECREF(encoding_obj);
7023 Py_XDECREF(errorHandler);
7024 Py_XDECREF(exc);
7025 return ret;
7026}
7027
Victor Stinner3a50e702011-10-18 21:21:00 +02007028static PyObject *
7029decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007030 const char *s, Py_ssize_t size,
7031 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007032{
Victor Stinner76a31a62011-11-04 00:05:13 +01007033 PyObject *v = NULL;
7034 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035
Victor Stinner3a50e702011-10-18 21:21:00 +02007036 if (code_page < 0) {
7037 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7038 return NULL;
7039 }
7040
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007042 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007043
Victor Stinner76a31a62011-11-04 00:05:13 +01007044 do
7045 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007047 if (size > INT_MAX) {
7048 chunk_size = INT_MAX;
7049 final = 0;
7050 done = 0;
7051 }
7052 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007054 {
7055 chunk_size = (int)size;
7056 final = (consumed == NULL);
7057 done = 1;
7058 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059
Victor Stinner76a31a62011-11-04 00:05:13 +01007060 if (chunk_size == 0 && done) {
7061 if (v != NULL)
7062 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007063 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007064 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065
Victor Stinner76a31a62011-11-04 00:05:13 +01007066 converted = decode_code_page_strict(code_page, &v,
7067 s, chunk_size);
7068 if (converted == -2)
7069 converted = decode_code_page_errors(code_page, &v,
7070 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007071 errors, final);
7072 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007073
7074 if (converted < 0) {
7075 Py_XDECREF(v);
7076 return NULL;
7077 }
7078
7079 if (consumed)
7080 *consumed += converted;
7081
7082 s += converted;
7083 size -= converted;
7084 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007085
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007086 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087}
7088
Alexander Belopolsky40018472011-02-26 01:02:56 +00007089PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007090PyUnicode_DecodeCodePageStateful(int code_page,
7091 const char *s,
7092 Py_ssize_t size,
7093 const char *errors,
7094 Py_ssize_t *consumed)
7095{
7096 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7097}
7098
7099PyObject *
7100PyUnicode_DecodeMBCSStateful(const char *s,
7101 Py_ssize_t size,
7102 const char *errors,
7103 Py_ssize_t *consumed)
7104{
7105 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7106}
7107
7108PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007109PyUnicode_DecodeMBCS(const char *s,
7110 Py_ssize_t size,
7111 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007112{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007113 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7114}
7115
Victor Stinner3a50e702011-10-18 21:21:00 +02007116static DWORD
7117encode_code_page_flags(UINT code_page, const char *errors)
7118{
7119 if (code_page == CP_UTF8) {
7120 if (winver.dwMajorVersion >= 6)
7121 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7122 and later */
7123 return WC_ERR_INVALID_CHARS;
7124 else
7125 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7126 return 0;
7127 }
7128 else if (code_page == CP_UTF7) {
7129 /* CP_UTF7 only supports flags=0 */
7130 return 0;
7131 }
7132 else {
7133 if (errors != NULL && strcmp(errors, "replace") == 0)
7134 return 0;
7135 else
7136 return WC_NO_BEST_FIT_CHARS;
7137 }
7138}
7139
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007140/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 * Encode a Unicode string to a Windows code page into a byte string in strict
7142 * mode.
7143 *
7144 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007145 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007146 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007147static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007148encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007149 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007151{
Victor Stinner554f3f02010-06-16 23:33:54 +00007152 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007153 BOOL *pusedDefaultChar = &usedDefaultChar;
7154 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007155 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007156 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007157 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 const DWORD flags = encode_code_page_flags(code_page, NULL);
7159 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007160 /* Create a substring so that we can get the UTF-16 representation
7161 of just the slice under consideration. */
7162 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007163
Martin v. Löwis3d325192011-11-04 18:23:06 +01007164 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007165
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007167 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007169 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007170
Victor Stinner2fc507f2011-11-04 20:06:39 +01007171 substring = PyUnicode_Substring(unicode, offset, offset+len);
7172 if (substring == NULL)
7173 return -1;
7174 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7175 if (p == NULL) {
7176 Py_DECREF(substring);
7177 return -1;
7178 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007179 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007180
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007181 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007183 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 NULL, 0,
7185 NULL, pusedDefaultChar);
7186 if (outsize <= 0)
7187 goto error;
7188 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007189 if (pusedDefaultChar && *pusedDefaultChar) {
7190 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007192 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007193
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007195 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007197 if (*outbytes == NULL) {
7198 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007199 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007200 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202 }
7203 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007204 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 const Py_ssize_t n = PyBytes_Size(*outbytes);
7206 if (outsize > PY_SSIZE_T_MAX - n) {
7207 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007208 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007209 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7212 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007216 }
7217
7218 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007220 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 out, outsize,
7222 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007223 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 if (outsize <= 0)
7225 goto error;
7226 if (pusedDefaultChar && *pusedDefaultChar)
7227 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007228 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007229
Victor Stinner3a50e702011-10-18 21:21:00 +02007230error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007231 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7233 return -2;
7234 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007235 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007236}
7237
Victor Stinner3a50e702011-10-18 21:21:00 +02007238/*
7239 * Encode a Unicode string to a Windows code page into a byte string using a
7240 * error handler.
7241 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007242 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 * -1 on other error.
7244 */
7245static int
7246encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007247 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007248 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007249{
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007251 Py_ssize_t pos = unicode_offset;
7252 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 /* Ideally, we should get reason from FormatMessage. This is the Windows
7254 2000 English version of the message. */
7255 const char *reason = "invalid character";
7256 /* 4=maximum length of a UTF-8 sequence */
7257 char buffer[4];
7258 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7259 Py_ssize_t outsize;
7260 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 PyObject *errorHandler = NULL;
7262 PyObject *exc = NULL;
7263 PyObject *encoding_obj = NULL;
7264 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007265 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 PyObject *rep;
7267 int ret = -1;
7268
7269 assert(insize > 0);
7270
7271 encoding = code_page_name(code_page, &encoding_obj);
7272 if (encoding == NULL)
7273 return -1;
7274
7275 if (errors == NULL || strcmp(errors, "strict") == 0) {
7276 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7277 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007278 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007279 if (exc != NULL) {
7280 PyCodec_StrictErrors(exc);
7281 Py_DECREF(exc);
7282 }
7283 Py_XDECREF(encoding_obj);
7284 return -1;
7285 }
7286
7287 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7288 pusedDefaultChar = &usedDefaultChar;
7289 else
7290 pusedDefaultChar = NULL;
7291
7292 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7293 PyErr_NoMemory();
7294 goto error;
7295 }
7296 outsize = insize * Py_ARRAY_LENGTH(buffer);
7297
7298 if (*outbytes == NULL) {
7299 /* Create string object */
7300 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7301 if (*outbytes == NULL)
7302 goto error;
7303 out = PyBytes_AS_STRING(*outbytes);
7304 }
7305 else {
7306 /* Extend string object */
7307 Py_ssize_t n = PyBytes_Size(*outbytes);
7308 if (n > PY_SSIZE_T_MAX - outsize) {
7309 PyErr_NoMemory();
7310 goto error;
7311 }
7312 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7313 goto error;
7314 out = PyBytes_AS_STRING(*outbytes) + n;
7315 }
7316
7317 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007318 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007320 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7321 wchar_t chars[2];
7322 int charsize;
7323 if (ch < 0x10000) {
7324 chars[0] = (wchar_t)ch;
7325 charsize = 1;
7326 }
7327 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007328 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7329 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007330 charsize = 2;
7331 }
7332
Victor Stinner3a50e702011-10-18 21:21:00 +02007333 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007334 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007335 buffer, Py_ARRAY_LENGTH(buffer),
7336 NULL, pusedDefaultChar);
7337 if (outsize > 0) {
7338 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7339 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 memcpy(out, buffer, outsize);
7342 out += outsize;
7343 continue;
7344 }
7345 }
7346 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7347 PyErr_SetFromWindowsErr(0);
7348 goto error;
7349 }
7350
Victor Stinner3a50e702011-10-18 21:21:00 +02007351 rep = unicode_encode_call_errorhandler(
7352 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007353 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007354 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 if (rep == NULL)
7356 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007357 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007358
7359 if (PyBytes_Check(rep)) {
7360 outsize = PyBytes_GET_SIZE(rep);
7361 if (outsize != 1) {
7362 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7363 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7364 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7365 Py_DECREF(rep);
7366 goto error;
7367 }
7368 out = PyBytes_AS_STRING(*outbytes) + offset;
7369 }
7370 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7371 out += outsize;
7372 }
7373 else {
7374 Py_ssize_t i;
7375 enum PyUnicode_Kind kind;
7376 void *data;
7377
Benjamin Petersonbac79492012-01-14 13:34:47 -05007378 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 Py_DECREF(rep);
7380 goto error;
7381 }
7382
7383 outsize = PyUnicode_GET_LENGTH(rep);
7384 if (outsize != 1) {
7385 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7386 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7387 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7388 Py_DECREF(rep);
7389 goto error;
7390 }
7391 out = PyBytes_AS_STRING(*outbytes) + offset;
7392 }
7393 kind = PyUnicode_KIND(rep);
7394 data = PyUnicode_DATA(rep);
7395 for (i=0; i < outsize; i++) {
7396 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7397 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007398 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007399 encoding, unicode,
7400 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 "unable to encode error handler result to ASCII");
7402 Py_DECREF(rep);
7403 goto error;
7404 }
7405 *out = (unsigned char)ch;
7406 out++;
7407 }
7408 }
7409 Py_DECREF(rep);
7410 }
7411 /* write a NUL byte */
7412 *out = 0;
7413 outsize = out - PyBytes_AS_STRING(*outbytes);
7414 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7415 if (_PyBytes_Resize(outbytes, outsize) < 0)
7416 goto error;
7417 ret = 0;
7418
7419error:
7420 Py_XDECREF(encoding_obj);
7421 Py_XDECREF(errorHandler);
7422 Py_XDECREF(exc);
7423 return ret;
7424}
7425
Victor Stinner3a50e702011-10-18 21:21:00 +02007426static PyObject *
7427encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007428 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 const char *errors)
7430{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007431 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007433 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007434 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007435
Benjamin Petersonbac79492012-01-14 13:34:47 -05007436 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007437 return NULL;
7438 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007439
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 if (code_page < 0) {
7441 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7442 return NULL;
7443 }
7444
Martin v. Löwis3d325192011-11-04 18:23:06 +01007445 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007446 return PyBytes_FromStringAndSize(NULL, 0);
7447
Victor Stinner7581cef2011-11-03 22:32:33 +01007448 offset = 0;
7449 do
7450 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007451#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007452 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007453 chunks. */
7454 if (len > INT_MAX/2) {
7455 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007456 done = 0;
7457 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007458 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007459#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007460 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007461 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007462 done = 1;
7463 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007464
Victor Stinner76a31a62011-11-04 00:05:13 +01007465 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007466 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007467 errors);
7468 if (ret == -2)
7469 ret = encode_code_page_errors(code_page, &outbytes,
7470 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007471 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007472 if (ret < 0) {
7473 Py_XDECREF(outbytes);
7474 return NULL;
7475 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007476
Victor Stinner7581cef2011-11-03 22:32:33 +01007477 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007478 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007479 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007480
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 return outbytes;
7482}
7483
7484PyObject *
7485PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7486 Py_ssize_t size,
7487 const char *errors)
7488{
Victor Stinner7581cef2011-11-03 22:32:33 +01007489 PyObject *unicode, *res;
7490 unicode = PyUnicode_FromUnicode(p, size);
7491 if (unicode == NULL)
7492 return NULL;
7493 res = encode_code_page(CP_ACP, unicode, errors);
7494 Py_DECREF(unicode);
7495 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007496}
7497
7498PyObject *
7499PyUnicode_EncodeCodePage(int code_page,
7500 PyObject *unicode,
7501 const char *errors)
7502{
Victor Stinner7581cef2011-11-03 22:32:33 +01007503 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007504}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007505
Alexander Belopolsky40018472011-02-26 01:02:56 +00007506PyObject *
7507PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007508{
7509 if (!PyUnicode_Check(unicode)) {
7510 PyErr_BadArgument();
7511 return NULL;
7512 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007513 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007514}
7515
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007516#undef NEED_RETRY
7517
Victor Stinner99b95382011-07-04 14:23:54 +02007518#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007519
Guido van Rossumd57fd912000-03-10 22:53:23 +00007520/* --- Character Mapping Codec -------------------------------------------- */
7521
Victor Stinnerfb161b12013-04-18 01:44:27 +02007522static int
7523charmap_decode_string(const char *s,
7524 Py_ssize_t size,
7525 PyObject *mapping,
7526 const char *errors,
7527 _PyUnicodeWriter *writer)
7528{
7529 const char *starts = s;
7530 const char *e;
7531 Py_ssize_t startinpos, endinpos;
7532 PyObject *errorHandler = NULL, *exc = NULL;
7533 Py_ssize_t maplen;
7534 enum PyUnicode_Kind mapkind;
7535 void *mapdata;
7536 Py_UCS4 x;
7537 unsigned char ch;
7538
7539 if (PyUnicode_READY(mapping) == -1)
7540 return -1;
7541
7542 maplen = PyUnicode_GET_LENGTH(mapping);
7543 mapdata = PyUnicode_DATA(mapping);
7544 mapkind = PyUnicode_KIND(mapping);
7545
7546 e = s + size;
7547
7548 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7549 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7550 * is disabled in encoding aliases, latin1 is preferred because
7551 * its implementation is faster. */
7552 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7553 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7554 Py_UCS4 maxchar = writer->maxchar;
7555
7556 assert (writer->kind == PyUnicode_1BYTE_KIND);
7557 while (s < e) {
7558 ch = *s;
7559 x = mapdata_ucs1[ch];
7560 if (x > maxchar) {
7561 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7562 goto onError;
7563 maxchar = writer->maxchar;
7564 outdata = (Py_UCS1 *)writer->data;
7565 }
7566 outdata[writer->pos] = x;
7567 writer->pos++;
7568 ++s;
7569 }
7570 return 0;
7571 }
7572
7573 while (s < e) {
7574 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7575 enum PyUnicode_Kind outkind = writer->kind;
7576 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7577 if (outkind == PyUnicode_1BYTE_KIND) {
7578 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7579 Py_UCS4 maxchar = writer->maxchar;
7580 while (s < e) {
7581 ch = *s;
7582 x = mapdata_ucs2[ch];
7583 if (x > maxchar)
7584 goto Error;
7585 outdata[writer->pos] = x;
7586 writer->pos++;
7587 ++s;
7588 }
7589 break;
7590 }
7591 else if (outkind == PyUnicode_2BYTE_KIND) {
7592 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7593 while (s < e) {
7594 ch = *s;
7595 x = mapdata_ucs2[ch];
7596 if (x == 0xFFFE)
7597 goto Error;
7598 outdata[writer->pos] = x;
7599 writer->pos++;
7600 ++s;
7601 }
7602 break;
7603 }
7604 }
7605 ch = *s;
7606
7607 if (ch < maplen)
7608 x = PyUnicode_READ(mapkind, mapdata, ch);
7609 else
7610 x = 0xfffe; /* invalid value */
7611Error:
7612 if (x == 0xfffe)
7613 {
7614 /* undefined mapping */
7615 startinpos = s-starts;
7616 endinpos = startinpos+1;
7617 if (unicode_decode_call_errorhandler_writer(
7618 errors, &errorHandler,
7619 "charmap", "character maps to <undefined>",
7620 &starts, &e, &startinpos, &endinpos, &exc, &s,
7621 writer)) {
7622 goto onError;
7623 }
7624 continue;
7625 }
7626
7627 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7628 goto onError;
7629 ++s;
7630 }
7631 Py_XDECREF(errorHandler);
7632 Py_XDECREF(exc);
7633 return 0;
7634
7635onError:
7636 Py_XDECREF(errorHandler);
7637 Py_XDECREF(exc);
7638 return -1;
7639}
7640
7641static int
7642charmap_decode_mapping(const char *s,
7643 Py_ssize_t size,
7644 PyObject *mapping,
7645 const char *errors,
7646 _PyUnicodeWriter *writer)
7647{
7648 const char *starts = s;
7649 const char *e;
7650 Py_ssize_t startinpos, endinpos;
7651 PyObject *errorHandler = NULL, *exc = NULL;
7652 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007653 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007654
7655 e = s + size;
7656
7657 while (s < e) {
7658 ch = *s;
7659
7660 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7661 key = PyLong_FromLong((long)ch);
7662 if (key == NULL)
7663 goto onError;
7664
7665 item = PyObject_GetItem(mapping, key);
7666 Py_DECREF(key);
7667 if (item == NULL) {
7668 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7669 /* No mapping found means: mapping is undefined. */
7670 PyErr_Clear();
7671 goto Undefined;
7672 } else
7673 goto onError;
7674 }
7675
7676 /* Apply mapping */
7677 if (item == Py_None)
7678 goto Undefined;
7679 if (PyLong_Check(item)) {
7680 long value = PyLong_AS_LONG(item);
7681 if (value == 0xFFFE)
7682 goto Undefined;
7683 if (value < 0 || value > MAX_UNICODE) {
7684 PyErr_Format(PyExc_TypeError,
7685 "character mapping must be in range(0x%lx)",
7686 (unsigned long)MAX_UNICODE + 1);
7687 goto onError;
7688 }
7689
7690 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7691 goto onError;
7692 }
7693 else if (PyUnicode_Check(item)) {
7694 if (PyUnicode_READY(item) == -1)
7695 goto onError;
7696 if (PyUnicode_GET_LENGTH(item) == 1) {
7697 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7698 if (value == 0xFFFE)
7699 goto Undefined;
7700 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7701 goto onError;
7702 }
7703 else {
7704 writer->overallocate = 1;
7705 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7706 goto onError;
7707 }
7708 }
7709 else {
7710 /* wrong return value */
7711 PyErr_SetString(PyExc_TypeError,
7712 "character mapping must return integer, None or str");
7713 goto onError;
7714 }
7715 Py_CLEAR(item);
7716 ++s;
7717 continue;
7718
7719Undefined:
7720 /* undefined mapping */
7721 Py_CLEAR(item);
7722 startinpos = s-starts;
7723 endinpos = startinpos+1;
7724 if (unicode_decode_call_errorhandler_writer(
7725 errors, &errorHandler,
7726 "charmap", "character maps to <undefined>",
7727 &starts, &e, &startinpos, &endinpos, &exc, &s,
7728 writer)) {
7729 goto onError;
7730 }
7731 }
7732 Py_XDECREF(errorHandler);
7733 Py_XDECREF(exc);
7734 return 0;
7735
7736onError:
7737 Py_XDECREF(item);
7738 Py_XDECREF(errorHandler);
7739 Py_XDECREF(exc);
7740 return -1;
7741}
7742
Alexander Belopolsky40018472011-02-26 01:02:56 +00007743PyObject *
7744PyUnicode_DecodeCharmap(const char *s,
7745 Py_ssize_t size,
7746 PyObject *mapping,
7747 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007748{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007749 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007750
Guido van Rossumd57fd912000-03-10 22:53:23 +00007751 /* Default to Latin-1 */
7752 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007753 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007754
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007756 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007757 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007758 writer.min_length = size;
7759 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007760 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007761
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007762 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007763 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7764 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007765 }
7766 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007767 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7768 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007769 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007770 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007771
Benjamin Peterson29060642009-01-31 22:14:21 +00007772 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007773 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007774 return NULL;
7775}
7776
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007777/* Charmap encoding: the lookup table */
7778
Alexander Belopolsky40018472011-02-26 01:02:56 +00007779struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007780 PyObject_HEAD
7781 unsigned char level1[32];
7782 int count2, count3;
7783 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007784};
7785
7786static PyObject*
7787encoding_map_size(PyObject *obj, PyObject* args)
7788{
7789 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007790 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007792}
7793
7794static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007795 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007796 PyDoc_STR("Return the size (in bytes) of this object") },
7797 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007798};
7799
7800static void
7801encoding_map_dealloc(PyObject* o)
7802{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007803 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007804}
7805
7806static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007807 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007808 "EncodingMap", /*tp_name*/
7809 sizeof(struct encoding_map), /*tp_basicsize*/
7810 0, /*tp_itemsize*/
7811 /* methods */
7812 encoding_map_dealloc, /*tp_dealloc*/
7813 0, /*tp_print*/
7814 0, /*tp_getattr*/
7815 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007816 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007817 0, /*tp_repr*/
7818 0, /*tp_as_number*/
7819 0, /*tp_as_sequence*/
7820 0, /*tp_as_mapping*/
7821 0, /*tp_hash*/
7822 0, /*tp_call*/
7823 0, /*tp_str*/
7824 0, /*tp_getattro*/
7825 0, /*tp_setattro*/
7826 0, /*tp_as_buffer*/
7827 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7828 0, /*tp_doc*/
7829 0, /*tp_traverse*/
7830 0, /*tp_clear*/
7831 0, /*tp_richcompare*/
7832 0, /*tp_weaklistoffset*/
7833 0, /*tp_iter*/
7834 0, /*tp_iternext*/
7835 encoding_map_methods, /*tp_methods*/
7836 0, /*tp_members*/
7837 0, /*tp_getset*/
7838 0, /*tp_base*/
7839 0, /*tp_dict*/
7840 0, /*tp_descr_get*/
7841 0, /*tp_descr_set*/
7842 0, /*tp_dictoffset*/
7843 0, /*tp_init*/
7844 0, /*tp_alloc*/
7845 0, /*tp_new*/
7846 0, /*tp_free*/
7847 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007848};
7849
7850PyObject*
7851PyUnicode_BuildEncodingMap(PyObject* string)
7852{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853 PyObject *result;
7854 struct encoding_map *mresult;
7855 int i;
7856 int need_dict = 0;
7857 unsigned char level1[32];
7858 unsigned char level2[512];
7859 unsigned char *mlevel1, *mlevel2, *mlevel3;
7860 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007861 int kind;
7862 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007863 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007864 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007865
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007866 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007867 PyErr_BadArgument();
7868 return NULL;
7869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007870 kind = PyUnicode_KIND(string);
7871 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007872 length = PyUnicode_GET_LENGTH(string);
7873 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874 memset(level1, 0xFF, sizeof level1);
7875 memset(level2, 0xFF, sizeof level2);
7876
7877 /* If there isn't a one-to-one mapping of NULL to \0,
7878 or if there are non-BMP characters, we need to use
7879 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007880 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007881 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007882 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007883 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007884 ch = PyUnicode_READ(kind, data, i);
7885 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007886 need_dict = 1;
7887 break;
7888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007889 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007890 /* unmapped character */
7891 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007892 l1 = ch >> 11;
7893 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007894 if (level1[l1] == 0xFF)
7895 level1[l1] = count2++;
7896 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007897 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007898 }
7899
7900 if (count2 >= 0xFF || count3 >= 0xFF)
7901 need_dict = 1;
7902
7903 if (need_dict) {
7904 PyObject *result = PyDict_New();
7905 PyObject *key, *value;
7906 if (!result)
7907 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007908 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007909 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007910 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007911 if (!key || !value)
7912 goto failed1;
7913 if (PyDict_SetItem(result, key, value) == -1)
7914 goto failed1;
7915 Py_DECREF(key);
7916 Py_DECREF(value);
7917 }
7918 return result;
7919 failed1:
7920 Py_XDECREF(key);
7921 Py_XDECREF(value);
7922 Py_DECREF(result);
7923 return NULL;
7924 }
7925
7926 /* Create a three-level trie */
7927 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7928 16*count2 + 128*count3 - 1);
7929 if (!result)
7930 return PyErr_NoMemory();
7931 PyObject_Init(result, &EncodingMapType);
7932 mresult = (struct encoding_map*)result;
7933 mresult->count2 = count2;
7934 mresult->count3 = count3;
7935 mlevel1 = mresult->level1;
7936 mlevel2 = mresult->level23;
7937 mlevel3 = mresult->level23 + 16*count2;
7938 memcpy(mlevel1, level1, 32);
7939 memset(mlevel2, 0xFF, 16*count2);
7940 memset(mlevel3, 0, 128*count3);
7941 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007942 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007943 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007944 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7945 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007946 /* unmapped character */
7947 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007948 o1 = ch>>11;
7949 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 i2 = 16*mlevel1[o1] + o2;
7951 if (mlevel2[i2] == 0xFF)
7952 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007953 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007954 i3 = 128*mlevel2[i2] + o3;
7955 mlevel3[i3] = i;
7956 }
7957 return result;
7958}
7959
7960static int
Victor Stinner22168992011-11-20 17:09:18 +01007961encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007962{
7963 struct encoding_map *map = (struct encoding_map*)mapping;
7964 int l1 = c>>11;
7965 int l2 = (c>>7) & 0xF;
7966 int l3 = c & 0x7F;
7967 int i;
7968
Victor Stinner22168992011-11-20 17:09:18 +01007969 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007970 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007971 if (c == 0)
7972 return 0;
7973 /* level 1*/
7974 i = map->level1[l1];
7975 if (i == 0xFF) {
7976 return -1;
7977 }
7978 /* level 2*/
7979 i = map->level23[16*i+l2];
7980 if (i == 0xFF) {
7981 return -1;
7982 }
7983 /* level 3 */
7984 i = map->level23[16*map->count2 + 128*i + l3];
7985 if (i == 0) {
7986 return -1;
7987 }
7988 return i;
7989}
7990
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007991/* Lookup the character ch in the mapping. If the character
7992 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007993 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007994static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007995charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007996{
Christian Heimes217cfd12007-12-02 14:31:20 +00007997 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007998 PyObject *x;
7999
8000 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008001 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008002 x = PyObject_GetItem(mapping, w);
8003 Py_DECREF(w);
8004 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8006 /* No mapping found means: mapping is undefined. */
8007 PyErr_Clear();
8008 x = Py_None;
8009 Py_INCREF(x);
8010 return x;
8011 } else
8012 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008013 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008014 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008016 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 long value = PyLong_AS_LONG(x);
8018 if (value < 0 || value > 255) {
8019 PyErr_SetString(PyExc_TypeError,
8020 "character mapping must be in range(256)");
8021 Py_DECREF(x);
8022 return NULL;
8023 }
8024 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008025 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008026 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008028 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 /* wrong return value */
8030 PyErr_Format(PyExc_TypeError,
8031 "character mapping must return integer, bytes or None, not %.400s",
8032 x->ob_type->tp_name);
8033 Py_DECREF(x);
8034 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008035 }
8036}
8037
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008038static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008039charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008041 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8042 /* exponentially overallocate to minimize reallocations */
8043 if (requiredsize < 2*outsize)
8044 requiredsize = 2*outsize;
8045 if (_PyBytes_Resize(outobj, requiredsize))
8046 return -1;
8047 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008048}
8049
Benjamin Peterson14339b62009-01-31 16:36:08 +00008050typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008051 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008052} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008054 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008055 space is available. Return a new reference to the object that
8056 was put in the output buffer, or Py_None, if the mapping was undefined
8057 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008058 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008059static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008060charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008061 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063 PyObject *rep;
8064 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008065 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008066
Christian Heimes90aa7642007-12-19 02:45:37 +00008067 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008068 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070 if (res == -1)
8071 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008072 if (outsize<requiredsize)
8073 if (charmapencode_resize(outobj, outpos, requiredsize))
8074 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008075 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 outstart[(*outpos)++] = (char)res;
8077 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 }
8079
8080 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008081 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008082 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 Py_DECREF(rep);
8085 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008086 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 if (PyLong_Check(rep)) {
8088 Py_ssize_t requiredsize = *outpos+1;
8089 if (outsize<requiredsize)
8090 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8091 Py_DECREF(rep);
8092 return enc_EXCEPTION;
8093 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008094 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008096 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008097 else {
8098 const char *repchars = PyBytes_AS_STRING(rep);
8099 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8100 Py_ssize_t requiredsize = *outpos+repsize;
8101 if (outsize<requiredsize)
8102 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8103 Py_DECREF(rep);
8104 return enc_EXCEPTION;
8105 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008106 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 memcpy(outstart + *outpos, repchars, repsize);
8108 *outpos += repsize;
8109 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 Py_DECREF(rep);
8112 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113}
8114
8115/* handle an error in PyUnicode_EncodeCharmap
8116 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008117static int
8118charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008121 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008122 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008123{
8124 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008125 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008126 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008127 enum PyUnicode_Kind kind;
8128 void *data;
8129 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008131 Py_ssize_t collstartpos = *inpos;
8132 Py_ssize_t collendpos = *inpos+1;
8133 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008134 char *encoding = "charmap";
8135 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008137 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008138 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008139
Benjamin Petersonbac79492012-01-14 13:34:47 -05008140 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008141 return -1;
8142 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008143 /* find all unencodable characters */
8144 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008145 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008146 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008147 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008148 val = encoding_map_lookup(ch, mapping);
8149 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 break;
8151 ++collendpos;
8152 continue;
8153 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008154
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008155 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8156 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 if (rep==NULL)
8158 return -1;
8159 else if (rep!=Py_None) {
8160 Py_DECREF(rep);
8161 break;
8162 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008163 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165 }
8166 /* cache callback name lookup
8167 * (if not done yet, i.e. it's the first error) */
8168 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 if ((errors==NULL) || (!strcmp(errors, "strict")))
8170 *known_errorHandler = 1;
8171 else if (!strcmp(errors, "replace"))
8172 *known_errorHandler = 2;
8173 else if (!strcmp(errors, "ignore"))
8174 *known_errorHandler = 3;
8175 else if (!strcmp(errors, "xmlcharrefreplace"))
8176 *known_errorHandler = 4;
8177 else
8178 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008179 }
8180 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008181 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008182 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 return -1;
8184 case 2: /* replace */
8185 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 x = charmapencode_output('?', mapping, res, respos);
8187 if (x==enc_EXCEPTION) {
8188 return -1;
8189 }
8190 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008191 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 return -1;
8193 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008194 }
8195 /* fall through */
8196 case 3: /* ignore */
8197 *inpos = collendpos;
8198 break;
8199 case 4: /* xmlcharrefreplace */
8200 /* generate replacement (temporarily (mis)uses p) */
8201 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 char buffer[2+29+1+1];
8203 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008204 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 for (cp = buffer; *cp; ++cp) {
8206 x = charmapencode_output(*cp, mapping, res, respos);
8207 if (x==enc_EXCEPTION)
8208 return -1;
8209 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008210 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 return -1;
8212 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008213 }
8214 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008215 *inpos = collendpos;
8216 break;
8217 default:
8218 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008219 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008221 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008223 if (PyBytes_Check(repunicode)) {
8224 /* Directly copy bytes result to output. */
8225 Py_ssize_t outsize = PyBytes_Size(*res);
8226 Py_ssize_t requiredsize;
8227 repsize = PyBytes_Size(repunicode);
8228 requiredsize = *respos + repsize;
8229 if (requiredsize > outsize)
8230 /* Make room for all additional bytes. */
8231 if (charmapencode_resize(res, respos, requiredsize)) {
8232 Py_DECREF(repunicode);
8233 return -1;
8234 }
8235 memcpy(PyBytes_AsString(*res) + *respos,
8236 PyBytes_AsString(repunicode), repsize);
8237 *respos += repsize;
8238 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008239 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008240 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008241 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008242 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008243 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008244 Py_DECREF(repunicode);
8245 return -1;
8246 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008247 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008248 data = PyUnicode_DATA(repunicode);
8249 kind = PyUnicode_KIND(repunicode);
8250 for (index = 0; index < repsize; index++) {
8251 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8252 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008254 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 return -1;
8256 }
8257 else if (x==enc_FAILED) {
8258 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008259 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 return -1;
8261 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008262 }
8263 *inpos = newpos;
8264 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 }
8266 return 0;
8267}
8268
Alexander Belopolsky40018472011-02-26 01:02:56 +00008269PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008270_PyUnicode_EncodeCharmap(PyObject *unicode,
8271 PyObject *mapping,
8272 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008273{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008274 /* output object */
8275 PyObject *res = NULL;
8276 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008277 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008278 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008280 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 PyObject *errorHandler = NULL;
8282 PyObject *exc = NULL;
8283 /* the following variable is used for caching string comparisons
8284 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8285 * 3=ignore, 4=xmlcharrefreplace */
8286 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008287 void *data;
8288 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008289
Benjamin Petersonbac79492012-01-14 13:34:47 -05008290 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008291 return NULL;
8292 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008293 data = PyUnicode_DATA(unicode);
8294 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008295
Guido van Rossumd57fd912000-03-10 22:53:23 +00008296 /* Default to Latin-1 */
8297 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008298 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008299
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300 /* allocate enough for a simple encoding without
8301 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008302 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303 if (res == NULL)
8304 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008305 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008307
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008309 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008311 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 if (x==enc_EXCEPTION) /* error */
8313 goto onError;
8314 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008315 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 &exc,
8317 &known_errorHandler, &errorHandler, errors,
8318 &res, &respos)) {
8319 goto onError;
8320 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008321 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 else
8323 /* done with this character => adjust input position */
8324 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008325 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008326
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008328 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008329 if (_PyBytes_Resize(&res, respos) < 0)
8330 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 Py_XDECREF(exc);
8333 Py_XDECREF(errorHandler);
8334 return res;
8335
Benjamin Peterson29060642009-01-31 22:14:21 +00008336 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 Py_XDECREF(res);
8338 Py_XDECREF(exc);
8339 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340 return NULL;
8341}
8342
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008343/* Deprecated */
8344PyObject *
8345PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8346 Py_ssize_t size,
8347 PyObject *mapping,
8348 const char *errors)
8349{
8350 PyObject *result;
8351 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8352 if (unicode == NULL)
8353 return NULL;
8354 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8355 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008356 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008357}
8358
Alexander Belopolsky40018472011-02-26 01:02:56 +00008359PyObject *
8360PyUnicode_AsCharmapString(PyObject *unicode,
8361 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008362{
8363 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 PyErr_BadArgument();
8365 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008366 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008367 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008368}
8369
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008371static void
8372make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008373 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008374 Py_ssize_t startpos, Py_ssize_t endpos,
8375 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378 *exceptionObject = _PyUnicodeTranslateError_Create(
8379 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008380 }
8381 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8383 goto onError;
8384 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8385 goto onError;
8386 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8387 goto onError;
8388 return;
8389 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008390 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 }
8392}
8393
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394/* error handling callback helper:
8395 build arguments, call the callback and check the arguments,
8396 put the result into newpos and return the replacement string, which
8397 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008398static PyObject *
8399unicode_translate_call_errorhandler(const char *errors,
8400 PyObject **errorHandler,
8401 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008402 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008403 Py_ssize_t startpos, Py_ssize_t endpos,
8404 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008406 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008408 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409 PyObject *restuple;
8410 PyObject *resunicode;
8411
8412 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416 }
8417
8418 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422
8423 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008427 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008428 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 Py_DECREF(restuple);
8430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 }
8432 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 &resunicode, &i_newpos)) {
8434 Py_DECREF(restuple);
8435 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008437 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008439 else
8440 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008441 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008442 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 Py_DECREF(restuple);
8444 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008445 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 Py_INCREF(resunicode);
8447 Py_DECREF(restuple);
8448 return resunicode;
8449}
8450
8451/* Lookup the character ch in the mapping and put the result in result,
8452 which must be decrefed by the caller.
8453 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008454static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456{
Christian Heimes217cfd12007-12-02 14:31:20 +00008457 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008458 PyObject *x;
8459
8460 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462 x = PyObject_GetItem(mapping, w);
8463 Py_DECREF(w);
8464 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8466 /* No mapping found means: use 1:1 mapping. */
8467 PyErr_Clear();
8468 *result = NULL;
8469 return 0;
8470 } else
8471 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472 }
8473 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 *result = x;
8475 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008477 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008479 if (value < 0 || value > MAX_UNICODE) {
8480 PyErr_Format(PyExc_ValueError,
8481 "character mapping must be in range(0x%x)",
8482 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 Py_DECREF(x);
8484 return -1;
8485 }
8486 *result = x;
8487 return 0;
8488 }
8489 else if (PyUnicode_Check(x)) {
8490 *result = x;
8491 return 0;
8492 }
8493 else {
8494 /* wrong return value */
8495 PyErr_SetString(PyExc_TypeError,
8496 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008497 Py_DECREF(x);
8498 return -1;
8499 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500}
Victor Stinner1194ea02014-04-04 19:37:40 +02008501
8502/* lookup the character, write the result into the writer.
8503 Return 1 if the result was written into the writer, return 0 if the mapping
8504 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008506charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8507 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508{
Victor Stinner1194ea02014-04-04 19:37:40 +02008509 PyObject *item;
8510
8511 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008513
8514 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008516 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008519 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008521
8522 if (item == Py_None) {
8523 Py_DECREF(item);
8524 return 0;
8525 }
8526
8527 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008528 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8529 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8530 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008531 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8532 Py_DECREF(item);
8533 return -1;
8534 }
8535 Py_DECREF(item);
8536 return 1;
8537 }
8538
8539 if (!PyUnicode_Check(item)) {
8540 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008542 }
8543
8544 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8545 Py_DECREF(item);
8546 return -1;
8547 }
8548
8549 Py_DECREF(item);
8550 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551}
8552
Victor Stinner89a76ab2014-04-05 11:44:04 +02008553static int
8554unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8555 Py_UCS1 *translate)
8556{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008557 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008558 int ret = 0;
8559
Victor Stinner89a76ab2014-04-05 11:44:04 +02008560 if (charmaptranslate_lookup(ch, mapping, &item)) {
8561 return -1;
8562 }
8563
8564 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008565 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008566 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008567 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008568 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008569 /* not found => default to 1:1 mapping */
8570 translate[ch] = ch;
8571 return 1;
8572 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008573 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008574 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008575 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8576 used it */
8577 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008578 /* invalid character or character outside ASCII:
8579 skip the fast translate */
8580 goto exit;
8581 }
8582 translate[ch] = (Py_UCS1)replace;
8583 }
8584 else if (PyUnicode_Check(item)) {
8585 Py_UCS4 replace;
8586
8587 if (PyUnicode_READY(item) == -1) {
8588 Py_DECREF(item);
8589 return -1;
8590 }
8591 if (PyUnicode_GET_LENGTH(item) != 1)
8592 goto exit;
8593
8594 replace = PyUnicode_READ_CHAR(item, 0);
8595 if (replace > 127)
8596 goto exit;
8597 translate[ch] = (Py_UCS1)replace;
8598 }
8599 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008600 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008601 goto exit;
8602 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008603 ret = 1;
8604
Benjamin Peterson1365de72014-04-07 20:15:41 -04008605 exit:
8606 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008607 return ret;
8608}
8609
8610/* Fast path for ascii => ascii translation. Return 1 if the whole string
8611 was translated into writer, return 0 if the input string was partially
8612 translated into writer, raise an exception and return -1 on error. */
8613static int
8614unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008615 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008616{
Victor Stinner872b2912014-04-05 14:27:07 +02008617 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008618 Py_ssize_t len;
8619 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008620 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008621
8622 if (PyUnicode_READY(input) == -1)
8623 return -1;
8624 if (!PyUnicode_IS_ASCII(input))
8625 return 0;
8626 len = PyUnicode_GET_LENGTH(input);
8627
Victor Stinner872b2912014-04-05 14:27:07 +02008628 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008629
8630 in = PyUnicode_1BYTE_DATA(input);
8631 end = in + len;
8632
8633 assert(PyUnicode_IS_ASCII(writer->buffer));
8634 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8635 out = PyUnicode_1BYTE_DATA(writer->buffer);
8636
Victor Stinner872b2912014-04-05 14:27:07 +02008637 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008638 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008639 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008640 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008641 int translate = unicode_fast_translate_lookup(mapping, ch,
8642 ascii_table);
8643 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008644 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008645 if (translate == 0)
8646 goto exit;
8647 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008648 }
Victor Stinner872b2912014-04-05 14:27:07 +02008649 if (ch2 == 0xfe) {
8650 if (ignore)
8651 continue;
8652 goto exit;
8653 }
8654 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008655 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008656 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008657 }
Victor Stinner872b2912014-04-05 14:27:07 +02008658 res = 1;
8659
8660exit:
8661 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8662 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008663}
8664
Alexander Belopolsky40018472011-02-26 01:02:56 +00008665PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666_PyUnicode_TranslateCharmap(PyObject *input,
8667 PyObject *mapping,
8668 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008671 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 Py_ssize_t size, i;
8673 int kind;
8674 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008675 _PyUnicodeWriter writer;
8676 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 char *reason = "character maps to <undefined>";
8678 PyObject *errorHandler = NULL;
8679 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008680 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008681 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008682
Guido van Rossumd57fd912000-03-10 22:53:23 +00008683 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 PyErr_BadArgument();
8685 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008686 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 if (PyUnicode_READY(input) == -1)
8689 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008690 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 kind = PyUnicode_KIND(input);
8692 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693
8694 if (size == 0) {
8695 Py_INCREF(input);
8696 return input;
8697 }
8698
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008699 /* allocate enough for a simple 1:1 translation without
8700 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008701 _PyUnicodeWriter_Init(&writer);
8702 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008704
Victor Stinner872b2912014-04-05 14:27:07 +02008705 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8706
8707 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008708 if (res < 0) {
8709 _PyUnicodeWriter_Dealloc(&writer);
8710 return NULL;
8711 }
8712 if (res == 1)
8713 return _PyUnicodeWriter_Finish(&writer);
8714
Victor Stinner89a76ab2014-04-05 11:44:04 +02008715 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008718 int translate;
8719 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8720 Py_ssize_t newpos;
8721 /* startpos for collecting untranslatable chars */
8722 Py_ssize_t collstart;
8723 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008724 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008725
Victor Stinner1194ea02014-04-04 19:37:40 +02008726 ch = PyUnicode_READ(kind, data, i);
8727 translate = charmaptranslate_output(ch, mapping, &writer);
8728 if (translate < 0)
8729 goto onError;
8730
8731 if (translate != 0) {
8732 /* it worked => adjust input pointer */
8733 ++i;
8734 continue;
8735 }
8736
8737 /* untranslatable character */
8738 collstart = i;
8739 collend = i+1;
8740
8741 /* find all untranslatable characters */
8742 while (collend < size) {
8743 PyObject *x;
8744 ch = PyUnicode_READ(kind, data, collend);
8745 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008746 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008747 Py_XDECREF(x);
8748 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008750 ++collend;
8751 }
8752
8753 if (ignore) {
8754 i = collend;
8755 }
8756 else {
8757 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8758 reason, input, &exc,
8759 collstart, collend, &newpos);
8760 if (repunicode == NULL)
8761 goto onError;
8762 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008763 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008764 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008765 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008766 Py_DECREF(repunicode);
8767 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008768 }
8769 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770 Py_XDECREF(exc);
8771 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008772 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008773
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008775 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776 Py_XDECREF(exc);
8777 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008778 return NULL;
8779}
8780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008781/* Deprecated. Use PyUnicode_Translate instead. */
8782PyObject *
8783PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8784 Py_ssize_t size,
8785 PyObject *mapping,
8786 const char *errors)
8787{
Christian Heimes5f520f42012-09-11 14:03:25 +02008788 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008789 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8790 if (!unicode)
8791 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008792 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8793 Py_DECREF(unicode);
8794 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795}
8796
Alexander Belopolsky40018472011-02-26 01:02:56 +00008797PyObject *
8798PyUnicode_Translate(PyObject *str,
8799 PyObject *mapping,
8800 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008801{
8802 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008803
Guido van Rossumd57fd912000-03-10 22:53:23 +00008804 str = PyUnicode_FromObject(str);
8805 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008806 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008807 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008808 Py_DECREF(str);
8809 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008810}
Tim Petersced69f82003-09-16 20:30:58 +00008811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008812static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008813fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814{
8815 /* No need to call PyUnicode_READY(self) because this function is only
8816 called as a callback from fixup() which does it already. */
8817 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8818 const int kind = PyUnicode_KIND(self);
8819 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008820 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008821 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822 Py_ssize_t i;
8823
8824 for (i = 0; i < len; ++i) {
8825 ch = PyUnicode_READ(kind, data, i);
8826 fixed = 0;
8827 if (ch > 127) {
8828 if (Py_UNICODE_ISSPACE(ch))
8829 fixed = ' ';
8830 else {
8831 const int decimal = Py_UNICODE_TODECIMAL(ch);
8832 if (decimal >= 0)
8833 fixed = '0' + decimal;
8834 }
8835 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008836 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008837 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838 PyUnicode_WRITE(kind, data, i, fixed);
8839 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008840 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008841 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843 }
8844
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008845 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846}
8847
8848PyObject *
8849_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8850{
8851 if (!PyUnicode_Check(unicode)) {
8852 PyErr_BadInternalCall();
8853 return NULL;
8854 }
8855 if (PyUnicode_READY(unicode) == -1)
8856 return NULL;
8857 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8858 /* If the string is already ASCII, just return the same string */
8859 Py_INCREF(unicode);
8860 return unicode;
8861 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008862 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863}
8864
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008865PyObject *
8866PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8867 Py_ssize_t length)
8868{
Victor Stinnerf0124502011-11-21 23:12:56 +01008869 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008870 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008871 Py_UCS4 maxchar;
8872 enum PyUnicode_Kind kind;
8873 void *data;
8874
Victor Stinner99d7ad02012-02-22 13:37:39 +01008875 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008876 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008877 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008878 if (ch > 127) {
8879 int decimal = Py_UNICODE_TODECIMAL(ch);
8880 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008881 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008882 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008883 }
8884 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008885
8886 /* Copy to a new string */
8887 decimal = PyUnicode_New(length, maxchar);
8888 if (decimal == NULL)
8889 return decimal;
8890 kind = PyUnicode_KIND(decimal);
8891 data = PyUnicode_DATA(decimal);
8892 /* Iterate over code points */
8893 for (i = 0; i < length; i++) {
8894 Py_UNICODE ch = s[i];
8895 if (ch > 127) {
8896 int decimal = Py_UNICODE_TODECIMAL(ch);
8897 if (decimal >= 0)
8898 ch = '0' + decimal;
8899 }
8900 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008902 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008903}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008904/* --- Decimal Encoder ---------------------------------------------------- */
8905
Alexander Belopolsky40018472011-02-26 01:02:56 +00008906int
8907PyUnicode_EncodeDecimal(Py_UNICODE *s,
8908 Py_ssize_t length,
8909 char *output,
8910 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008911{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008912 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008913 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008914 enum PyUnicode_Kind kind;
8915 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008916
8917 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 PyErr_BadArgument();
8919 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008920 }
8921
Victor Stinner42bf7752011-11-21 22:52:58 +01008922 unicode = PyUnicode_FromUnicode(s, length);
8923 if (unicode == NULL)
8924 return -1;
8925
Benjamin Petersonbac79492012-01-14 13:34:47 -05008926 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008927 Py_DECREF(unicode);
8928 return -1;
8929 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008930 kind = PyUnicode_KIND(unicode);
8931 data = PyUnicode_DATA(unicode);
8932
Victor Stinnerb84d7232011-11-22 01:50:07 +01008933 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008934 PyObject *exc;
8935 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008936 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008937 Py_ssize_t startpos;
8938
8939 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008940
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008942 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008943 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008945 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008946 decimal = Py_UNICODE_TODECIMAL(ch);
8947 if (decimal >= 0) {
8948 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008949 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008950 continue;
8951 }
8952 if (0 < ch && ch < 256) {
8953 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008954 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 continue;
8956 }
Victor Stinner6345be92011-11-25 20:09:01 +01008957
Victor Stinner42bf7752011-11-21 22:52:58 +01008958 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008959 exc = NULL;
8960 raise_encode_exception(&exc, "decimal", unicode,
8961 startpos, startpos+1,
8962 "invalid decimal Unicode string");
8963 Py_XDECREF(exc);
8964 Py_DECREF(unicode);
8965 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008966 }
8967 /* 0-terminate the output string */
8968 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008969 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008970 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008971}
8972
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973/* --- Helpers ------------------------------------------------------------ */
8974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008976any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 Py_ssize_t start,
8978 Py_ssize_t end)
8979{
8980 int kind1, kind2, kind;
8981 void *buf1, *buf2;
8982 Py_ssize_t len1, len2, result;
8983
8984 kind1 = PyUnicode_KIND(s1);
8985 kind2 = PyUnicode_KIND(s2);
8986 kind = kind1 > kind2 ? kind1 : kind2;
8987 buf1 = PyUnicode_DATA(s1);
8988 buf2 = PyUnicode_DATA(s2);
8989 if (kind1 != kind)
8990 buf1 = _PyUnicode_AsKind(s1, kind);
8991 if (!buf1)
8992 return -2;
8993 if (kind2 != kind)
8994 buf2 = _PyUnicode_AsKind(s2, kind);
8995 if (!buf2) {
8996 if (kind1 != kind) PyMem_Free(buf1);
8997 return -2;
8998 }
8999 len1 = PyUnicode_GET_LENGTH(s1);
9000 len2 = PyUnicode_GET_LENGTH(s2);
9001
Victor Stinner794d5672011-10-10 03:21:36 +02009002 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009003 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009004 case PyUnicode_1BYTE_KIND:
9005 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9006 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9007 else
9008 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9009 break;
9010 case PyUnicode_2BYTE_KIND:
9011 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9012 break;
9013 case PyUnicode_4BYTE_KIND:
9014 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9015 break;
9016 default:
9017 assert(0); result = -2;
9018 }
9019 }
9020 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009021 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009022 case PyUnicode_1BYTE_KIND:
9023 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9024 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9025 else
9026 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9027 break;
9028 case PyUnicode_2BYTE_KIND:
9029 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9030 break;
9031 case PyUnicode_4BYTE_KIND:
9032 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9033 break;
9034 default:
9035 assert(0); result = -2;
9036 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037 }
9038
9039 if (kind1 != kind)
9040 PyMem_Free(buf1);
9041 if (kind2 != kind)
9042 PyMem_Free(buf2);
9043
9044 return result;
9045}
9046
9047Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009048_PyUnicode_InsertThousandsGrouping(
9049 PyObject *unicode, Py_ssize_t index,
9050 Py_ssize_t n_buffer,
9051 void *digits, Py_ssize_t n_digits,
9052 Py_ssize_t min_width,
9053 const char *grouping, PyObject *thousands_sep,
9054 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009055{
Victor Stinner41a863c2012-02-24 00:37:51 +01009056 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009057 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009058 Py_ssize_t thousands_sep_len;
9059 Py_ssize_t len;
9060
9061 if (unicode != NULL) {
9062 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009063 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009064 }
9065 else {
9066 kind = PyUnicode_1BYTE_KIND;
9067 data = NULL;
9068 }
9069 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9070 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9071 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9072 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009073 if (thousands_sep_kind < kind) {
9074 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9075 if (!thousands_sep_data)
9076 return -1;
9077 }
9078 else {
9079 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9080 if (!data)
9081 return -1;
9082 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009083 }
9084
Benjamin Petersonead6b532011-12-20 17:23:42 -06009085 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009087 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009088 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009089 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009090 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009091 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009092 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009094 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009095 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009096 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009097 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009100 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009102 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009103 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009105 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009106 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009107 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009108 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009109 break;
9110 default:
9111 assert(0);
9112 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009114 if (unicode != NULL && thousands_sep_kind != kind) {
9115 if (thousands_sep_kind < kind)
9116 PyMem_Free(thousands_sep_data);
9117 else
9118 PyMem_Free(data);
9119 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009120 if (unicode == NULL) {
9121 *maxchar = 127;
9122 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009123 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009124 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009125 }
9126 }
9127 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128}
9129
9130
Thomas Wouters477c8d52006-05-27 19:21:47 +00009131/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009132#define ADJUST_INDICES(start, end, len) \
9133 if (end > len) \
9134 end = len; \
9135 else if (end < 0) { \
9136 end += len; \
9137 if (end < 0) \
9138 end = 0; \
9139 } \
9140 if (start < 0) { \
9141 start += len; \
9142 if (start < 0) \
9143 start = 0; \
9144 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009145
Alexander Belopolsky40018472011-02-26 01:02:56 +00009146Py_ssize_t
9147PyUnicode_Count(PyObject *str,
9148 PyObject *substr,
9149 Py_ssize_t start,
9150 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009151{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009152 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009153 PyObject* str_obj;
9154 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009155 int kind1, kind2, kind;
9156 void *buf1 = NULL, *buf2 = NULL;
9157 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009158
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009159 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009160 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009162 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009163 if (!sub_obj) {
9164 Py_DECREF(str_obj);
9165 return -1;
9166 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009167 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009168 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009169 Py_DECREF(str_obj);
9170 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171 }
Tim Petersced69f82003-09-16 20:30:58 +00009172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173 kind1 = PyUnicode_KIND(str_obj);
9174 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009175 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009176 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009178 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009179 if (kind2 > kind) {
9180 Py_DECREF(sub_obj);
9181 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009182 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009183 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009184 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009185 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009186 if (!buf2)
9187 goto onError;
9188 len1 = PyUnicode_GET_LENGTH(str_obj);
9189 len2 = PyUnicode_GET_LENGTH(sub_obj);
9190
9191 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009192 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009193 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009194 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9195 result = asciilib_count(
9196 ((Py_UCS1*)buf1) + start, end - start,
9197 buf2, len2, PY_SSIZE_T_MAX
9198 );
9199 else
9200 result = ucs1lib_count(
9201 ((Py_UCS1*)buf1) + start, end - start,
9202 buf2, len2, PY_SSIZE_T_MAX
9203 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 break;
9205 case PyUnicode_2BYTE_KIND:
9206 result = ucs2lib_count(
9207 ((Py_UCS2*)buf1) + start, end - start,
9208 buf2, len2, PY_SSIZE_T_MAX
9209 );
9210 break;
9211 case PyUnicode_4BYTE_KIND:
9212 result = ucs4lib_count(
9213 ((Py_UCS4*)buf1) + start, end - start,
9214 buf2, len2, PY_SSIZE_T_MAX
9215 );
9216 break;
9217 default:
9218 assert(0); result = 0;
9219 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009220
9221 Py_DECREF(sub_obj);
9222 Py_DECREF(str_obj);
9223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224 if (kind2 != kind)
9225 PyMem_Free(buf2);
9226
Guido van Rossumd57fd912000-03-10 22:53:23 +00009227 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 onError:
9229 Py_DECREF(sub_obj);
9230 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 if (kind2 != kind && buf2)
9232 PyMem_Free(buf2);
9233 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234}
9235
Alexander Belopolsky40018472011-02-26 01:02:56 +00009236Py_ssize_t
9237PyUnicode_Find(PyObject *str,
9238 PyObject *sub,
9239 Py_ssize_t start,
9240 Py_ssize_t end,
9241 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009243 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009244
Guido van Rossumd57fd912000-03-10 22:53:23 +00009245 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009246 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009247 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009248 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009249 if (!sub) {
9250 Py_DECREF(str);
9251 return -2;
9252 }
9253 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9254 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009255 Py_DECREF(str);
9256 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257 }
Tim Petersced69f82003-09-16 20:30:58 +00009258
Victor Stinner794d5672011-10-10 03:21:36 +02009259 result = any_find_slice(direction,
9260 str, sub, start, end
9261 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009262
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009264 Py_DECREF(sub);
9265
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266 return result;
9267}
9268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269Py_ssize_t
9270PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9271 Py_ssize_t start, Py_ssize_t end,
9272 int direction)
9273{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009275 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 if (PyUnicode_READY(str) == -1)
9277 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009278 if (start < 0 || end < 0) {
9279 PyErr_SetString(PyExc_IndexError, "string index out of range");
9280 return -2;
9281 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 if (end > PyUnicode_GET_LENGTH(str))
9283 end = PyUnicode_GET_LENGTH(str);
9284 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009285 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9286 kind, end-start, ch, direction);
9287 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009289 else
9290 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291}
9292
Alexander Belopolsky40018472011-02-26 01:02:56 +00009293static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009294tailmatch(PyObject *self,
9295 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009296 Py_ssize_t start,
9297 Py_ssize_t end,
9298 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 int kind_self;
9301 int kind_sub;
9302 void *data_self;
9303 void *data_sub;
9304 Py_ssize_t offset;
9305 Py_ssize_t i;
9306 Py_ssize_t end_sub;
9307
9308 if (PyUnicode_READY(self) == -1 ||
9309 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009310 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311
9312 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313 return 1;
9314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9316 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009317 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009318 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 kind_self = PyUnicode_KIND(self);
9321 data_self = PyUnicode_DATA(self);
9322 kind_sub = PyUnicode_KIND(substring);
9323 data_sub = PyUnicode_DATA(substring);
9324 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9325
9326 if (direction > 0)
9327 offset = end;
9328 else
9329 offset = start;
9330
9331 if (PyUnicode_READ(kind_self, data_self, offset) ==
9332 PyUnicode_READ(kind_sub, data_sub, 0) &&
9333 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9334 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9335 /* If both are of the same kind, memcmp is sufficient */
9336 if (kind_self == kind_sub) {
9337 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009338 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009339 data_sub,
9340 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009341 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 }
9343 /* otherwise we have to compare each character by first accesing it */
9344 else {
9345 /* We do not need to compare 0 and len(substring)-1 because
9346 the if statement above ensured already that they are equal
9347 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 for (i = 1; i < end_sub; ++i) {
9349 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9350 PyUnicode_READ(kind_sub, data_sub, i))
9351 return 0;
9352 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009353 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009355 }
9356
9357 return 0;
9358}
9359
Alexander Belopolsky40018472011-02-26 01:02:56 +00009360Py_ssize_t
9361PyUnicode_Tailmatch(PyObject *str,
9362 PyObject *substr,
9363 Py_ssize_t start,
9364 Py_ssize_t end,
9365 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009367 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009368
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369 str = PyUnicode_FromObject(str);
9370 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009371 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372 substr = PyUnicode_FromObject(substr);
9373 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009374 Py_DECREF(str);
9375 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 }
Tim Petersced69f82003-09-16 20:30:58 +00009377
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009378 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009379 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 Py_DECREF(str);
9381 Py_DECREF(substr);
9382 return result;
9383}
9384
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385/* Apply fixfct filter to the Unicode object self and return a
9386 reference to the modified object */
9387
Alexander Belopolsky40018472011-02-26 01:02:56 +00009388static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009389fixup(PyObject *self,
9390 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 PyObject *u;
9393 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009394 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009396 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009398 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009399 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009401 /* fix functions return the new maximum character in a string,
9402 if the kind of the resulting unicode object does not change,
9403 everything is fine. Otherwise we need to change the string kind
9404 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009405 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009406
9407 if (maxchar_new == 0) {
9408 /* no changes */;
9409 if (PyUnicode_CheckExact(self)) {
9410 Py_DECREF(u);
9411 Py_INCREF(self);
9412 return self;
9413 }
9414 else
9415 return u;
9416 }
9417
Victor Stinnere6abb482012-05-02 01:15:40 +02009418 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419
Victor Stinnereaab6042011-12-11 22:22:39 +01009420 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009422
9423 /* In case the maximum character changed, we need to
9424 convert the string to the new category. */
9425 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9426 if (v == NULL) {
9427 Py_DECREF(u);
9428 return NULL;
9429 }
9430 if (maxchar_new > maxchar_old) {
9431 /* If the maxchar increased so that the kind changed, not all
9432 characters are representable anymore and we need to fix the
9433 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009434 _PyUnicode_FastCopyCharacters(v, 0,
9435 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009436 maxchar_old = fixfct(v);
9437 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 }
9439 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009440 _PyUnicode_FastCopyCharacters(v, 0,
9441 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009443 Py_DECREF(u);
9444 assert(_PyUnicode_CheckConsistency(v, 1));
9445 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009446}
9447
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009448static PyObject *
9449ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009451 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9452 char *resdata, *data = PyUnicode_DATA(self);
9453 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009454
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009455 res = PyUnicode_New(len, 127);
9456 if (res == NULL)
9457 return NULL;
9458 resdata = PyUnicode_DATA(res);
9459 if (lower)
9460 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009462 _Py_bytes_upper(resdata, data, len);
9463 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464}
9465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009467handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009468{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009469 Py_ssize_t j;
9470 int final_sigma;
9471 Py_UCS4 c;
9472 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009473
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009474 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9475
9476 where ! is a negation and \p{xxx} is a character with property xxx.
9477 */
9478 for (j = i - 1; j >= 0; j--) {
9479 c = PyUnicode_READ(kind, data, j);
9480 if (!_PyUnicode_IsCaseIgnorable(c))
9481 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009483 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9484 if (final_sigma) {
9485 for (j = i + 1; j < length; j++) {
9486 c = PyUnicode_READ(kind, data, j);
9487 if (!_PyUnicode_IsCaseIgnorable(c))
9488 break;
9489 }
9490 final_sigma = j == length || !_PyUnicode_IsCased(c);
9491 }
9492 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493}
9494
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009495static int
9496lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9497 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009499 /* Obscure special case. */
9500 if (c == 0x3A3) {
9501 mapped[0] = handle_capital_sigma(kind, data, length, i);
9502 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009504 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505}
9506
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009507static Py_ssize_t
9508do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009510 Py_ssize_t i, k = 0;
9511 int n_res, j;
9512 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009513
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009514 c = PyUnicode_READ(kind, data, 0);
9515 n_res = _PyUnicode_ToUpperFull(c, mapped);
9516 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009517 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009518 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009519 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009520 for (i = 1; i < length; i++) {
9521 c = PyUnicode_READ(kind, data, i);
9522 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9523 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009524 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009525 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009526 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009527 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009528 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009529}
9530
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009531static Py_ssize_t
9532do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9533 Py_ssize_t i, k = 0;
9534
9535 for (i = 0; i < length; i++) {
9536 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9537 int n_res, j;
9538 if (Py_UNICODE_ISUPPER(c)) {
9539 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9540 }
9541 else if (Py_UNICODE_ISLOWER(c)) {
9542 n_res = _PyUnicode_ToUpperFull(c, mapped);
9543 }
9544 else {
9545 n_res = 1;
9546 mapped[0] = c;
9547 }
9548 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009549 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009550 res[k++] = mapped[j];
9551 }
9552 }
9553 return k;
9554}
9555
9556static Py_ssize_t
9557do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9558 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009559{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009560 Py_ssize_t i, k = 0;
9561
9562 for (i = 0; i < length; i++) {
9563 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9564 int n_res, j;
9565 if (lower)
9566 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9567 else
9568 n_res = _PyUnicode_ToUpperFull(c, mapped);
9569 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009570 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009571 res[k++] = mapped[j];
9572 }
9573 }
9574 return k;
9575}
9576
9577static Py_ssize_t
9578do_upper(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, 0);
9581}
9582
9583static Py_ssize_t
9584do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9585{
9586 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9587}
9588
Benjamin Petersone51757f2012-01-12 21:10:29 -05009589static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009590do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9591{
9592 Py_ssize_t i, k = 0;
9593
9594 for (i = 0; i < length; i++) {
9595 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9596 Py_UCS4 mapped[3];
9597 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9598 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009599 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009600 res[k++] = mapped[j];
9601 }
9602 }
9603 return k;
9604}
9605
9606static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009607do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9608{
9609 Py_ssize_t i, k = 0;
9610 int previous_is_cased;
9611
9612 previous_is_cased = 0;
9613 for (i = 0; i < length; i++) {
9614 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9615 Py_UCS4 mapped[3];
9616 int n_res, j;
9617
9618 if (previous_is_cased)
9619 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9620 else
9621 n_res = _PyUnicode_ToTitleFull(c, mapped);
9622
9623 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009624 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009625 res[k++] = mapped[j];
9626 }
9627
9628 previous_is_cased = _PyUnicode_IsCased(c);
9629 }
9630 return k;
9631}
9632
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009633static PyObject *
9634case_operation(PyObject *self,
9635 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9636{
9637 PyObject *res = NULL;
9638 Py_ssize_t length, newlength = 0;
9639 int kind, outkind;
9640 void *data, *outdata;
9641 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9642
Benjamin Petersoneea48462012-01-16 14:28:50 -05009643 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644
9645 kind = PyUnicode_KIND(self);
9646 data = PyUnicode_DATA(self);
9647 length = PyUnicode_GET_LENGTH(self);
9648 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9649 if (tmp == NULL)
9650 return PyErr_NoMemory();
9651 newlength = perform(kind, data, length, tmp, &maxchar);
9652 res = PyUnicode_New(newlength, maxchar);
9653 if (res == NULL)
9654 goto leave;
9655 tmpend = tmp + newlength;
9656 outdata = PyUnicode_DATA(res);
9657 outkind = PyUnicode_KIND(res);
9658 switch (outkind) {
9659 case PyUnicode_1BYTE_KIND:
9660 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9661 break;
9662 case PyUnicode_2BYTE_KIND:
9663 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9664 break;
9665 case PyUnicode_4BYTE_KIND:
9666 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9667 break;
9668 default:
9669 assert(0);
9670 break;
9671 }
9672 leave:
9673 PyMem_FREE(tmp);
9674 return res;
9675}
9676
Tim Peters8ce9f162004-08-27 01:49:32 +00009677PyObject *
9678PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009681 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009683 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009684 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9685 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009686 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009688 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009690 int use_memcpy;
9691 unsigned char *res_data = NULL, *sep_data = NULL;
9692 PyObject *last_obj;
9693 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009695 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009696 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009697 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009698 }
9699
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009700 /* NOTE: the following code can't call back into Python code,
9701 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009702 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009703
Tim Peters05eba1f2004-08-27 21:32:02 +00009704 seqlen = PySequence_Fast_GET_SIZE(fseq);
9705 /* If empty sequence, return u"". */
9706 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009707 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009708 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009709 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009710
Tim Peters05eba1f2004-08-27 21:32:02 +00009711 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009712 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009713 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009714 if (seqlen == 1) {
9715 if (PyUnicode_CheckExact(items[0])) {
9716 res = items[0];
9717 Py_INCREF(res);
9718 Py_DECREF(fseq);
9719 return res;
9720 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009721 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009722 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009723 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009724 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009725 /* Set up sep and seplen */
9726 if (separator == NULL) {
9727 /* fall back to a blank space separator */
9728 sep = PyUnicode_FromOrdinal(' ');
9729 if (!sep)
9730 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009731 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009732 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009733 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009734 else {
9735 if (!PyUnicode_Check(separator)) {
9736 PyErr_Format(PyExc_TypeError,
9737 "separator: expected str instance,"
9738 " %.80s found",
9739 Py_TYPE(separator)->tp_name);
9740 goto onError;
9741 }
9742 if (PyUnicode_READY(separator))
9743 goto onError;
9744 sep = separator;
9745 seplen = PyUnicode_GET_LENGTH(separator);
9746 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9747 /* inc refcount to keep this code path symmetric with the
9748 above case of a blank separator */
9749 Py_INCREF(sep);
9750 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009751 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009752 }
9753
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009754 /* There are at least two things to join, or else we have a subclass
9755 * of str in the sequence.
9756 * Do a pre-pass to figure out the total amount of space we'll
9757 * need (sz), and see whether all argument are strings.
9758 */
9759 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009760#ifdef Py_DEBUG
9761 use_memcpy = 0;
9762#else
9763 use_memcpy = 1;
9764#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009765 for (i = 0; i < seqlen; i++) {
9766 const Py_ssize_t old_sz = sz;
9767 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009768 if (!PyUnicode_Check(item)) {
9769 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009770 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009771 " %.80s found",
9772 i, Py_TYPE(item)->tp_name);
9773 goto onError;
9774 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 if (PyUnicode_READY(item) == -1)
9776 goto onError;
9777 sz += PyUnicode_GET_LENGTH(item);
9778 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009779 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009780 if (i != 0)
9781 sz += seplen;
9782 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9783 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009784 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009785 goto onError;
9786 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009787 if (use_memcpy && last_obj != NULL) {
9788 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9789 use_memcpy = 0;
9790 }
9791 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009792 }
Tim Petersced69f82003-09-16 20:30:58 +00009793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009794 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009795 if (res == NULL)
9796 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009797
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009798 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009799#ifdef Py_DEBUG
9800 use_memcpy = 0;
9801#else
9802 if (use_memcpy) {
9803 res_data = PyUnicode_1BYTE_DATA(res);
9804 kind = PyUnicode_KIND(res);
9805 if (seplen != 0)
9806 sep_data = PyUnicode_1BYTE_DATA(sep);
9807 }
9808#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009809 if (use_memcpy) {
9810 for (i = 0; i < seqlen; ++i) {
9811 Py_ssize_t itemlen;
9812 item = items[i];
9813
9814 /* Copy item, and maybe the separator. */
9815 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009816 Py_MEMCPY(res_data,
9817 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009818 kind * seplen);
9819 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009820 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009821
9822 itemlen = PyUnicode_GET_LENGTH(item);
9823 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009824 Py_MEMCPY(res_data,
9825 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009826 kind * itemlen);
9827 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009828 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009829 }
9830 assert(res_data == PyUnicode_1BYTE_DATA(res)
9831 + kind * PyUnicode_GET_LENGTH(res));
9832 }
9833 else {
9834 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9835 Py_ssize_t itemlen;
9836 item = items[i];
9837
9838 /* Copy item, and maybe the separator. */
9839 if (i && seplen != 0) {
9840 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9841 res_offset += seplen;
9842 }
9843
9844 itemlen = PyUnicode_GET_LENGTH(item);
9845 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009846 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009847 res_offset += itemlen;
9848 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009849 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009850 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009851 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009852
Tim Peters05eba1f2004-08-27 21:32:02 +00009853 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009855 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009856 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857
Benjamin Peterson29060642009-01-31 22:14:21 +00009858 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009859 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009861 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009862 return NULL;
9863}
9864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865#define FILL(kind, data, value, start, length) \
9866 do { \
9867 Py_ssize_t i_ = 0; \
9868 assert(kind != PyUnicode_WCHAR_KIND); \
9869 switch ((kind)) { \
9870 case PyUnicode_1BYTE_KIND: { \
9871 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009872 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 break; \
9874 } \
9875 case PyUnicode_2BYTE_KIND: { \
9876 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9877 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9878 break; \
9879 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009880 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9882 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9883 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009884 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009885 } \
9886 } \
9887 } while (0)
9888
Victor Stinnerd3f08822012-05-29 12:57:52 +02009889void
9890_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9891 Py_UCS4 fill_char)
9892{
9893 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9894 const void *data = PyUnicode_DATA(unicode);
9895 assert(PyUnicode_IS_READY(unicode));
9896 assert(unicode_modifiable(unicode));
9897 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9898 assert(start >= 0);
9899 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9900 FILL(kind, data, fill_char, start, length);
9901}
9902
Victor Stinner3fe55312012-01-04 00:33:50 +01009903Py_ssize_t
9904PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9905 Py_UCS4 fill_char)
9906{
9907 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009908
9909 if (!PyUnicode_Check(unicode)) {
9910 PyErr_BadInternalCall();
9911 return -1;
9912 }
9913 if (PyUnicode_READY(unicode) == -1)
9914 return -1;
9915 if (unicode_check_modifiable(unicode))
9916 return -1;
9917
Victor Stinnerd3f08822012-05-29 12:57:52 +02009918 if (start < 0) {
9919 PyErr_SetString(PyExc_IndexError, "string index out of range");
9920 return -1;
9921 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009922 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9923 PyErr_SetString(PyExc_ValueError,
9924 "fill character is bigger than "
9925 "the string maximum character");
9926 return -1;
9927 }
9928
9929 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9930 length = Py_MIN(maxlen, length);
9931 if (length <= 0)
9932 return 0;
9933
Victor Stinnerd3f08822012-05-29 12:57:52 +02009934 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009935 return length;
9936}
9937
Victor Stinner9310abb2011-10-05 00:59:23 +02009938static PyObject *
9939pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009940 Py_ssize_t left,
9941 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009943{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009944 PyObject *u;
9945 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009946 int kind;
9947 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009948
9949 if (left < 0)
9950 left = 0;
9951 if (right < 0)
9952 right = 0;
9953
Victor Stinnerc4b49542011-12-11 22:44:26 +01009954 if (left == 0 && right == 0)
9955 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9958 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009959 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9960 return NULL;
9961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009963 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009965 if (!u)
9966 return NULL;
9967
9968 kind = PyUnicode_KIND(u);
9969 data = PyUnicode_DATA(u);
9970 if (left)
9971 FILL(kind, data, fill, 0, left);
9972 if (right)
9973 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009974 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009975 assert(_PyUnicode_CheckConsistency(u, 1));
9976 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009977}
9978
Alexander Belopolsky40018472011-02-26 01:02:56 +00009979PyObject *
9980PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009981{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009982 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009983
9984 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009985 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009986 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009987 if (PyUnicode_READY(string) == -1) {
9988 Py_DECREF(string);
9989 return NULL;
9990 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991
Benjamin Petersonead6b532011-12-20 17:23:42 -06009992 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009994 if (PyUnicode_IS_ASCII(string))
9995 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009996 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009997 PyUnicode_GET_LENGTH(string), keepends);
9998 else
9999 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010000 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010001 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 break;
10003 case PyUnicode_2BYTE_KIND:
10004 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010005 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 PyUnicode_GET_LENGTH(string), keepends);
10007 break;
10008 case PyUnicode_4BYTE_KIND:
10009 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010010 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 PyUnicode_GET_LENGTH(string), keepends);
10012 break;
10013 default:
10014 assert(0);
10015 list = 0;
10016 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010017 Py_DECREF(string);
10018 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010019}
10020
Alexander Belopolsky40018472011-02-26 01:02:56 +000010021static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010022split(PyObject *self,
10023 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010024 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010025{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 int kind1, kind2, kind;
10027 void *buf1, *buf2;
10028 Py_ssize_t len1, len2;
10029 PyObject* out;
10030
Guido van Rossumd57fd912000-03-10 22:53:23 +000010031 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010032 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 if (PyUnicode_READY(self) == -1)
10035 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010038 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010040 if (PyUnicode_IS_ASCII(self))
10041 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010042 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010043 PyUnicode_GET_LENGTH(self), maxcount
10044 );
10045 else
10046 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010047 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010048 PyUnicode_GET_LENGTH(self), maxcount
10049 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 case PyUnicode_2BYTE_KIND:
10051 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 PyUnicode_GET_LENGTH(self), maxcount
10054 );
10055 case PyUnicode_4BYTE_KIND:
10056 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010057 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 PyUnicode_GET_LENGTH(self), maxcount
10059 );
10060 default:
10061 assert(0);
10062 return NULL;
10063 }
10064
10065 if (PyUnicode_READY(substring) == -1)
10066 return NULL;
10067
10068 kind1 = PyUnicode_KIND(self);
10069 kind2 = PyUnicode_KIND(substring);
10070 kind = kind1 > kind2 ? kind1 : kind2;
10071 buf1 = PyUnicode_DATA(self);
10072 buf2 = PyUnicode_DATA(substring);
10073 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010074 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075 if (!buf1)
10076 return NULL;
10077 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010078 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 if (!buf2) {
10080 if (kind1 != kind) PyMem_Free(buf1);
10081 return NULL;
10082 }
10083 len1 = PyUnicode_GET_LENGTH(self);
10084 len2 = PyUnicode_GET_LENGTH(substring);
10085
Benjamin Petersonead6b532011-12-20 17:23:42 -060010086 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010088 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10089 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010090 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010091 else
10092 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010093 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 break;
10095 case PyUnicode_2BYTE_KIND:
10096 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010097 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 break;
10099 case PyUnicode_4BYTE_KIND:
10100 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010101 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 break;
10103 default:
10104 out = NULL;
10105 }
10106 if (kind1 != kind)
10107 PyMem_Free(buf1);
10108 if (kind2 != kind)
10109 PyMem_Free(buf2);
10110 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010111}
10112
Alexander Belopolsky40018472011-02-26 01:02:56 +000010113static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010114rsplit(PyObject *self,
10115 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010116 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010117{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 int kind1, kind2, kind;
10119 void *buf1, *buf2;
10120 Py_ssize_t len1, len2;
10121 PyObject* out;
10122
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010123 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010124 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 if (PyUnicode_READY(self) == -1)
10127 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010130 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010132 if (PyUnicode_IS_ASCII(self))
10133 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010134 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010135 PyUnicode_GET_LENGTH(self), maxcount
10136 );
10137 else
10138 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010139 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010140 PyUnicode_GET_LENGTH(self), maxcount
10141 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 case PyUnicode_2BYTE_KIND:
10143 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010144 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 PyUnicode_GET_LENGTH(self), maxcount
10146 );
10147 case PyUnicode_4BYTE_KIND:
10148 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010149 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 PyUnicode_GET_LENGTH(self), maxcount
10151 );
10152 default:
10153 assert(0);
10154 return NULL;
10155 }
10156
10157 if (PyUnicode_READY(substring) == -1)
10158 return NULL;
10159
10160 kind1 = PyUnicode_KIND(self);
10161 kind2 = PyUnicode_KIND(substring);
10162 kind = kind1 > kind2 ? kind1 : kind2;
10163 buf1 = PyUnicode_DATA(self);
10164 buf2 = PyUnicode_DATA(substring);
10165 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010166 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 if (!buf1)
10168 return NULL;
10169 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010170 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 if (!buf2) {
10172 if (kind1 != kind) PyMem_Free(buf1);
10173 return NULL;
10174 }
10175 len1 = PyUnicode_GET_LENGTH(self);
10176 len2 = PyUnicode_GET_LENGTH(substring);
10177
Benjamin Petersonead6b532011-12-20 17:23:42 -060010178 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010180 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10181 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010182 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 else
10184 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010185 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 break;
10187 case PyUnicode_2BYTE_KIND:
10188 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010189 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 break;
10191 case PyUnicode_4BYTE_KIND:
10192 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010193 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 break;
10195 default:
10196 out = NULL;
10197 }
10198 if (kind1 != kind)
10199 PyMem_Free(buf1);
10200 if (kind2 != kind)
10201 PyMem_Free(buf2);
10202 return out;
10203}
10204
10205static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10207 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010209 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010211 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10212 return asciilib_find(buf1, len1, buf2, len2, offset);
10213 else
10214 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 case PyUnicode_2BYTE_KIND:
10216 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10217 case PyUnicode_4BYTE_KIND:
10218 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10219 }
10220 assert(0);
10221 return -1;
10222}
10223
10224static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010225anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10226 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010228 switch (kind) {
10229 case PyUnicode_1BYTE_KIND:
10230 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10231 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10232 else
10233 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10234 case PyUnicode_2BYTE_KIND:
10235 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10236 case PyUnicode_4BYTE_KIND:
10237 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10238 }
10239 assert(0);
10240 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010241}
10242
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010243static void
10244replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10245 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10246{
10247 int kind = PyUnicode_KIND(u);
10248 void *data = PyUnicode_DATA(u);
10249 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10250 if (kind == PyUnicode_1BYTE_KIND) {
10251 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10252 (Py_UCS1 *)data + len,
10253 u1, u2, maxcount);
10254 }
10255 else if (kind == PyUnicode_2BYTE_KIND) {
10256 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10257 (Py_UCS2 *)data + len,
10258 u1, u2, maxcount);
10259 }
10260 else {
10261 assert(kind == PyUnicode_4BYTE_KIND);
10262 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10263 (Py_UCS4 *)data + len,
10264 u1, u2, maxcount);
10265 }
10266}
10267
Alexander Belopolsky40018472011-02-26 01:02:56 +000010268static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269replace(PyObject *self, PyObject *str1,
10270 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010271{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 PyObject *u;
10273 char *sbuf = PyUnicode_DATA(self);
10274 char *buf1 = PyUnicode_DATA(str1);
10275 char *buf2 = PyUnicode_DATA(str2);
10276 int srelease = 0, release1 = 0, release2 = 0;
10277 int skind = PyUnicode_KIND(self);
10278 int kind1 = PyUnicode_KIND(str1);
10279 int kind2 = PyUnicode_KIND(str2);
10280 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10281 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10282 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010283 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010284 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010285
10286 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010287 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010289 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290
Victor Stinner59de0ee2011-10-07 10:01:28 +020010291 if (str1 == str2)
10292 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293
Victor Stinner49a0a212011-10-12 23:46:10 +020010294 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010295 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10296 if (maxchar < maxchar_str1)
10297 /* substring too wide to be present */
10298 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010299 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10300 /* Replacing str1 with str2 may cause a maxchar reduction in the
10301 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010302 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010303 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010306 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010308 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010310 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010311 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010312 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010313
Victor Stinner69ed0f42013-04-09 21:48:24 +020010314 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010315 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010316 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010317 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010318 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010320 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010322
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010323 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10324 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010325 }
10326 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 int rkind = skind;
10328 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010329 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 if (kind1 < rkind) {
10332 /* widen substring */
10333 buf1 = _PyUnicode_AsKind(str1, rkind);
10334 if (!buf1) goto error;
10335 release1 = 1;
10336 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010337 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010338 if (i < 0)
10339 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 if (rkind > kind2) {
10341 /* widen replacement */
10342 buf2 = _PyUnicode_AsKind(str2, rkind);
10343 if (!buf2) goto error;
10344 release2 = 1;
10345 }
10346 else if (rkind < kind2) {
10347 /* widen self and buf1 */
10348 rkind = kind2;
10349 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010350 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 sbuf = _PyUnicode_AsKind(self, rkind);
10352 if (!sbuf) goto error;
10353 srelease = 1;
10354 buf1 = _PyUnicode_AsKind(str1, rkind);
10355 if (!buf1) goto error;
10356 release1 = 1;
10357 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010358 u = PyUnicode_New(slen, maxchar);
10359 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010361 assert(PyUnicode_KIND(u) == rkind);
10362 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010363
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010364 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010365 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010366 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010368 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010370
10371 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010373 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010374 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010375 if (i == -1)
10376 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010377 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010379 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010381 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010383 }
10384 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010386 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 int rkind = skind;
10388 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010391 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 buf1 = _PyUnicode_AsKind(str1, rkind);
10393 if (!buf1) goto error;
10394 release1 = 1;
10395 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010396 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010397 if (n == 0)
10398 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010400 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 buf2 = _PyUnicode_AsKind(str2, rkind);
10402 if (!buf2) goto error;
10403 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010404 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010406 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 rkind = kind2;
10408 sbuf = _PyUnicode_AsKind(self, rkind);
10409 if (!sbuf) goto error;
10410 srelease = 1;
10411 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010412 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 buf1 = _PyUnicode_AsKind(str1, rkind);
10414 if (!buf1) goto error;
10415 release1 = 1;
10416 }
10417 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10418 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010419 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 PyErr_SetString(PyExc_OverflowError,
10421 "replace string is too long");
10422 goto error;
10423 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010424 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010425 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010426 _Py_INCREF_UNICODE_EMPTY();
10427 if (!unicode_empty)
10428 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010429 u = unicode_empty;
10430 goto done;
10431 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010432 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 PyErr_SetString(PyExc_OverflowError,
10434 "replace string is too long");
10435 goto error;
10436 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010437 u = PyUnicode_New(new_size, maxchar);
10438 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010440 assert(PyUnicode_KIND(u) == rkind);
10441 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 ires = i = 0;
10443 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010444 while (n-- > 0) {
10445 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010446 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010447 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010448 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010449 if (j == -1)
10450 break;
10451 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010452 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010453 memcpy(res + rkind * ires,
10454 sbuf + rkind * i,
10455 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010457 }
10458 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010460 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010462 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010464 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010468 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010469 memcpy(res + rkind * ires,
10470 sbuf + rkind * i,
10471 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010472 }
10473 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010474 /* interleave */
10475 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010476 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010478 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010480 if (--n <= 0)
10481 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010482 memcpy(res + rkind * ires,
10483 sbuf + rkind * i,
10484 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 ires++;
10486 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010488 memcpy(res + rkind * ires,
10489 sbuf + rkind * i,
10490 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010491 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010492 }
10493
10494 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010495 unicode_adjust_maxchar(&u);
10496 if (u == NULL)
10497 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010498 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010499
10500 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (srelease)
10502 PyMem_FREE(sbuf);
10503 if (release1)
10504 PyMem_FREE(buf1);
10505 if (release2)
10506 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010507 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010509
Benjamin Peterson29060642009-01-31 22:14:21 +000010510 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010511 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 if (srelease)
10513 PyMem_FREE(sbuf);
10514 if (release1)
10515 PyMem_FREE(buf1);
10516 if (release2)
10517 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010518 return unicode_result_unchanged(self);
10519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 error:
10521 if (srelease && sbuf)
10522 PyMem_FREE(sbuf);
10523 if (release1 && buf1)
10524 PyMem_FREE(buf1);
10525 if (release2 && buf2)
10526 PyMem_FREE(buf2);
10527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528}
10529
10530/* --- Unicode Object Methods --------------------------------------------- */
10531
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010532PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010533 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534\n\
10535Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010536characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537
10538static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010539unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010541 if (PyUnicode_READY(self) == -1)
10542 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010543 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010544}
10545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010546PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010547 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010548\n\
10549Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010550have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010551
10552static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010553unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010554{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010555 if (PyUnicode_READY(self) == -1)
10556 return NULL;
10557 if (PyUnicode_GET_LENGTH(self) == 0)
10558 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010559 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560}
10561
Benjamin Petersond5890c82012-01-14 13:23:30 -050010562PyDoc_STRVAR(casefold__doc__,
10563 "S.casefold() -> str\n\
10564\n\
10565Return a version of S suitable for caseless comparisons.");
10566
10567static PyObject *
10568unicode_casefold(PyObject *self)
10569{
10570 if (PyUnicode_READY(self) == -1)
10571 return NULL;
10572 if (PyUnicode_IS_ASCII(self))
10573 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010574 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010575}
10576
10577
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010578/* Argument converter. Coerces to a single unicode character */
10579
10580static int
10581convert_uc(PyObject *obj, void *addr)
10582{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010584 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010585
Benjamin Peterson14339b62009-01-31 16:36:08 +000010586 uniobj = PyUnicode_FromObject(obj);
10587 if (uniobj == NULL) {
10588 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010589 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010590 return 0;
10591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010593 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010594 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010595 Py_DECREF(uniobj);
10596 return 0;
10597 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010599 Py_DECREF(uniobj);
10600 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010601}
10602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010603PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010604 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010606Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010607done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010608
10609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010610unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010612 Py_ssize_t marg, left;
10613 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 Py_UCS4 fillchar = ' ';
10615
Victor Stinnere9a29352011-10-01 02:14:59 +020010616 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618
Benjamin Petersonbac79492012-01-14 13:34:47 -050010619 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620 return NULL;
10621
Victor Stinnerc4b49542011-12-11 22:44:26 +010010622 if (PyUnicode_GET_LENGTH(self) >= width)
10623 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624
Victor Stinnerc4b49542011-12-11 22:44:26 +010010625 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626 left = marg / 2 + (marg & width & 1);
10627
Victor Stinner9310abb2011-10-05 00:59:23 +020010628 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629}
10630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631/* This function assumes that str1 and str2 are readied by the caller. */
10632
Marc-André Lemburge5034372000-08-08 08:04:29 +000010633static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010634unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010635{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010636#define COMPARE(TYPE1, TYPE2) \
10637 do { \
10638 TYPE1* p1 = (TYPE1 *)data1; \
10639 TYPE2* p2 = (TYPE2 *)data2; \
10640 TYPE1* end = p1 + len; \
10641 Py_UCS4 c1, c2; \
10642 for (; p1 != end; p1++, p2++) { \
10643 c1 = *p1; \
10644 c2 = *p2; \
10645 if (c1 != c2) \
10646 return (c1 < c2) ? -1 : 1; \
10647 } \
10648 } \
10649 while (0)
10650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 int kind1, kind2;
10652 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010653 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010654
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 kind1 = PyUnicode_KIND(str1);
10656 kind2 = PyUnicode_KIND(str2);
10657 data1 = PyUnicode_DATA(str1);
10658 data2 = PyUnicode_DATA(str2);
10659 len1 = PyUnicode_GET_LENGTH(str1);
10660 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010661 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010662
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010663 switch(kind1) {
10664 case PyUnicode_1BYTE_KIND:
10665 {
10666 switch(kind2) {
10667 case PyUnicode_1BYTE_KIND:
10668 {
10669 int cmp = memcmp(data1, data2, len);
10670 /* normalize result of memcmp() into the range [-1; 1] */
10671 if (cmp < 0)
10672 return -1;
10673 if (cmp > 0)
10674 return 1;
10675 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010676 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010677 case PyUnicode_2BYTE_KIND:
10678 COMPARE(Py_UCS1, Py_UCS2);
10679 break;
10680 case PyUnicode_4BYTE_KIND:
10681 COMPARE(Py_UCS1, Py_UCS4);
10682 break;
10683 default:
10684 assert(0);
10685 }
10686 break;
10687 }
10688 case PyUnicode_2BYTE_KIND:
10689 {
10690 switch(kind2) {
10691 case PyUnicode_1BYTE_KIND:
10692 COMPARE(Py_UCS2, Py_UCS1);
10693 break;
10694 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010695 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010696 COMPARE(Py_UCS2, Py_UCS2);
10697 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010698 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010699 case PyUnicode_4BYTE_KIND:
10700 COMPARE(Py_UCS2, Py_UCS4);
10701 break;
10702 default:
10703 assert(0);
10704 }
10705 break;
10706 }
10707 case PyUnicode_4BYTE_KIND:
10708 {
10709 switch(kind2) {
10710 case PyUnicode_1BYTE_KIND:
10711 COMPARE(Py_UCS4, Py_UCS1);
10712 break;
10713 case PyUnicode_2BYTE_KIND:
10714 COMPARE(Py_UCS4, Py_UCS2);
10715 break;
10716 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010717 {
10718#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10719 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10720 /* normalize result of wmemcmp() into the range [-1; 1] */
10721 if (cmp < 0)
10722 return -1;
10723 if (cmp > 0)
10724 return 1;
10725#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010726 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010727#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010728 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010729 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010730 default:
10731 assert(0);
10732 }
10733 break;
10734 }
10735 default:
10736 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010737 }
10738
Victor Stinner770e19e2012-10-04 22:59:45 +020010739 if (len1 == len2)
10740 return 0;
10741 if (len1 < len2)
10742 return -1;
10743 else
10744 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010745
10746#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010747}
10748
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010749Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010750unicode_compare_eq(PyObject *str1, PyObject *str2)
10751{
10752 int kind;
10753 void *data1, *data2;
10754 Py_ssize_t len;
10755 int cmp;
10756
Victor Stinnere5567ad2012-10-23 02:48:49 +020010757 len = PyUnicode_GET_LENGTH(str1);
10758 if (PyUnicode_GET_LENGTH(str2) != len)
10759 return 0;
10760 kind = PyUnicode_KIND(str1);
10761 if (PyUnicode_KIND(str2) != kind)
10762 return 0;
10763 data1 = PyUnicode_DATA(str1);
10764 data2 = PyUnicode_DATA(str2);
10765
10766 cmp = memcmp(data1, data2, len * kind);
10767 return (cmp == 0);
10768}
10769
10770
Alexander Belopolsky40018472011-02-26 01:02:56 +000010771int
10772PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10775 if (PyUnicode_READY(left) == -1 ||
10776 PyUnicode_READY(right) == -1)
10777 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010778
10779 /* a string is equal to itself */
10780 if (left == right)
10781 return 0;
10782
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010783 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010785 PyErr_Format(PyExc_TypeError,
10786 "Can't compare %.100s and %.100s",
10787 left->ob_type->tp_name,
10788 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789 return -1;
10790}
10791
Martin v. Löwis5b222132007-06-10 09:51:05 +000010792int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010793_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10794{
10795 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10796 if (right_str == NULL)
10797 return -1;
10798 return PyUnicode_Compare(left, right_str);
10799}
10800
10801int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010802PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10803{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 Py_ssize_t i;
10805 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 Py_UCS4 chr;
10807
Victor Stinner910337b2011-10-03 03:20:16 +020010808 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 if (PyUnicode_READY(uni) == -1)
10810 return -1;
10811 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010812 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010813 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010814 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010815 size_t len, len2 = strlen(str);
10816 int cmp;
10817
10818 len = Py_MIN(len1, len2);
10819 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010820 if (cmp != 0) {
10821 if (cmp < 0)
10822 return -1;
10823 else
10824 return 1;
10825 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010826 if (len1 > len2)
10827 return 1; /* uni is longer */
10828 if (len2 > len1)
10829 return -1; /* str is longer */
10830 return 0;
10831 }
10832 else {
10833 void *data = PyUnicode_DATA(uni);
10834 /* Compare Unicode string and source character set string */
10835 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10836 if (chr != str[i])
10837 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10838 /* This check keeps Python strings that end in '\0' from comparing equal
10839 to C strings identical up to that point. */
10840 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10841 return 1; /* uni is longer */
10842 if (str[i])
10843 return -1; /* str is longer */
10844 return 0;
10845 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010846}
10847
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010848
Benjamin Peterson29060642009-01-31 22:14:21 +000010849#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010850 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010851
Alexander Belopolsky40018472011-02-26 01:02:56 +000010852PyObject *
10853PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010854{
10855 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010856 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010857
Victor Stinnere5567ad2012-10-23 02:48:49 +020010858 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10859 Py_RETURN_NOTIMPLEMENTED;
10860
10861 if (PyUnicode_READY(left) == -1 ||
10862 PyUnicode_READY(right) == -1)
10863 return NULL;
10864
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010865 if (left == right) {
10866 switch (op) {
10867 case Py_EQ:
10868 case Py_LE:
10869 case Py_GE:
10870 /* a string is equal to itself */
10871 v = Py_True;
10872 break;
10873 case Py_NE:
10874 case Py_LT:
10875 case Py_GT:
10876 v = Py_False;
10877 break;
10878 default:
10879 PyErr_BadArgument();
10880 return NULL;
10881 }
10882 }
10883 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010884 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010885 result ^= (op == Py_NE);
10886 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010887 }
10888 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010889 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010890
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010891 /* Convert the return value to a Boolean */
10892 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010893 case Py_LE:
10894 v = TEST_COND(result <= 0);
10895 break;
10896 case Py_GE:
10897 v = TEST_COND(result >= 0);
10898 break;
10899 case Py_LT:
10900 v = TEST_COND(result == -1);
10901 break;
10902 case Py_GT:
10903 v = TEST_COND(result == 1);
10904 break;
10905 default:
10906 PyErr_BadArgument();
10907 return NULL;
10908 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010909 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010910 Py_INCREF(v);
10911 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010912}
10913
Alexander Belopolsky40018472011-02-26 01:02:56 +000010914int
10915PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010916{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010917 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010918 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919 void *buf1, *buf2;
10920 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010921 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010922
10923 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010924 sub = PyUnicode_FromObject(element);
10925 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010926 PyErr_Format(PyExc_TypeError,
10927 "'in <string>' requires string as left operand, not %s",
10928 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010929 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010930 }
10931
Thomas Wouters477c8d52006-05-27 19:21:47 +000010932 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010933 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010934 Py_DECREF(sub);
10935 return -1;
10936 }
10937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 kind1 = PyUnicode_KIND(str);
10939 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010940 buf1 = PyUnicode_DATA(str);
10941 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010942 if (kind2 != kind1) {
10943 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010944 Py_DECREF(sub);
10945 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010946 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010947 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010948 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 if (!buf2) {
10951 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010952 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953 return -1;
10954 }
10955 len1 = PyUnicode_GET_LENGTH(str);
10956 len2 = PyUnicode_GET_LENGTH(sub);
10957
Victor Stinner77282cb2013-04-14 19:22:47 +020010958 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010959 case PyUnicode_1BYTE_KIND:
10960 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10961 break;
10962 case PyUnicode_2BYTE_KIND:
10963 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10964 break;
10965 case PyUnicode_4BYTE_KIND:
10966 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10967 break;
10968 default:
10969 result = -1;
10970 assert(0);
10971 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010972
10973 Py_DECREF(str);
10974 Py_DECREF(sub);
10975
Victor Stinner77282cb2013-04-14 19:22:47 +020010976 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010977 PyMem_Free(buf2);
10978
Guido van Rossum403d68b2000-03-13 15:55:09 +000010979 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010980}
10981
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982/* Concat to string or Unicode object giving a new Unicode object. */
10983
Alexander Belopolsky40018472011-02-26 01:02:56 +000010984PyObject *
10985PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010988 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010989 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990
10991 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010992 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010994 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010995 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010997 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998
10999 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011000 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011001 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011002 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011004 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011005 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011006 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007 }
11008
Victor Stinner488fa492011-12-12 00:01:39 +010011009 u_len = PyUnicode_GET_LENGTH(u);
11010 v_len = PyUnicode_GET_LENGTH(v);
11011 if (u_len > PY_SSIZE_T_MAX - v_len) {
11012 PyErr_SetString(PyExc_OverflowError,
11013 "strings are too large to concat");
11014 goto onError;
11015 }
11016 new_len = u_len + v_len;
11017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011019 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011020 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011023 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011026 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11027 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028 Py_DECREF(u);
11029 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011030 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011031 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032
Benjamin Peterson29060642009-01-31 22:14:21 +000011033 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034 Py_XDECREF(u);
11035 Py_XDECREF(v);
11036 return NULL;
11037}
11038
Walter Dörwald1ab83302007-05-18 17:15:44 +000011039void
Victor Stinner23e56682011-10-03 03:54:37 +020011040PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011041{
Victor Stinner23e56682011-10-03 03:54:37 +020011042 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011043 Py_UCS4 maxchar, maxchar2;
11044 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011045
11046 if (p_left == NULL) {
11047 if (!PyErr_Occurred())
11048 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011049 return;
11050 }
Victor Stinner23e56682011-10-03 03:54:37 +020011051 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011052 if (right == NULL || left == NULL
11053 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011054 if (!PyErr_Occurred())
11055 PyErr_BadInternalCall();
11056 goto error;
11057 }
11058
Benjamin Petersonbac79492012-01-14 13:34:47 -050011059 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011060 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011061 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011062 goto error;
11063
Victor Stinner488fa492011-12-12 00:01:39 +010011064 /* Shortcuts */
11065 if (left == unicode_empty) {
11066 Py_DECREF(left);
11067 Py_INCREF(right);
11068 *p_left = right;
11069 return;
11070 }
11071 if (right == unicode_empty)
11072 return;
11073
11074 left_len = PyUnicode_GET_LENGTH(left);
11075 right_len = PyUnicode_GET_LENGTH(right);
11076 if (left_len > PY_SSIZE_T_MAX - right_len) {
11077 PyErr_SetString(PyExc_OverflowError,
11078 "strings are too large to concat");
11079 goto error;
11080 }
11081 new_len = left_len + right_len;
11082
11083 if (unicode_modifiable(left)
11084 && PyUnicode_CheckExact(right)
11085 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011086 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11087 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011088 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011089 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011090 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11091 {
11092 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011093 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011094 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011095
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011096 /* copy 'right' into the newly allocated area of 'left' */
11097 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011098 }
Victor Stinner488fa492011-12-12 00:01:39 +010011099 else {
11100 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11101 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011102 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011103
Victor Stinner488fa492011-12-12 00:01:39 +010011104 /* Concat the two Unicode strings */
11105 res = PyUnicode_New(new_len, maxchar);
11106 if (res == NULL)
11107 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011108 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11109 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011110 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011111 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011112 }
11113 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011114 return;
11115
11116error:
Victor Stinner488fa492011-12-12 00:01:39 +010011117 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011118}
11119
11120void
11121PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11122{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011123 PyUnicode_Append(pleft, right);
11124 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011125}
11126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011127PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011131string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011132interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133
11134static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011135unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011137 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011138 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011139 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 int kind1, kind2, kind;
11142 void *buf1, *buf2;
11143 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Jesus Ceaac451502011-04-20 17:09:23 +020011145 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11146 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011147 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 kind1 = PyUnicode_KIND(self);
11150 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011151 if (kind2 > kind1) {
11152 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011153 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011154 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011155 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 buf1 = PyUnicode_DATA(self);
11157 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011159 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 if (!buf2) {
11161 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 return NULL;
11163 }
11164 len1 = PyUnicode_GET_LENGTH(self);
11165 len2 = PyUnicode_GET_LENGTH(substring);
11166
11167 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011168 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 case PyUnicode_1BYTE_KIND:
11170 iresult = ucs1lib_count(
11171 ((Py_UCS1*)buf1) + start, end - start,
11172 buf2, len2, PY_SSIZE_T_MAX
11173 );
11174 break;
11175 case PyUnicode_2BYTE_KIND:
11176 iresult = ucs2lib_count(
11177 ((Py_UCS2*)buf1) + start, end - start,
11178 buf2, len2, PY_SSIZE_T_MAX
11179 );
11180 break;
11181 case PyUnicode_4BYTE_KIND:
11182 iresult = ucs4lib_count(
11183 ((Py_UCS4*)buf1) + start, end - start,
11184 buf2, len2, PY_SSIZE_T_MAX
11185 );
11186 break;
11187 default:
11188 assert(0); iresult = 0;
11189 }
11190
11191 result = PyLong_FromSsize_t(iresult);
11192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 if (kind2 != kind)
11194 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
11196 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011197
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198 return result;
11199}
11200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011201PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011202 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011204Encode S using the codec registered for encoding. Default encoding\n\
11205is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011206handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011207a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11208'xmlcharrefreplace' as well as any other name registered with\n\
11209codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
11211static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011212unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011214 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215 char *encoding = NULL;
11216 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011217
Benjamin Peterson308d6372009-09-18 21:42:35 +000011218 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11219 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011221 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011222}
11223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011224PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011225 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226\n\
11227Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011228If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229
11230static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011231unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011233 Py_ssize_t i, j, line_pos, src_len, incr;
11234 Py_UCS4 ch;
11235 PyObject *u;
11236 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011237 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011239 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011240 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241
Ezio Melotti745d54d2013-11-16 19:10:57 +020011242 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11243 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011244 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245
Antoine Pitrou22425222011-10-04 19:10:51 +020011246 if (PyUnicode_READY(self) == -1)
11247 return NULL;
11248
Thomas Wouters7e474022000-07-16 12:04:32 +000011249 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011250 src_len = PyUnicode_GET_LENGTH(self);
11251 i = j = line_pos = 0;
11252 kind = PyUnicode_KIND(self);
11253 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011254 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011255 for (; i < src_len; i++) {
11256 ch = PyUnicode_READ(kind, src_data, i);
11257 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011258 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011261 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011262 goto overflow;
11263 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011264 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011265 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011269 goto overflow;
11270 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011272 if (ch == '\n' || ch == '\r')
11273 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011275 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011276 if (!found)
11277 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011278
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011280 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 if (!u)
11282 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011283 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284
Antoine Pitroue71d5742011-10-04 15:55:09 +020011285 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286
Antoine Pitroue71d5742011-10-04 15:55:09 +020011287 for (; i < src_len; i++) {
11288 ch = PyUnicode_READ(kind, src_data, i);
11289 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011291 incr = tabsize - (line_pos % tabsize);
11292 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011293 FILL(kind, dest_data, ' ', j, incr);
11294 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011296 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011297 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011298 line_pos++;
11299 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011300 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011301 if (ch == '\n' || ch == '\r')
11302 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011304 }
11305 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011306 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011307
Antoine Pitroue71d5742011-10-04 15:55:09 +020011308 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011309 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11310 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311}
11312
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011313PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011314 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315\n\
11316Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011317such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318arguments start and end are interpreted as in slice notation.\n\
11319\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011320Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321
11322static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011325 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011326 Py_ssize_t start;
11327 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011328 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329
Jesus Ceaac451502011-04-20 17:09:23 +020011330 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11331 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333
Christian Heimesd47802e2013-06-29 21:33:36 +020011334 if (PyUnicode_READY(self) == -1) {
11335 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011337 }
11338 if (PyUnicode_READY(substring) == -1) {
11339 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011341 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011342
Victor Stinner7931d9a2011-11-04 00:22:48 +010011343 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344
11345 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 if (result == -2)
11348 return NULL;
11349
Christian Heimes217cfd12007-12-02 14:31:20 +000011350 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351}
11352
11353static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011354unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011356 void *data;
11357 enum PyUnicode_Kind kind;
11358 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011359
11360 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11361 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011363 }
11364 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11365 PyErr_SetString(PyExc_IndexError, "string index out of range");
11366 return NULL;
11367 }
11368 kind = PyUnicode_KIND(self);
11369 data = PyUnicode_DATA(self);
11370 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011371 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011372}
11373
Guido van Rossumc2504932007-09-18 19:42:40 +000011374/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011375 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011376static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011377unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378{
Guido van Rossumc2504932007-09-18 19:42:40 +000011379 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011380 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011381
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011382#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011383 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011384#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 if (_PyUnicode_HASH(self) != -1)
11386 return _PyUnicode_HASH(self);
11387 if (PyUnicode_READY(self) == -1)
11388 return -1;
11389 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011390 /*
11391 We make the hash of the empty string be 0, rather than using
11392 (prefix ^ suffix), since this slightly obfuscates the hash secret
11393 */
11394 if (len == 0) {
11395 _PyUnicode_HASH(self) = 0;
11396 return 0;
11397 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011398 x = _Py_HashBytes(PyUnicode_DATA(self),
11399 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011400 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011401 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402}
11403
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011404PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011405 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
11409static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011412 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011413 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011414 Py_ssize_t start;
11415 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
Jesus Ceaac451502011-04-20 17:09:23 +020011417 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11418 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
Christian Heimesd47a0452013-06-29 21:21:37 +020011421 if (PyUnicode_READY(self) == -1) {
11422 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011424 }
11425 if (PyUnicode_READY(substring) == -1) {
11426 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011428 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429
Victor Stinner7931d9a2011-11-04 00:22:48 +010011430 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
11432 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 if (result == -2)
11435 return NULL;
11436
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 if (result < 0) {
11438 PyErr_SetString(PyExc_ValueError, "substring not found");
11439 return NULL;
11440 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011441
Christian Heimes217cfd12007-12-02 14:31:20 +000011442 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443}
11444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011445PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011448Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011449at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450
11451static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011452unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 Py_ssize_t i, length;
11455 int kind;
11456 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 int cased;
11458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (PyUnicode_READY(self) == -1)
11460 return NULL;
11461 length = PyUnicode_GET_LENGTH(self);
11462 kind = PyUnicode_KIND(self);
11463 data = PyUnicode_DATA(self);
11464
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 if (length == 1)
11467 return PyBool_FromLong(
11468 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011470 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 for (i = 0; i < length; i++) {
11476 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011477
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11479 return PyBool_FromLong(0);
11480 else if (!cased && Py_UNICODE_ISLOWER(ch))
11481 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011483 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484}
11485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011486PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011489Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011490at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491
11492static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011493unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 Py_ssize_t i, length;
11496 int kind;
11497 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 int cased;
11499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (PyUnicode_READY(self) == -1)
11501 return NULL;
11502 length = PyUnicode_GET_LENGTH(self);
11503 kind = PyUnicode_KIND(self);
11504 data = PyUnicode_DATA(self);
11505
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 if (length == 1)
11508 return PyBool_FromLong(
11509 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011511 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011514
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 for (i = 0; i < length; i++) {
11517 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011518
Benjamin Peterson29060642009-01-31 22:14:21 +000011519 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11520 return PyBool_FromLong(0);
11521 else if (!cased && Py_UNICODE_ISUPPER(ch))
11522 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011524 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525}
11526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011527PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011530Return True if S is a titlecased string and there is at least one\n\
11531character in S, i.e. upper- and titlecase characters may only\n\
11532follow uncased characters and lowercase characters only cased ones.\n\
11533Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534
11535static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011536unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 Py_ssize_t i, length;
11539 int kind;
11540 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 int cased, previous_is_cased;
11542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011543 if (PyUnicode_READY(self) == -1)
11544 return NULL;
11545 length = PyUnicode_GET_LENGTH(self);
11546 kind = PyUnicode_KIND(self);
11547 data = PyUnicode_DATA(self);
11548
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (length == 1) {
11551 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11552 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11553 (Py_UNICODE_ISUPPER(ch) != 0));
11554 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011556 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011559
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 cased = 0;
11561 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 for (i = 0; i < length; i++) {
11563 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011564
Benjamin Peterson29060642009-01-31 22:14:21 +000011565 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11566 if (previous_is_cased)
11567 return PyBool_FromLong(0);
11568 previous_is_cased = 1;
11569 cased = 1;
11570 }
11571 else if (Py_UNICODE_ISLOWER(ch)) {
11572 if (!previous_is_cased)
11573 return PyBool_FromLong(0);
11574 previous_is_cased = 1;
11575 cased = 1;
11576 }
11577 else
11578 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011580 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581}
11582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011583PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011586Return True if all characters in S are whitespace\n\
11587and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
11589static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011590unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011592 Py_ssize_t i, length;
11593 int kind;
11594 void *data;
11595
11596 if (PyUnicode_READY(self) == -1)
11597 return NULL;
11598 length = PyUnicode_GET_LENGTH(self);
11599 kind = PyUnicode_KIND(self);
11600 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 if (length == 1)
11604 return PyBool_FromLong(
11605 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011607 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011611 for (i = 0; i < length; i++) {
11612 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011613 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011616 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617}
11618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011619PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011621\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011622Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011623and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011624
11625static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011626unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011627{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 Py_ssize_t i, length;
11629 int kind;
11630 void *data;
11631
11632 if (PyUnicode_READY(self) == -1)
11633 return NULL;
11634 length = PyUnicode_GET_LENGTH(self);
11635 kind = PyUnicode_KIND(self);
11636 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011637
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011638 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 if (length == 1)
11640 return PyBool_FromLong(
11641 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011642
11643 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011645 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 for (i = 0; i < length; i++) {
11648 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011650 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011651 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652}
11653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011654PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011656\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011657Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011658and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011659
11660static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011661unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 int kind;
11664 void *data;
11665 Py_ssize_t len, i;
11666
11667 if (PyUnicode_READY(self) == -1)
11668 return NULL;
11669
11670 kind = PyUnicode_KIND(self);
11671 data = PyUnicode_DATA(self);
11672 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011673
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011674 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 if (len == 1) {
11676 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11677 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11678 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011679
11680 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011683
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 for (i = 0; i < len; i++) {
11685 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011686 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011689 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011690}
11691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011692PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011693 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011695Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011696False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697
11698static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011699unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 Py_ssize_t i, length;
11702 int kind;
11703 void *data;
11704
11705 if (PyUnicode_READY(self) == -1)
11706 return NULL;
11707 length = PyUnicode_GET_LENGTH(self);
11708 kind = PyUnicode_KIND(self);
11709 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 if (length == 1)
11713 return PyBool_FromLong(
11714 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011716 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011718 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 for (i = 0; i < length; i++) {
11721 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011722 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011724 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725}
11726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011727PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011730Return True if all characters in S are digits\n\
11731and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
11733static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011734unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 Py_ssize_t i, length;
11737 int kind;
11738 void *data;
11739
11740 if (PyUnicode_READY(self) == -1)
11741 return NULL;
11742 length = PyUnicode_GET_LENGTH(self);
11743 kind = PyUnicode_KIND(self);
11744 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747 if (length == 1) {
11748 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11749 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11750 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011752 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011754 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 for (i = 0; i < length; i++) {
11757 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011758 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011760 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761}
11762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011763PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011766Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011767False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
11769static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011770unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 Py_ssize_t i, length;
11773 int kind;
11774 void *data;
11775
11776 if (PyUnicode_READY(self) == -1)
11777 return NULL;
11778 length = PyUnicode_GET_LENGTH(self);
11779 kind = PyUnicode_KIND(self);
11780 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011783 if (length == 1)
11784 return PyBool_FromLong(
11785 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011787 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011788 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 for (i = 0; i < length; i++) {
11792 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011793 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011795 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796}
11797
Martin v. Löwis47383402007-08-15 07:32:56 +000011798int
11799PyUnicode_IsIdentifier(PyObject *self)
11800{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 int kind;
11802 void *data;
11803 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011804 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (PyUnicode_READY(self) == -1) {
11807 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011808 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011809 }
11810
11811 /* Special case for empty strings */
11812 if (PyUnicode_GET_LENGTH(self) == 0)
11813 return 0;
11814 kind = PyUnicode_KIND(self);
11815 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011816
11817 /* PEP 3131 says that the first character must be in
11818 XID_Start and subsequent characters in XID_Continue,
11819 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011820 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011821 letters, digits, underscore). However, given the current
11822 definition of XID_Start and XID_Continue, it is sufficient
11823 to check just for these, except that _ must be allowed
11824 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011826 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011827 return 0;
11828
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011829 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011831 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011832 return 1;
11833}
11834
11835PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011836 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011837\n\
11838Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011839to the language definition.\n\
11840\n\
11841Use keyword.iskeyword() to test for reserved identifiers\n\
11842such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011843
11844static PyObject*
11845unicode_isidentifier(PyObject *self)
11846{
11847 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11848}
11849
Georg Brandl559e5d72008-06-11 18:37:52 +000011850PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011851 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011852\n\
11853Return True if all characters in S are considered\n\
11854printable in repr() or S is empty, False otherwise.");
11855
11856static PyObject*
11857unicode_isprintable(PyObject *self)
11858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 Py_ssize_t i, length;
11860 int kind;
11861 void *data;
11862
11863 if (PyUnicode_READY(self) == -1)
11864 return NULL;
11865 length = PyUnicode_GET_LENGTH(self);
11866 kind = PyUnicode_KIND(self);
11867 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011868
11869 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 if (length == 1)
11871 return PyBool_FromLong(
11872 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 for (i = 0; i < length; i++) {
11875 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011876 Py_RETURN_FALSE;
11877 }
11878 }
11879 Py_RETURN_TRUE;
11880}
11881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011882PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011883 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884\n\
11885Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011886iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
11888static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011889unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011891 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892}
11893
Martin v. Löwis18e16552006-02-15 17:27:45 +000011894static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011895unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 if (PyUnicode_READY(self) == -1)
11898 return -1;
11899 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900}
11901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011902PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011903 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011905Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011906done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907
11908static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011909unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011911 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 Py_UCS4 fillchar = ' ';
11913
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011914 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915 return NULL;
11916
Benjamin Petersonbac79492012-01-14 13:34:47 -050011917 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011918 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919
Victor Stinnerc4b49542011-12-11 22:44:26 +010011920 if (PyUnicode_GET_LENGTH(self) >= width)
11921 return unicode_result_unchanged(self);
11922
11923 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924}
11925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011926PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011927 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011929Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930
11931static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011932unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011934 if (PyUnicode_READY(self) == -1)
11935 return NULL;
11936 if (PyUnicode_IS_ASCII(self))
11937 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011938 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939}
11940
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011941#define LEFTSTRIP 0
11942#define RIGHTSTRIP 1
11943#define BOTHSTRIP 2
11944
11945/* Arrays indexed by above */
11946static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11947
11948#define STRIPNAME(i) (stripformat[i]+3)
11949
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011950/* externally visible for str.strip(unicode) */
11951PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011952_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 void *data;
11955 int kind;
11956 Py_ssize_t i, j, len;
11957 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011958 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11961 return NULL;
11962
11963 kind = PyUnicode_KIND(self);
11964 data = PyUnicode_DATA(self);
11965 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011966 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11968 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011969 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011970
Benjamin Peterson14339b62009-01-31 16:36:08 +000011971 i = 0;
11972 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011973 while (i < len) {
11974 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11975 if (!BLOOM(sepmask, ch))
11976 break;
11977 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11978 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 i++;
11980 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011981 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011982
Benjamin Peterson14339b62009-01-31 16:36:08 +000011983 j = len;
11984 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011985 j--;
11986 while (j >= i) {
11987 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11988 if (!BLOOM(sepmask, ch))
11989 break;
11990 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11991 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011992 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011993 }
11994
Benjamin Peterson29060642009-01-31 22:14:21 +000011995 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011996 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011997
Victor Stinner7931d9a2011-11-04 00:22:48 +010011998 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999}
12000
12001PyObject*
12002PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12003{
12004 unsigned char *data;
12005 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012006 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007
Victor Stinnerde636f32011-10-01 03:55:54 +020012008 if (PyUnicode_READY(self) == -1)
12009 return NULL;
12010
Victor Stinner684d5fd2012-05-03 02:32:34 +020012011 length = PyUnicode_GET_LENGTH(self);
12012 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012013
Victor Stinner684d5fd2012-05-03 02:32:34 +020012014 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012015 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016
Victor Stinnerde636f32011-10-01 03:55:54 +020012017 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012018 PyErr_SetString(PyExc_IndexError, "string index out of range");
12019 return NULL;
12020 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012021 if (start >= length || end < start)
12022 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012023
Victor Stinner684d5fd2012-05-03 02:32:34 +020012024 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012025 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012026 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012027 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012028 }
12029 else {
12030 kind = PyUnicode_KIND(self);
12031 data = PyUnicode_1BYTE_DATA(self);
12032 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012033 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012034 length);
12035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037
12038static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012039do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 Py_ssize_t len, i, j;
12042
12043 if (PyUnicode_READY(self) == -1)
12044 return NULL;
12045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012047
Victor Stinnercc7af722013-04-09 22:39:24 +020012048 if (PyUnicode_IS_ASCII(self)) {
12049 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12050
12051 i = 0;
12052 if (striptype != RIGHTSTRIP) {
12053 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012054 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012055 if (!_Py_ascii_whitespace[ch])
12056 break;
12057 i++;
12058 }
12059 }
12060
12061 j = len;
12062 if (striptype != LEFTSTRIP) {
12063 j--;
12064 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012065 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012066 if (!_Py_ascii_whitespace[ch])
12067 break;
12068 j--;
12069 }
12070 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012071 }
12072 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012073 else {
12074 int kind = PyUnicode_KIND(self);
12075 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012076
Victor Stinnercc7af722013-04-09 22:39:24 +020012077 i = 0;
12078 if (striptype != RIGHTSTRIP) {
12079 while (i < len) {
12080 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12081 if (!Py_UNICODE_ISSPACE(ch))
12082 break;
12083 i++;
12084 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012085 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012086
12087 j = len;
12088 if (striptype != LEFTSTRIP) {
12089 j--;
12090 while (j >= i) {
12091 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12092 if (!Py_UNICODE_ISSPACE(ch))
12093 break;
12094 j--;
12095 }
12096 j++;
12097 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012098 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012099
Victor Stinner7931d9a2011-11-04 00:22:48 +010012100 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101}
12102
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012103
12104static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012105do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012106{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012107 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012108
Serhiy Storchakac6792272013-10-19 21:03:34 +030012109 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012110 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012111
Benjamin Peterson14339b62009-01-31 16:36:08 +000012112 if (sep != NULL && sep != Py_None) {
12113 if (PyUnicode_Check(sep))
12114 return _PyUnicode_XStrip(self, striptype, sep);
12115 else {
12116 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012117 "%s arg must be None or str",
12118 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012119 return NULL;
12120 }
12121 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122
Benjamin Peterson14339b62009-01-31 16:36:08 +000012123 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012124}
12125
12126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012127PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012128 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012129\n\
12130Return a copy of the string S with leading and trailing\n\
12131whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012132If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133
12134static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012135unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012137 if (PyTuple_GET_SIZE(args) == 0)
12138 return do_strip(self, BOTHSTRIP); /* Common case */
12139 else
12140 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141}
12142
12143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012144PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012145 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012146\n\
12147Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012148If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012149
12150static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012151unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012152{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012153 if (PyTuple_GET_SIZE(args) == 0)
12154 return do_strip(self, LEFTSTRIP); /* Common case */
12155 else
12156 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012157}
12158
12159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012160PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012161 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012162\n\
12163Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012164If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012165
12166static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012167unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012168{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012169 if (PyTuple_GET_SIZE(args) == 0)
12170 return do_strip(self, RIGHTSTRIP); /* Common case */
12171 else
12172 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012173}
12174
12175
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012177unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012179 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
Serhiy Storchaka05997252013-01-26 12:14:02 +020012182 if (len < 1)
12183 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184
Victor Stinnerc4b49542011-12-11 22:44:26 +010012185 /* no repeat, return original string */
12186 if (len == 1)
12187 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012188
Benjamin Petersonbac79492012-01-14 13:34:47 -050012189 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 return NULL;
12191
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012192 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012193 PyErr_SetString(PyExc_OverflowError,
12194 "repeated string is too long");
12195 return NULL;
12196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012197 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012198
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012199 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200 if (!u)
12201 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012202 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 if (PyUnicode_GET_LENGTH(str) == 1) {
12205 const int kind = PyUnicode_KIND(str);
12206 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012207 if (kind == PyUnicode_1BYTE_KIND) {
12208 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012209 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012210 }
12211 else if (kind == PyUnicode_2BYTE_KIND) {
12212 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012213 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012214 ucs2[n] = fill_char;
12215 } else {
12216 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12217 assert(kind == PyUnicode_4BYTE_KIND);
12218 for (n = 0; n < len; ++n)
12219 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 }
12222 else {
12223 /* number of characters copied this far */
12224 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012225 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 char *to = (char *) PyUnicode_DATA(u);
12227 Py_MEMCPY(to, PyUnicode_DATA(str),
12228 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012229 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 n = (done <= nchars-done) ? done : nchars-done;
12231 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012232 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012233 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234 }
12235
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012236 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012237 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238}
12239
Alexander Belopolsky40018472011-02-26 01:02:56 +000012240PyObject *
12241PyUnicode_Replace(PyObject *obj,
12242 PyObject *subobj,
12243 PyObject *replobj,
12244 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245{
12246 PyObject *self;
12247 PyObject *str1;
12248 PyObject *str2;
12249 PyObject *result;
12250
12251 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012252 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012253 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012255 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012256 Py_DECREF(self);
12257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258 }
12259 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012260 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012261 Py_DECREF(self);
12262 Py_DECREF(str1);
12263 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012265 if (PyUnicode_READY(self) == -1 ||
12266 PyUnicode_READY(str1) == -1 ||
12267 PyUnicode_READY(str2) == -1)
12268 result = NULL;
12269 else
12270 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271 Py_DECREF(self);
12272 Py_DECREF(str1);
12273 Py_DECREF(str2);
12274 return result;
12275}
12276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012277PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012278 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279\n\
12280Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012281old replaced by new. If the optional argument count is\n\
12282given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283
12284static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287 PyObject *str1;
12288 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012289 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 PyObject *result;
12291
Martin v. Löwis18e16552006-02-15 17:27:45 +000012292 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012294 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012295 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012297 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 return NULL;
12299 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012300 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012301 Py_DECREF(str1);
12302 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012303 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012304 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12305 result = NULL;
12306 else
12307 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308
12309 Py_DECREF(str1);
12310 Py_DECREF(str2);
12311 return result;
12312}
12313
Alexander Belopolsky40018472011-02-26 01:02:56 +000012314static PyObject *
12315unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012317 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 Py_ssize_t isize;
12319 Py_ssize_t osize, squote, dquote, i, o;
12320 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012321 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012325 return NULL;
12326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 isize = PyUnicode_GET_LENGTH(unicode);
12328 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 /* Compute length of output, quote characters, and
12331 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012332 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 max = 127;
12334 squote = dquote = 0;
12335 ikind = PyUnicode_KIND(unicode);
12336 for (i = 0; i < isize; i++) {
12337 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12338 switch (ch) {
12339 case '\'': squote++; osize++; break;
12340 case '"': dquote++; osize++; break;
12341 case '\\': case '\t': case '\r': case '\n':
12342 osize += 2; break;
12343 default:
12344 /* Fast-path ASCII */
12345 if (ch < ' ' || ch == 0x7f)
12346 osize += 4; /* \xHH */
12347 else if (ch < 0x7f)
12348 osize++;
12349 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12350 osize++;
12351 max = ch > max ? ch : max;
12352 }
12353 else if (ch < 0x100)
12354 osize += 4; /* \xHH */
12355 else if (ch < 0x10000)
12356 osize += 6; /* \uHHHH */
12357 else
12358 osize += 10; /* \uHHHHHHHH */
12359 }
12360 }
12361
12362 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012363 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012365 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 if (dquote)
12367 /* Both squote and dquote present. Use squote,
12368 and escape them */
12369 osize += squote;
12370 else
12371 quote = '"';
12372 }
Victor Stinner55c08782013-04-14 18:45:39 +020012373 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374
12375 repr = PyUnicode_New(osize, max);
12376 if (repr == NULL)
12377 return NULL;
12378 okind = PyUnicode_KIND(repr);
12379 odata = PyUnicode_DATA(repr);
12380
12381 PyUnicode_WRITE(okind, odata, 0, quote);
12382 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012383 if (unchanged) {
12384 _PyUnicode_FastCopyCharacters(repr, 1,
12385 unicode, 0,
12386 isize);
12387 }
12388 else {
12389 for (i = 0, o = 1; i < isize; i++) {
12390 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391
Victor Stinner55c08782013-04-14 18:45:39 +020012392 /* Escape quotes and backslashes */
12393 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012394 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012396 continue;
12397 }
12398
12399 /* Map special whitespace to '\t', \n', '\r' */
12400 if (ch == '\t') {
12401 PyUnicode_WRITE(okind, odata, o++, '\\');
12402 PyUnicode_WRITE(okind, odata, o++, 't');
12403 }
12404 else if (ch == '\n') {
12405 PyUnicode_WRITE(okind, odata, o++, '\\');
12406 PyUnicode_WRITE(okind, odata, o++, 'n');
12407 }
12408 else if (ch == '\r') {
12409 PyUnicode_WRITE(okind, odata, o++, '\\');
12410 PyUnicode_WRITE(okind, odata, o++, 'r');
12411 }
12412
12413 /* Map non-printable US ASCII to '\xhh' */
12414 else if (ch < ' ' || ch == 0x7F) {
12415 PyUnicode_WRITE(okind, odata, o++, '\\');
12416 PyUnicode_WRITE(okind, odata, o++, 'x');
12417 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12418 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12419 }
12420
12421 /* Copy ASCII characters as-is */
12422 else if (ch < 0x7F) {
12423 PyUnicode_WRITE(okind, odata, o++, ch);
12424 }
12425
12426 /* Non-ASCII characters */
12427 else {
12428 /* Map Unicode whitespace and control characters
12429 (categories Z* and C* except ASCII space)
12430 */
12431 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12432 PyUnicode_WRITE(okind, odata, o++, '\\');
12433 /* Map 8-bit characters to '\xhh' */
12434 if (ch <= 0xff) {
12435 PyUnicode_WRITE(okind, odata, o++, 'x');
12436 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12437 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12438 }
12439 /* Map 16-bit characters to '\uxxxx' */
12440 else if (ch <= 0xffff) {
12441 PyUnicode_WRITE(okind, odata, o++, 'u');
12442 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12443 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12444 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12445 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12446 }
12447 /* Map 21-bit characters to '\U00xxxxxx' */
12448 else {
12449 PyUnicode_WRITE(okind, odata, o++, 'U');
12450 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12451 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12452 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12453 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12454 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12455 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12456 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12457 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12458 }
12459 }
12460 /* Copy characters as-is */
12461 else {
12462 PyUnicode_WRITE(okind, odata, o++, ch);
12463 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012464 }
12465 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012467 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012468 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012469 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470}
12471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012472PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012473 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474\n\
12475Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012476such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012477arguments start and end are interpreted as in slice notation.\n\
12478\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012479Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012480
12481static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012484 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012485 Py_ssize_t start;
12486 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012487 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488
Jesus Ceaac451502011-04-20 17:09:23 +020012489 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12490 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012491 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492
Christian Heimesea71a522013-06-29 21:17:34 +020012493 if (PyUnicode_READY(self) == -1) {
12494 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012496 }
12497 if (PyUnicode_READY(substring) == -1) {
12498 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012499 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012500 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012501
Victor Stinner7931d9a2011-11-04 00:22:48 +010012502 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
12504 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 if (result == -2)
12507 return NULL;
12508
Christian Heimes217cfd12007-12-02 14:31:20 +000012509 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510}
12511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012512PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012513 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012515Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516
12517static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012518unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012520 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012521 Py_ssize_t start;
12522 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012523 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524
Jesus Ceaac451502011-04-20 17:09:23 +020012525 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12526 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528
Christian Heimesea71a522013-06-29 21:17:34 +020012529 if (PyUnicode_READY(self) == -1) {
12530 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012531 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012532 }
12533 if (PyUnicode_READY(substring) == -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 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537
Victor Stinner7931d9a2011-11-04 00:22:48 +010012538 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539
12540 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 if (result == -2)
12543 return NULL;
12544
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545 if (result < 0) {
12546 PyErr_SetString(PyExc_ValueError, "substring not found");
12547 return NULL;
12548 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549
Christian Heimes217cfd12007-12-02 14:31:20 +000012550 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551}
12552
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012553PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012554 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012556Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012557done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558
12559static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012560unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012562 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 Py_UCS4 fillchar = ' ';
12564
Victor Stinnere9a29352011-10-01 02:14:59 +020012565 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012567
Benjamin Petersonbac79492012-01-14 13:34:47 -050012568 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012569 return NULL;
12570
Victor Stinnerc4b49542011-12-11 22:44:26 +010012571 if (PyUnicode_GET_LENGTH(self) >= width)
12572 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573
Victor Stinnerc4b49542011-12-11 22:44:26 +010012574 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012575}
12576
Alexander Belopolsky40018472011-02-26 01:02:56 +000012577PyObject *
12578PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579{
12580 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012581
Guido van Rossumd57fd912000-03-10 22:53:23 +000012582 s = PyUnicode_FromObject(s);
12583 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012584 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012585 if (sep != NULL) {
12586 sep = PyUnicode_FromObject(sep);
12587 if (sep == NULL) {
12588 Py_DECREF(s);
12589 return NULL;
12590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591 }
12592
Victor Stinner9310abb2011-10-05 00:59:23 +020012593 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594
12595 Py_DECREF(s);
12596 Py_XDECREF(sep);
12597 return result;
12598}
12599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012600PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012601 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602\n\
12603Return a list of the words in S, using sep as the\n\
12604delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012605splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012606whitespace string is a separator and empty strings are\n\
12607removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608
12609static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012610unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012612 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012614 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012616 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12617 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618 return NULL;
12619
12620 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012621 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012623 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012625 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626}
12627
Thomas Wouters477c8d52006-05-27 19:21:47 +000012628PyObject *
12629PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12630{
12631 PyObject* str_obj;
12632 PyObject* sep_obj;
12633 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 int kind1, kind2, kind;
12635 void *buf1 = NULL, *buf2 = NULL;
12636 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012637
12638 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012639 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012640 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012641 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012642 if (!sep_obj) {
12643 Py_DECREF(str_obj);
12644 return NULL;
12645 }
12646 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12647 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012648 Py_DECREF(str_obj);
12649 return NULL;
12650 }
12651
Victor Stinner14f8f022011-10-05 20:58:25 +020012652 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012654 kind = Py_MAX(kind1, kind2);
12655 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012657 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658 if (!buf1)
12659 goto onError;
12660 buf2 = PyUnicode_DATA(sep_obj);
12661 if (kind2 != kind)
12662 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12663 if (!buf2)
12664 goto onError;
12665 len1 = PyUnicode_GET_LENGTH(str_obj);
12666 len2 = PyUnicode_GET_LENGTH(sep_obj);
12667
Benjamin Petersonead6b532011-12-20 17:23:42 -060012668 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012670 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12671 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12672 else
12673 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 break;
12675 case PyUnicode_2BYTE_KIND:
12676 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12677 break;
12678 case PyUnicode_4BYTE_KIND:
12679 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12680 break;
12681 default:
12682 assert(0);
12683 out = 0;
12684 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012685
12686 Py_DECREF(sep_obj);
12687 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688 if (kind1 != kind)
12689 PyMem_Free(buf1);
12690 if (kind2 != kind)
12691 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012692
12693 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012694 onError:
12695 Py_DECREF(sep_obj);
12696 Py_DECREF(str_obj);
12697 if (kind1 != kind && buf1)
12698 PyMem_Free(buf1);
12699 if (kind2 != kind && buf2)
12700 PyMem_Free(buf2);
12701 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012702}
12703
12704
12705PyObject *
12706PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12707{
12708 PyObject* str_obj;
12709 PyObject* sep_obj;
12710 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 int kind1, kind2, kind;
12712 void *buf1 = NULL, *buf2 = NULL;
12713 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012714
12715 str_obj = PyUnicode_FromObject(str_in);
12716 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012717 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012718 sep_obj = PyUnicode_FromObject(sep_in);
12719 if (!sep_obj) {
12720 Py_DECREF(str_obj);
12721 return NULL;
12722 }
12723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 kind1 = PyUnicode_KIND(str_in);
12725 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012726 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 buf1 = PyUnicode_DATA(str_in);
12728 if (kind1 != kind)
12729 buf1 = _PyUnicode_AsKind(str_in, kind);
12730 if (!buf1)
12731 goto onError;
12732 buf2 = PyUnicode_DATA(sep_obj);
12733 if (kind2 != kind)
12734 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12735 if (!buf2)
12736 goto onError;
12737 len1 = PyUnicode_GET_LENGTH(str_obj);
12738 len2 = PyUnicode_GET_LENGTH(sep_obj);
12739
Benjamin Petersonead6b532011-12-20 17:23:42 -060012740 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012741 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012742 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12743 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12744 else
12745 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012746 break;
12747 case PyUnicode_2BYTE_KIND:
12748 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12749 break;
12750 case PyUnicode_4BYTE_KIND:
12751 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12752 break;
12753 default:
12754 assert(0);
12755 out = 0;
12756 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012757
12758 Py_DECREF(sep_obj);
12759 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 if (kind1 != kind)
12761 PyMem_Free(buf1);
12762 if (kind2 != kind)
12763 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012764
12765 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766 onError:
12767 Py_DECREF(sep_obj);
12768 Py_DECREF(str_obj);
12769 if (kind1 != kind && buf1)
12770 PyMem_Free(buf1);
12771 if (kind2 != kind && buf2)
12772 PyMem_Free(buf2);
12773 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012774}
12775
12776PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012778\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012779Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012780the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012781found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012782
12783static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012784unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012785{
Victor Stinner9310abb2011-10-05 00:59:23 +020012786 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012787}
12788
12789PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012790 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012791\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012792Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012793the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012794separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012795
12796static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012797unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012798{
Victor Stinner9310abb2011-10-05 00:59:23 +020012799 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800}
12801
Alexander Belopolsky40018472011-02-26 01:02:56 +000012802PyObject *
12803PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012804{
12805 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012806
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012807 s = PyUnicode_FromObject(s);
12808 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012809 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012810 if (sep != NULL) {
12811 sep = PyUnicode_FromObject(sep);
12812 if (sep == NULL) {
12813 Py_DECREF(s);
12814 return NULL;
12815 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012816 }
12817
Victor Stinner9310abb2011-10-05 00:59:23 +020012818 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012819
12820 Py_DECREF(s);
12821 Py_XDECREF(sep);
12822 return result;
12823}
12824
12825PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012826 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012827\n\
12828Return a list of the words in S, using sep as the\n\
12829delimiter string, starting at the end of the string and\n\
12830working to the front. If maxsplit is given, at most maxsplit\n\
12831splits are done. If sep is not specified, any whitespace string\n\
12832is a separator.");
12833
12834static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012835unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012836{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012837 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012838 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012839 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012840
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012841 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12842 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012843 return NULL;
12844
12845 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012846 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012847 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012848 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012849 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012850 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012851}
12852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012853PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012854 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855\n\
12856Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012857Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012858is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859
12860static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012861unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012863 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012864 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012866 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12867 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012868 return NULL;
12869
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012870 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871}
12872
12873static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012874PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012876 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877}
12878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012879PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012880 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881\n\
12882Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012883and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884
12885static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012886unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012888 if (PyUnicode_READY(self) == -1)
12889 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012890 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891}
12892
Larry Hastings61272b72014-01-07 12:41:53 -080012893/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012894
Larry Hastings31826802013-10-19 00:09:25 -070012895@staticmethod
12896str.maketrans as unicode_maketrans
12897
12898 x: object
12899
12900 y: unicode=NULL
12901
12902 z: unicode=NULL
12903
12904 /
12905
12906Return a translation table usable for str.translate().
12907
12908If there is only one argument, it must be a dictionary mapping Unicode
12909ordinals (integers) or characters to Unicode ordinals, strings or None.
12910Character keys will be then converted to ordinals.
12911If there are two arguments, they must be strings of equal length, and
12912in the resulting dictionary, each character in x will be mapped to the
12913character at the same position in y. If there is a third argument, it
12914must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012915[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012916
12917PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012918"maketrans(x, y=None, z=None, /)\n"
12919"--\n"
12920"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012921"Return a translation table usable for str.translate().\n"
12922"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012923"If there is only one argument, it must be a dictionary mapping Unicode\n"
12924"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12925"Character keys will be then converted to ordinals.\n"
12926"If there are two arguments, they must be strings of equal length, and\n"
12927"in the resulting dictionary, each character in x will be mapped to the\n"
12928"character at the same position in y. If there is a third argument, it\n"
12929"must be a string, whose characters will be mapped to None in the result.");
12930
12931#define UNICODE_MAKETRANS_METHODDEF \
12932 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12933
12934static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012935unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012936
12937static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012938unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012939{
Larry Hastings31826802013-10-19 00:09:25 -070012940 PyObject *return_value = NULL;
12941 PyObject *x;
12942 PyObject *y = NULL;
12943 PyObject *z = NULL;
12944
12945 if (!PyArg_ParseTuple(args,
12946 "O|UU:maketrans",
12947 &x, &y, &z))
12948 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012949 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012950
12951exit:
12952 return return_value;
12953}
12954
12955static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012956unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012957/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012958{
Georg Brandlceee0772007-11-27 23:48:05 +000012959 PyObject *new = NULL, *key, *value;
12960 Py_ssize_t i = 0;
12961 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012962
Georg Brandlceee0772007-11-27 23:48:05 +000012963 new = PyDict_New();
12964 if (!new)
12965 return NULL;
12966 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012967 int x_kind, y_kind, z_kind;
12968 void *x_data, *y_data, *z_data;
12969
Georg Brandlceee0772007-11-27 23:48:05 +000012970 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012971 if (!PyUnicode_Check(x)) {
12972 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12973 "be a string if there is a second argument");
12974 goto err;
12975 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012976 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012977 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12978 "arguments must have equal length");
12979 goto err;
12980 }
12981 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 x_kind = PyUnicode_KIND(x);
12983 y_kind = PyUnicode_KIND(y);
12984 x_data = PyUnicode_DATA(x);
12985 y_data = PyUnicode_DATA(y);
12986 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12987 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012988 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012989 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012990 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012991 if (!value) {
12992 Py_DECREF(key);
12993 goto err;
12994 }
Georg Brandlceee0772007-11-27 23:48:05 +000012995 res = PyDict_SetItem(new, key, value);
12996 Py_DECREF(key);
12997 Py_DECREF(value);
12998 if (res < 0)
12999 goto err;
13000 }
13001 /* create entries for deleting chars in z */
13002 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 z_kind = PyUnicode_KIND(z);
13004 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013005 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013006 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013007 if (!key)
13008 goto err;
13009 res = PyDict_SetItem(new, key, Py_None);
13010 Py_DECREF(key);
13011 if (res < 0)
13012 goto err;
13013 }
13014 }
13015 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013016 int kind;
13017 void *data;
13018
Georg Brandlceee0772007-11-27 23:48:05 +000013019 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013020 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013021 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13022 "to maketrans it must be a dict");
13023 goto err;
13024 }
13025 /* copy entries into the new dict, converting string keys to int keys */
13026 while (PyDict_Next(x, &i, &key, &value)) {
13027 if (PyUnicode_Check(key)) {
13028 /* convert string keys to integer keys */
13029 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013030 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013031 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13032 "table must be of length 1");
13033 goto err;
13034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013035 kind = PyUnicode_KIND(key);
13036 data = PyUnicode_DATA(key);
13037 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013038 if (!newkey)
13039 goto err;
13040 res = PyDict_SetItem(new, newkey, value);
13041 Py_DECREF(newkey);
13042 if (res < 0)
13043 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013044 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013045 /* just keep integer keys */
13046 if (PyDict_SetItem(new, key, value) < 0)
13047 goto err;
13048 } else {
13049 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13050 "be strings or integers");
13051 goto err;
13052 }
13053 }
13054 }
13055 return new;
13056 err:
13057 Py_DECREF(new);
13058 return NULL;
13059}
13060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013061PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013062 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013063\n\
13064Return a copy of the string S, where all characters have been mapped\n\
13065through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013066Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013067Unmapped characters are left untouched. Characters mapped to None\n\
13068are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069
13070static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013071unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013072{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013073 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074}
13075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013076PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013077 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013079Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013080
13081static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013082unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013084 if (PyUnicode_READY(self) == -1)
13085 return NULL;
13086 if (PyUnicode_IS_ASCII(self))
13087 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013088 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089}
13090
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013091PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013092 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013094Pad a numeric string S with zeros on the left, to fill a field\n\
13095of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096
13097static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013098unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013100 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013101 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013102 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013103 int kind;
13104 void *data;
13105 Py_UCS4 chr;
13106
Martin v. Löwis18e16552006-02-15 17:27:45 +000013107 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108 return NULL;
13109
Benjamin Petersonbac79492012-01-14 13:34:47 -050013110 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013111 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112
Victor Stinnerc4b49542011-12-11 22:44:26 +010013113 if (PyUnicode_GET_LENGTH(self) >= width)
13114 return unicode_result_unchanged(self);
13115
13116 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117
13118 u = pad(self, fill, 0, '0');
13119
Walter Dörwald068325e2002-04-15 13:36:47 +000013120 if (u == NULL)
13121 return NULL;
13122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013123 kind = PyUnicode_KIND(u);
13124 data = PyUnicode_DATA(u);
13125 chr = PyUnicode_READ(kind, data, fill);
13126
13127 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129 PyUnicode_WRITE(kind, data, 0, chr);
13130 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131 }
13132
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013133 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013134 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136
13137#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013138static PyObject *
13139unicode__decimal2ascii(PyObject *self)
13140{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013141 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013142}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143#endif
13144
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013145PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013146 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013148Return True if S starts with the specified prefix, False otherwise.\n\
13149With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013150With optional end, stop comparing S at that position.\n\
13151prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152
13153static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013154unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013155 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013157 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013158 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013159 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013160 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013161 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162
Jesus Ceaac451502011-04-20 17:09:23 +020013163 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013164 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013165 if (PyTuple_Check(subobj)) {
13166 Py_ssize_t i;
13167 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013168 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013169 if (substring == NULL)
13170 return NULL;
13171 result = tailmatch(self, substring, start, end, -1);
13172 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013173 if (result == -1)
13174 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013175 if (result) {
13176 Py_RETURN_TRUE;
13177 }
13178 }
13179 /* nothing matched */
13180 Py_RETURN_FALSE;
13181 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013182 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013183 if (substring == NULL) {
13184 if (PyErr_ExceptionMatches(PyExc_TypeError))
13185 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13186 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013188 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013189 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013191 if (result == -1)
13192 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013193 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194}
13195
13196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013197PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013198 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013200Return True if S ends with the specified suffix, False otherwise.\n\
13201With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013202With optional end, stop comparing S at that position.\n\
13203suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204
13205static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013206unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013207 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013209 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013210 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013211 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013212 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013213 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214
Jesus Ceaac451502011-04-20 17:09:23 +020013215 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013216 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013217 if (PyTuple_Check(subobj)) {
13218 Py_ssize_t i;
13219 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013220 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013222 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013224 result = tailmatch(self, substring, start, end, +1);
13225 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013226 if (result == -1)
13227 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013228 if (result) {
13229 Py_RETURN_TRUE;
13230 }
13231 }
13232 Py_RETURN_FALSE;
13233 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013234 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013235 if (substring == NULL) {
13236 if (PyErr_ExceptionMatches(PyExc_TypeError))
13237 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13238 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013240 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013241 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013242 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013243 if (result == -1)
13244 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013245 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246}
13247
Victor Stinner202fdca2012-05-07 12:47:02 +020013248Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013249_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013250{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013251 if (!writer->readonly)
13252 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13253 else {
13254 /* Copy-on-write mode: set buffer size to 0 so
13255 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13256 * next write. */
13257 writer->size = 0;
13258 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013259 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13260 writer->data = PyUnicode_DATA(writer->buffer);
13261 writer->kind = PyUnicode_KIND(writer->buffer);
13262}
13263
Victor Stinnerd3f08822012-05-29 12:57:52 +020013264void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013265_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013266{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013267 memset(writer, 0, sizeof(*writer));
13268#ifdef Py_DEBUG
13269 writer->kind = 5; /* invalid kind */
13270#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013271 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013272}
13273
Victor Stinnerd3f08822012-05-29 12:57:52 +020013274int
13275_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13276 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013277{
Victor Stinner6989ba02013-11-18 21:08:39 +010013278#ifdef MS_WINDOWS
13279 /* On Windows, overallocate by 50% is the best factor */
13280# define OVERALLOCATE_FACTOR 2
13281#else
13282 /* On Linux, overallocate by 25% is the best factor */
13283# define OVERALLOCATE_FACTOR 4
13284#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013285 Py_ssize_t newlen;
13286 PyObject *newbuffer;
13287
Victor Stinnerd3f08822012-05-29 12:57:52 +020013288 assert(length > 0);
13289
Victor Stinner202fdca2012-05-07 12:47:02 +020013290 if (length > PY_SSIZE_T_MAX - writer->pos) {
13291 PyErr_NoMemory();
13292 return -1;
13293 }
13294 newlen = writer->pos + length;
13295
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013296 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013297
Victor Stinnerd3f08822012-05-29 12:57:52 +020013298 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013299 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013300 if (writer->overallocate
13301 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13302 /* overallocate to limit the number of realloc() */
13303 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013304 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013305 if (newlen < writer->min_length)
13306 newlen = writer->min_length;
13307
Victor Stinnerd3f08822012-05-29 12:57:52 +020013308 writer->buffer = PyUnicode_New(newlen, maxchar);
13309 if (writer->buffer == NULL)
13310 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013311 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013312 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013313 if (writer->overallocate
13314 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13315 /* overallocate to limit the number of realloc() */
13316 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013317 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013318 if (newlen < writer->min_length)
13319 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013320
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013321 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013322 /* resize + widen */
13323 newbuffer = PyUnicode_New(newlen, maxchar);
13324 if (newbuffer == NULL)
13325 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013326 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13327 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013328 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013329 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013330 }
13331 else {
13332 newbuffer = resize_compact(writer->buffer, newlen);
13333 if (newbuffer == NULL)
13334 return -1;
13335 }
13336 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013337 }
13338 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013339 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013340 newbuffer = PyUnicode_New(writer->size, maxchar);
13341 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013342 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013343 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13344 writer->buffer, 0, writer->pos);
13345 Py_DECREF(writer->buffer);
13346 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013347 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013348 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013349 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013350
13351#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013352}
13353
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013354Py_LOCAL_INLINE(int)
13355_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013356{
13357 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13358 return -1;
13359 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13360 writer->pos++;
13361 return 0;
13362}
13363
13364int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013365_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13366{
13367 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13368}
13369
13370int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013371_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13372{
13373 Py_UCS4 maxchar;
13374 Py_ssize_t len;
13375
13376 if (PyUnicode_READY(str) == -1)
13377 return -1;
13378 len = PyUnicode_GET_LENGTH(str);
13379 if (len == 0)
13380 return 0;
13381 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13382 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013383 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013384 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013385 Py_INCREF(str);
13386 writer->buffer = str;
13387 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013388 writer->pos += len;
13389 return 0;
13390 }
13391 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13392 return -1;
13393 }
13394 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13395 str, 0, len);
13396 writer->pos += len;
13397 return 0;
13398}
13399
Victor Stinnere215d962012-10-06 23:03:36 +020013400int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013401_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13402 Py_ssize_t start, Py_ssize_t end)
13403{
13404 Py_UCS4 maxchar;
13405 Py_ssize_t len;
13406
13407 if (PyUnicode_READY(str) == -1)
13408 return -1;
13409
13410 assert(0 <= start);
13411 assert(end <= PyUnicode_GET_LENGTH(str));
13412 assert(start <= end);
13413
13414 if (end == 0)
13415 return 0;
13416
13417 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13418 return _PyUnicodeWriter_WriteStr(writer, str);
13419
13420 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13421 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13422 else
13423 maxchar = writer->maxchar;
13424 len = end - start;
13425
13426 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13427 return -1;
13428
13429 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13430 str, start, len);
13431 writer->pos += len;
13432 return 0;
13433}
13434
13435int
Victor Stinner4a587072013-11-19 12:54:53 +010013436_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13437 const char *ascii, Py_ssize_t len)
13438{
13439 if (len == -1)
13440 len = strlen(ascii);
13441
13442 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13443
13444 if (writer->buffer == NULL && !writer->overallocate) {
13445 PyObject *str;
13446
13447 str = _PyUnicode_FromASCII(ascii, len);
13448 if (str == NULL)
13449 return -1;
13450
13451 writer->readonly = 1;
13452 writer->buffer = str;
13453 _PyUnicodeWriter_Update(writer);
13454 writer->pos += len;
13455 return 0;
13456 }
13457
13458 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13459 return -1;
13460
13461 switch (writer->kind)
13462 {
13463 case PyUnicode_1BYTE_KIND:
13464 {
13465 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13466 Py_UCS1 *data = writer->data;
13467
13468 Py_MEMCPY(data + writer->pos, str, len);
13469 break;
13470 }
13471 case PyUnicode_2BYTE_KIND:
13472 {
13473 _PyUnicode_CONVERT_BYTES(
13474 Py_UCS1, Py_UCS2,
13475 ascii, ascii + len,
13476 (Py_UCS2 *)writer->data + writer->pos);
13477 break;
13478 }
13479 case PyUnicode_4BYTE_KIND:
13480 {
13481 _PyUnicode_CONVERT_BYTES(
13482 Py_UCS1, Py_UCS4,
13483 ascii, ascii + len,
13484 (Py_UCS4 *)writer->data + writer->pos);
13485 break;
13486 }
13487 default:
13488 assert(0);
13489 }
13490
13491 writer->pos += len;
13492 return 0;
13493}
13494
13495int
13496_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13497 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013498{
13499 Py_UCS4 maxchar;
13500
13501 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13502 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13503 return -1;
13504 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13505 writer->pos += len;
13506 return 0;
13507}
13508
Victor Stinnerd3f08822012-05-29 12:57:52 +020013509PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013510_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013511{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013512 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013513 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013514 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013515 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013516 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013517 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013518 str = writer->buffer;
13519 writer->buffer = NULL;
13520 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13521 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013522 }
13523 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13524 PyObject *newbuffer;
13525 newbuffer = resize_compact(writer->buffer, writer->pos);
13526 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013527 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013528 return NULL;
13529 }
13530 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013531 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013532 str = writer->buffer;
13533 writer->buffer = NULL;
13534 assert(_PyUnicode_CheckConsistency(str, 1));
13535 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013536}
13537
Victor Stinnerd3f08822012-05-29 12:57:52 +020013538void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013539_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013540{
13541 Py_CLEAR(writer->buffer);
13542}
13543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013544#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013545
13546PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013547 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013548\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013549Return a formatted version of S, using substitutions from args and kwargs.\n\
13550The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013551
Eric Smith27bbca62010-11-04 17:06:58 +000013552PyDoc_STRVAR(format_map__doc__,
13553 "S.format_map(mapping) -> str\n\
13554\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013555Return a formatted version of S, using substitutions from mapping.\n\
13556The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013557
Eric Smith4a7d76d2008-05-30 18:10:19 +000013558static PyObject *
13559unicode__format__(PyObject* self, PyObject* args)
13560{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013561 PyObject *format_spec;
13562 _PyUnicodeWriter writer;
13563 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013564
13565 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13566 return NULL;
13567
Victor Stinnerd3f08822012-05-29 12:57:52 +020013568 if (PyUnicode_READY(self) == -1)
13569 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013570 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013571 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13572 self, format_spec, 0,
13573 PyUnicode_GET_LENGTH(format_spec));
13574 if (ret == -1) {
13575 _PyUnicodeWriter_Dealloc(&writer);
13576 return NULL;
13577 }
13578 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013579}
13580
Eric Smith8c663262007-08-25 02:26:07 +000013581PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013582 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013583\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013584Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013585
13586static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013587unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013588{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013589 Py_ssize_t size;
13590
13591 /* If it's a compact object, account for base structure +
13592 character data. */
13593 if (PyUnicode_IS_COMPACT_ASCII(v))
13594 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13595 else if (PyUnicode_IS_COMPACT(v))
13596 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013597 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013598 else {
13599 /* If it is a two-block object, account for base object, and
13600 for character block if present. */
13601 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013602 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013603 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013604 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013605 }
13606 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013607 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013608 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013609 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013610 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013611 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013612
13613 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013614}
13615
13616PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013618
13619static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013620unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013621{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013622 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013623 if (!copy)
13624 return NULL;
13625 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013626}
13627
Guido van Rossumd57fd912000-03-10 22:53:23 +000013628static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013629 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013630 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013631 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13632 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013633 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13634 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013635 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013636 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13637 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13638 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013639 {"expandtabs", (PyCFunction) unicode_expandtabs,
13640 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013641 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013642 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013643 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13644 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13645 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013646 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013647 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13648 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13649 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013650 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013651 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013652 {"splitlines", (PyCFunction) unicode_splitlines,
13653 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013654 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013655 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13656 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13657 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13658 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13659 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13660 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13661 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13662 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13663 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13664 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13665 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13666 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13667 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13668 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013669 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013670 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013671 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013672 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013673 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013674 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013675 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013676 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013677#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013678 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013679 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013680#endif
13681
Benjamin Peterson14339b62009-01-31 16:36:08 +000013682 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013683 {NULL, NULL}
13684};
13685
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013686static PyObject *
13687unicode_mod(PyObject *v, PyObject *w)
13688{
Brian Curtindfc80e32011-08-10 20:28:54 -050013689 if (!PyUnicode_Check(v))
13690 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013692}
13693
13694static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013695 0, /*nb_add*/
13696 0, /*nb_subtract*/
13697 0, /*nb_multiply*/
13698 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013699};
13700
Guido van Rossumd57fd912000-03-10 22:53:23 +000013701static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013702 (lenfunc) unicode_length, /* sq_length */
13703 PyUnicode_Concat, /* sq_concat */
13704 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13705 (ssizeargfunc) unicode_getitem, /* sq_item */
13706 0, /* sq_slice */
13707 0, /* sq_ass_item */
13708 0, /* sq_ass_slice */
13709 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013710};
13711
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013712static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013713unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013714{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013715 if (PyUnicode_READY(self) == -1)
13716 return NULL;
13717
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013718 if (PyIndex_Check(item)) {
13719 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013720 if (i == -1 && PyErr_Occurred())
13721 return NULL;
13722 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013723 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013724 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013725 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013726 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013727 PyObject *result;
13728 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013729 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013730 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013732 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013734 return NULL;
13735 }
13736
13737 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013738 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013739 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013740 slicelength == PyUnicode_GET_LENGTH(self)) {
13741 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013742 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013743 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013744 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013745 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013746 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013747 src_kind = PyUnicode_KIND(self);
13748 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013749 if (!PyUnicode_IS_ASCII(self)) {
13750 kind_limit = kind_maxchar_limit(src_kind);
13751 max_char = 0;
13752 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13753 ch = PyUnicode_READ(src_kind, src_data, cur);
13754 if (ch > max_char) {
13755 max_char = ch;
13756 if (max_char >= kind_limit)
13757 break;
13758 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013759 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013760 }
Victor Stinner55c99112011-10-13 01:17:06 +020013761 else
13762 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013763 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013764 if (result == NULL)
13765 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013766 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013767 dest_data = PyUnicode_DATA(result);
13768
13769 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013770 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13771 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013772 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013773 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013774 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013775 } else {
13776 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13777 return NULL;
13778 }
13779}
13780
13781static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013782 (lenfunc)unicode_length, /* mp_length */
13783 (binaryfunc)unicode_subscript, /* mp_subscript */
13784 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013785};
13786
Guido van Rossumd57fd912000-03-10 22:53:23 +000013787
Guido van Rossumd57fd912000-03-10 22:53:23 +000013788/* Helpers for PyUnicode_Format() */
13789
Victor Stinnera47082312012-10-04 02:19:54 +020013790struct unicode_formatter_t {
13791 PyObject *args;
13792 int args_owned;
13793 Py_ssize_t arglen, argidx;
13794 PyObject *dict;
13795
13796 enum PyUnicode_Kind fmtkind;
13797 Py_ssize_t fmtcnt, fmtpos;
13798 void *fmtdata;
13799 PyObject *fmtstr;
13800
13801 _PyUnicodeWriter writer;
13802};
13803
13804struct unicode_format_arg_t {
13805 Py_UCS4 ch;
13806 int flags;
13807 Py_ssize_t width;
13808 int prec;
13809 int sign;
13810};
13811
Guido van Rossumd57fd912000-03-10 22:53:23 +000013812static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013813unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013814{
Victor Stinnera47082312012-10-04 02:19:54 +020013815 Py_ssize_t argidx = ctx->argidx;
13816
13817 if (argidx < ctx->arglen) {
13818 ctx->argidx++;
13819 if (ctx->arglen < 0)
13820 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013821 else
Victor Stinnera47082312012-10-04 02:19:54 +020013822 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013823 }
13824 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013825 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013826 return NULL;
13827}
13828
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013829/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830
Victor Stinnera47082312012-10-04 02:19:54 +020013831/* Format a float into the writer if the writer is not NULL, or into *p_output
13832 otherwise.
13833
13834 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013835static int
Victor Stinnera47082312012-10-04 02:19:54 +020013836formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13837 PyObject **p_output,
13838 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013839{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013840 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013841 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013842 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013843 int prec;
13844 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013845
Guido van Rossumd57fd912000-03-10 22:53:23 +000013846 x = PyFloat_AsDouble(v);
13847 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013848 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013849
Victor Stinnera47082312012-10-04 02:19:54 +020013850 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013851 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013852 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013853
Victor Stinnera47082312012-10-04 02:19:54 +020013854 if (arg->flags & F_ALT)
13855 dtoa_flags = Py_DTSF_ALT;
13856 else
13857 dtoa_flags = 0;
13858 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013859 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013860 return -1;
13861 len = strlen(p);
13862 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013863 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013864 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013865 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013866 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013867 }
13868 else
13869 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013870 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013871 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013872}
13873
Victor Stinnerd0880d52012-04-27 23:40:13 +020013874/* formatlong() emulates the format codes d, u, o, x and X, and
13875 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13876 * Python's regular ints.
13877 * Return value: a new PyUnicodeObject*, or NULL if error.
13878 * The output string is of the form
13879 * "-"? ("0x" | "0X")? digit+
13880 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13881 * set in flags. The case of hex digits will be correct,
13882 * There will be at least prec digits, zero-filled on the left if
13883 * necessary to get that many.
13884 * val object to be converted
13885 * flags bitmask of format flags; only F_ALT is looked at
13886 * prec minimum number of digits; 0-fill on left if needed
13887 * type a character in [duoxX]; u acts the same as d
13888 *
13889 * CAUTION: o, x and X conversions on regular ints can never
13890 * produce a '-' sign, but can for Python's unbounded ints.
13891 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013892static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013893formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013894{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013895 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013896 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013897 Py_ssize_t i;
13898 int sign; /* 1 if '-', else 0 */
13899 int len; /* number of characters */
13900 Py_ssize_t llen;
13901 int numdigits; /* len == numnondigits + numdigits */
13902 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013903 int prec = arg->prec;
13904 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013905
Victor Stinnerd0880d52012-04-27 23:40:13 +020013906 /* Avoid exceeding SSIZE_T_MAX */
13907 if (prec > INT_MAX-3) {
13908 PyErr_SetString(PyExc_OverflowError,
13909 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013910 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013911 }
13912
13913 assert(PyLong_Check(val));
13914
13915 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013916 default:
13917 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013918 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013919 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013920 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013921 /* int and int subclasses should print numerically when a numeric */
13922 /* format code is used (see issue18780) */
13923 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013924 break;
13925 case 'o':
13926 numnondigits = 2;
13927 result = PyNumber_ToBase(val, 8);
13928 break;
13929 case 'x':
13930 case 'X':
13931 numnondigits = 2;
13932 result = PyNumber_ToBase(val, 16);
13933 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013934 }
13935 if (!result)
13936 return NULL;
13937
13938 assert(unicode_modifiable(result));
13939 assert(PyUnicode_IS_READY(result));
13940 assert(PyUnicode_IS_ASCII(result));
13941
13942 /* To modify the string in-place, there can only be one reference. */
13943 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013944 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013945 PyErr_BadInternalCall();
13946 return NULL;
13947 }
13948 buf = PyUnicode_DATA(result);
13949 llen = PyUnicode_GET_LENGTH(result);
13950 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013951 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013952 PyErr_SetString(PyExc_ValueError,
13953 "string too large in _PyBytes_FormatLong");
13954 return NULL;
13955 }
13956 len = (int)llen;
13957 sign = buf[0] == '-';
13958 numnondigits += sign;
13959 numdigits = len - numnondigits;
13960 assert(numdigits > 0);
13961
13962 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013963 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013964 (type == 'o' || type == 'x' || type == 'X'))) {
13965 assert(buf[sign] == '0');
13966 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13967 buf[sign+1] == 'o');
13968 numnondigits -= 2;
13969 buf += 2;
13970 len -= 2;
13971 if (sign)
13972 buf[0] = '-';
13973 assert(len == numnondigits + numdigits);
13974 assert(numdigits > 0);
13975 }
13976
13977 /* Fill with leading zeroes to meet minimum width. */
13978 if (prec > numdigits) {
13979 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13980 numnondigits + prec);
13981 char *b1;
13982 if (!r1) {
13983 Py_DECREF(result);
13984 return NULL;
13985 }
13986 b1 = PyBytes_AS_STRING(r1);
13987 for (i = 0; i < numnondigits; ++i)
13988 *b1++ = *buf++;
13989 for (i = 0; i < prec - numdigits; i++)
13990 *b1++ = '0';
13991 for (i = 0; i < numdigits; i++)
13992 *b1++ = *buf++;
13993 *b1 = '\0';
13994 Py_DECREF(result);
13995 result = r1;
13996 buf = PyBytes_AS_STRING(result);
13997 len = numnondigits + prec;
13998 }
13999
14000 /* Fix up case for hex conversions. */
14001 if (type == 'X') {
14002 /* Need to convert all lower case letters to upper case.
14003 and need to convert 0x to 0X (and -0x to -0X). */
14004 for (i = 0; i < len; i++)
14005 if (buf[i] >= 'a' && buf[i] <= 'x')
14006 buf[i] -= 'a'-'A';
14007 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014008 if (!PyUnicode_Check(result)
14009 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014010 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014011 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014012 Py_DECREF(result);
14013 result = unicode;
14014 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014015 else if (len != PyUnicode_GET_LENGTH(result)) {
14016 if (PyUnicode_Resize(&result, len) < 0)
14017 Py_CLEAR(result);
14018 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014020}
14021
Ethan Furmandf3ed242014-01-05 06:50:30 -080014022/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014023 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014024 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014025 * -1 and raise an exception on error */
14026static int
Victor Stinnera47082312012-10-04 02:19:54 +020014027mainformatlong(PyObject *v,
14028 struct unicode_format_arg_t *arg,
14029 PyObject **p_output,
14030 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014031{
14032 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014033 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014034
14035 if (!PyNumber_Check(v))
14036 goto wrongtype;
14037
Ethan Furman9ab74802014-03-21 06:38:46 -070014038 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014039 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014040 if (type == 'o' || type == 'x' || type == 'X') {
14041 iobj = PyNumber_Index(v);
14042 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014043 if (PyErr_ExceptionMatches(PyExc_TypeError))
14044 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014045 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014046 }
14047 }
14048 else {
14049 iobj = PyNumber_Long(v);
14050 if (iobj == NULL ) {
14051 if (PyErr_ExceptionMatches(PyExc_TypeError))
14052 goto wrongtype;
14053 return -1;
14054 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014055 }
14056 assert(PyLong_Check(iobj));
14057 }
14058 else {
14059 iobj = v;
14060 Py_INCREF(iobj);
14061 }
14062
14063 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014064 && arg->width == -1 && arg->prec == -1
14065 && !(arg->flags & (F_SIGN | F_BLANK))
14066 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014067 {
14068 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014069 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014070 int base;
14071
Victor Stinnera47082312012-10-04 02:19:54 +020014072 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014073 {
14074 default:
14075 assert(0 && "'type' not in [diuoxX]");
14076 case 'd':
14077 case 'i':
14078 case 'u':
14079 base = 10;
14080 break;
14081 case 'o':
14082 base = 8;
14083 break;
14084 case 'x':
14085 case 'X':
14086 base = 16;
14087 break;
14088 }
14089
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014090 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14091 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014092 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014093 }
14094 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 return 1;
14096 }
14097
Victor Stinnera47082312012-10-04 02:19:54 +020014098 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014099 Py_DECREF(iobj);
14100 if (res == NULL)
14101 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014102 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014103 return 0;
14104
14105wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014106 switch(type)
14107 {
14108 case 'o':
14109 case 'x':
14110 case 'X':
14111 PyErr_Format(PyExc_TypeError,
14112 "%%%c format: an integer is required, "
14113 "not %.200s",
14114 type, Py_TYPE(v)->tp_name);
14115 break;
14116 default:
14117 PyErr_Format(PyExc_TypeError,
14118 "%%%c format: a number is required, "
14119 "not %.200s",
14120 type, Py_TYPE(v)->tp_name);
14121 break;
14122 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014123 return -1;
14124}
14125
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014126static Py_UCS4
14127formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014128{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014129 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014130 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014131 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014132 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 goto onError;
14135 }
14136 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014137 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014138 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014139 /* make sure number is a type of integer */
14140 if (!PyLong_Check(v)) {
14141 iobj = PyNumber_Index(v);
14142 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014143 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014144 }
14145 v = iobj;
14146 Py_DECREF(iobj);
14147 }
14148 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014149 x = PyLong_AsLong(v);
14150 if (x == -1 && PyErr_Occurred())
14151 goto onError;
14152
Victor Stinner8faf8212011-12-08 22:14:11 +010014153 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014154 PyErr_SetString(PyExc_OverflowError,
14155 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014156 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014157 }
14158
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014159 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014160 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014161
Benjamin Peterson29060642009-01-31 22:14:21 +000014162 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014163 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014164 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014165 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014166}
14167
Victor Stinnera47082312012-10-04 02:19:54 +020014168/* Parse options of an argument: flags, width, precision.
14169 Handle also "%(name)" syntax.
14170
14171 Return 0 if the argument has been formatted into arg->str.
14172 Return 1 if the argument has been written into ctx->writer,
14173 Raise an exception and return -1 on error. */
14174static int
14175unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14176 struct unicode_format_arg_t *arg)
14177{
14178#define FORMAT_READ(ctx) \
14179 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14180
14181 PyObject *v;
14182
Victor Stinnera47082312012-10-04 02:19:54 +020014183 if (arg->ch == '(') {
14184 /* Get argument value from a dictionary. Example: "%(name)s". */
14185 Py_ssize_t keystart;
14186 Py_ssize_t keylen;
14187 PyObject *key;
14188 int pcount = 1;
14189
14190 if (ctx->dict == NULL) {
14191 PyErr_SetString(PyExc_TypeError,
14192 "format requires a mapping");
14193 return -1;
14194 }
14195 ++ctx->fmtpos;
14196 --ctx->fmtcnt;
14197 keystart = ctx->fmtpos;
14198 /* Skip over balanced parentheses */
14199 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14200 arg->ch = FORMAT_READ(ctx);
14201 if (arg->ch == ')')
14202 --pcount;
14203 else if (arg->ch == '(')
14204 ++pcount;
14205 ctx->fmtpos++;
14206 }
14207 keylen = ctx->fmtpos - keystart - 1;
14208 if (ctx->fmtcnt < 0 || pcount > 0) {
14209 PyErr_SetString(PyExc_ValueError,
14210 "incomplete format key");
14211 return -1;
14212 }
14213 key = PyUnicode_Substring(ctx->fmtstr,
14214 keystart, keystart + keylen);
14215 if (key == NULL)
14216 return -1;
14217 if (ctx->args_owned) {
14218 Py_DECREF(ctx->args);
14219 ctx->args_owned = 0;
14220 }
14221 ctx->args = PyObject_GetItem(ctx->dict, key);
14222 Py_DECREF(key);
14223 if (ctx->args == NULL)
14224 return -1;
14225 ctx->args_owned = 1;
14226 ctx->arglen = -1;
14227 ctx->argidx = -2;
14228 }
14229
14230 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014231 while (--ctx->fmtcnt >= 0) {
14232 arg->ch = FORMAT_READ(ctx);
14233 ctx->fmtpos++;
14234 switch (arg->ch) {
14235 case '-': arg->flags |= F_LJUST; continue;
14236 case '+': arg->flags |= F_SIGN; continue;
14237 case ' ': arg->flags |= F_BLANK; continue;
14238 case '#': arg->flags |= F_ALT; continue;
14239 case '0': arg->flags |= F_ZERO; continue;
14240 }
14241 break;
14242 }
14243
14244 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014245 if (arg->ch == '*') {
14246 v = unicode_format_getnextarg(ctx);
14247 if (v == NULL)
14248 return -1;
14249 if (!PyLong_Check(v)) {
14250 PyErr_SetString(PyExc_TypeError,
14251 "* wants int");
14252 return -1;
14253 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014254 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014255 if (arg->width == -1 && PyErr_Occurred())
14256 return -1;
14257 if (arg->width < 0) {
14258 arg->flags |= F_LJUST;
14259 arg->width = -arg->width;
14260 }
14261 if (--ctx->fmtcnt >= 0) {
14262 arg->ch = FORMAT_READ(ctx);
14263 ctx->fmtpos++;
14264 }
14265 }
14266 else if (arg->ch >= '0' && arg->ch <= '9') {
14267 arg->width = arg->ch - '0';
14268 while (--ctx->fmtcnt >= 0) {
14269 arg->ch = FORMAT_READ(ctx);
14270 ctx->fmtpos++;
14271 if (arg->ch < '0' || arg->ch > '9')
14272 break;
14273 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14274 mixing signed and unsigned comparison. Since arg->ch is between
14275 '0' and '9', casting to int is safe. */
14276 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14277 PyErr_SetString(PyExc_ValueError,
14278 "width too big");
14279 return -1;
14280 }
14281 arg->width = arg->width*10 + (arg->ch - '0');
14282 }
14283 }
14284
14285 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014286 if (arg->ch == '.') {
14287 arg->prec = 0;
14288 if (--ctx->fmtcnt >= 0) {
14289 arg->ch = FORMAT_READ(ctx);
14290 ctx->fmtpos++;
14291 }
14292 if (arg->ch == '*') {
14293 v = unicode_format_getnextarg(ctx);
14294 if (v == NULL)
14295 return -1;
14296 if (!PyLong_Check(v)) {
14297 PyErr_SetString(PyExc_TypeError,
14298 "* wants int");
14299 return -1;
14300 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014301 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014302 if (arg->prec == -1 && PyErr_Occurred())
14303 return -1;
14304 if (arg->prec < 0)
14305 arg->prec = 0;
14306 if (--ctx->fmtcnt >= 0) {
14307 arg->ch = FORMAT_READ(ctx);
14308 ctx->fmtpos++;
14309 }
14310 }
14311 else if (arg->ch >= '0' && arg->ch <= '9') {
14312 arg->prec = arg->ch - '0';
14313 while (--ctx->fmtcnt >= 0) {
14314 arg->ch = FORMAT_READ(ctx);
14315 ctx->fmtpos++;
14316 if (arg->ch < '0' || arg->ch > '9')
14317 break;
14318 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14319 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014320 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014321 return -1;
14322 }
14323 arg->prec = arg->prec*10 + (arg->ch - '0');
14324 }
14325 }
14326 }
14327
14328 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14329 if (ctx->fmtcnt >= 0) {
14330 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14331 if (--ctx->fmtcnt >= 0) {
14332 arg->ch = FORMAT_READ(ctx);
14333 ctx->fmtpos++;
14334 }
14335 }
14336 }
14337 if (ctx->fmtcnt < 0) {
14338 PyErr_SetString(PyExc_ValueError,
14339 "incomplete format");
14340 return -1;
14341 }
14342 return 0;
14343
14344#undef FORMAT_READ
14345}
14346
14347/* Format one argument. Supported conversion specifiers:
14348
14349 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014350 - "i", "d", "u": int or float
14351 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014352 - "e", "E", "f", "F", "g", "G": float
14353 - "c": int or str (1 character)
14354
Victor Stinner8dbd4212012-12-04 09:30:24 +010014355 When possible, the output is written directly into the Unicode writer
14356 (ctx->writer). A string is created when padding is required.
14357
Victor Stinnera47082312012-10-04 02:19:54 +020014358 Return 0 if the argument has been formatted into *p_str,
14359 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014360 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014361static int
14362unicode_format_arg_format(struct unicode_formatter_t *ctx,
14363 struct unicode_format_arg_t *arg,
14364 PyObject **p_str)
14365{
14366 PyObject *v;
14367 _PyUnicodeWriter *writer = &ctx->writer;
14368
14369 if (ctx->fmtcnt == 0)
14370 ctx->writer.overallocate = 0;
14371
14372 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014373 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014374 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014375 return 1;
14376 }
14377
14378 v = unicode_format_getnextarg(ctx);
14379 if (v == NULL)
14380 return -1;
14381
Victor Stinnera47082312012-10-04 02:19:54 +020014382
14383 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014384 case 's':
14385 case 'r':
14386 case 'a':
14387 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14388 /* Fast path */
14389 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14390 return -1;
14391 return 1;
14392 }
14393
14394 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14395 *p_str = v;
14396 Py_INCREF(*p_str);
14397 }
14398 else {
14399 if (arg->ch == 's')
14400 *p_str = PyObject_Str(v);
14401 else if (arg->ch == 'r')
14402 *p_str = PyObject_Repr(v);
14403 else
14404 *p_str = PyObject_ASCII(v);
14405 }
14406 break;
14407
14408 case 'i':
14409 case 'd':
14410 case 'u':
14411 case 'o':
14412 case 'x':
14413 case 'X':
14414 {
14415 int ret = mainformatlong(v, arg, p_str, writer);
14416 if (ret != 0)
14417 return ret;
14418 arg->sign = 1;
14419 break;
14420 }
14421
14422 case 'e':
14423 case 'E':
14424 case 'f':
14425 case 'F':
14426 case 'g':
14427 case 'G':
14428 if (arg->width == -1 && arg->prec == -1
14429 && !(arg->flags & (F_SIGN | F_BLANK)))
14430 {
14431 /* Fast path */
14432 if (formatfloat(v, arg, NULL, writer) == -1)
14433 return -1;
14434 return 1;
14435 }
14436
14437 arg->sign = 1;
14438 if (formatfloat(v, arg, p_str, NULL) == -1)
14439 return -1;
14440 break;
14441
14442 case 'c':
14443 {
14444 Py_UCS4 ch = formatchar(v);
14445 if (ch == (Py_UCS4) -1)
14446 return -1;
14447 if (arg->width == -1 && arg->prec == -1) {
14448 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014449 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014450 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014451 return 1;
14452 }
14453 *p_str = PyUnicode_FromOrdinal(ch);
14454 break;
14455 }
14456
14457 default:
14458 PyErr_Format(PyExc_ValueError,
14459 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014460 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014461 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14462 (int)arg->ch,
14463 ctx->fmtpos - 1);
14464 return -1;
14465 }
14466 if (*p_str == NULL)
14467 return -1;
14468 assert (PyUnicode_Check(*p_str));
14469 return 0;
14470}
14471
14472static int
14473unicode_format_arg_output(struct unicode_formatter_t *ctx,
14474 struct unicode_format_arg_t *arg,
14475 PyObject *str)
14476{
14477 Py_ssize_t len;
14478 enum PyUnicode_Kind kind;
14479 void *pbuf;
14480 Py_ssize_t pindex;
14481 Py_UCS4 signchar;
14482 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014483 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014484 Py_ssize_t sublen;
14485 _PyUnicodeWriter *writer = &ctx->writer;
14486 Py_UCS4 fill;
14487
14488 fill = ' ';
14489 if (arg->sign && arg->flags & F_ZERO)
14490 fill = '0';
14491
14492 if (PyUnicode_READY(str) == -1)
14493 return -1;
14494
14495 len = PyUnicode_GET_LENGTH(str);
14496 if ((arg->width == -1 || arg->width <= len)
14497 && (arg->prec == -1 || arg->prec >= len)
14498 && !(arg->flags & (F_SIGN | F_BLANK)))
14499 {
14500 /* Fast path */
14501 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14502 return -1;
14503 return 0;
14504 }
14505
14506 /* Truncate the string for "s", "r" and "a" formats
14507 if the precision is set */
14508 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14509 if (arg->prec >= 0 && len > arg->prec)
14510 len = arg->prec;
14511 }
14512
14513 /* Adjust sign and width */
14514 kind = PyUnicode_KIND(str);
14515 pbuf = PyUnicode_DATA(str);
14516 pindex = 0;
14517 signchar = '\0';
14518 if (arg->sign) {
14519 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14520 if (ch == '-' || ch == '+') {
14521 signchar = ch;
14522 len--;
14523 pindex++;
14524 }
14525 else if (arg->flags & F_SIGN)
14526 signchar = '+';
14527 else if (arg->flags & F_BLANK)
14528 signchar = ' ';
14529 else
14530 arg->sign = 0;
14531 }
14532 if (arg->width < len)
14533 arg->width = len;
14534
14535 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014536 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014537 if (!(arg->flags & F_LJUST)) {
14538 if (arg->sign) {
14539 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014540 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014541 }
14542 else {
14543 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014544 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014545 }
14546 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014547 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14548 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014549 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014550 }
14551
Victor Stinnera47082312012-10-04 02:19:54 +020014552 buflen = arg->width;
14553 if (arg->sign && len == arg->width)
14554 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014555 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014556 return -1;
14557
14558 /* Write the sign if needed */
14559 if (arg->sign) {
14560 if (fill != ' ') {
14561 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14562 writer->pos += 1;
14563 }
14564 if (arg->width > len)
14565 arg->width--;
14566 }
14567
14568 /* Write the numeric prefix for "x", "X" and "o" formats
14569 if the alternate form is used.
14570 For example, write "0x" for the "%#x" format. */
14571 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14572 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14573 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14574 if (fill != ' ') {
14575 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14576 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14577 writer->pos += 2;
14578 pindex += 2;
14579 }
14580 arg->width -= 2;
14581 if (arg->width < 0)
14582 arg->width = 0;
14583 len -= 2;
14584 }
14585
14586 /* Pad left with the fill character if needed */
14587 if (arg->width > len && !(arg->flags & F_LJUST)) {
14588 sublen = arg->width - len;
14589 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14590 writer->pos += sublen;
14591 arg->width = len;
14592 }
14593
14594 /* If padding with spaces: write sign if needed and/or numeric prefix if
14595 the alternate form is used */
14596 if (fill == ' ') {
14597 if (arg->sign) {
14598 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14599 writer->pos += 1;
14600 }
14601 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14602 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14603 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14604 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14605 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14606 writer->pos += 2;
14607 pindex += 2;
14608 }
14609 }
14610
14611 /* Write characters */
14612 if (len) {
14613 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14614 str, pindex, len);
14615 writer->pos += len;
14616 }
14617
14618 /* Pad right with the fill character if needed */
14619 if (arg->width > len) {
14620 sublen = arg->width - len;
14621 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14622 writer->pos += sublen;
14623 }
14624 return 0;
14625}
14626
14627/* Helper of PyUnicode_Format(): format one arg.
14628 Return 0 on success, raise an exception and return -1 on error. */
14629static int
14630unicode_format_arg(struct unicode_formatter_t *ctx)
14631{
14632 struct unicode_format_arg_t arg;
14633 PyObject *str;
14634 int ret;
14635
Victor Stinner8dbd4212012-12-04 09:30:24 +010014636 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14637 arg.flags = 0;
14638 arg.width = -1;
14639 arg.prec = -1;
14640 arg.sign = 0;
14641 str = NULL;
14642
Victor Stinnera47082312012-10-04 02:19:54 +020014643 ret = unicode_format_arg_parse(ctx, &arg);
14644 if (ret == -1)
14645 return -1;
14646
14647 ret = unicode_format_arg_format(ctx, &arg, &str);
14648 if (ret == -1)
14649 return -1;
14650
14651 if (ret != 1) {
14652 ret = unicode_format_arg_output(ctx, &arg, str);
14653 Py_DECREF(str);
14654 if (ret == -1)
14655 return -1;
14656 }
14657
14658 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14659 PyErr_SetString(PyExc_TypeError,
14660 "not all arguments converted during string formatting");
14661 return -1;
14662 }
14663 return 0;
14664}
14665
Alexander Belopolsky40018472011-02-26 01:02:56 +000014666PyObject *
14667PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014668{
Victor Stinnera47082312012-10-04 02:19:54 +020014669 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014670
Guido van Rossumd57fd912000-03-10 22:53:23 +000014671 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014672 PyErr_BadInternalCall();
14673 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014674 }
Victor Stinnera47082312012-10-04 02:19:54 +020014675
14676 ctx.fmtstr = PyUnicode_FromObject(format);
14677 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014678 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014679 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14680 Py_DECREF(ctx.fmtstr);
14681 return NULL;
14682 }
14683 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14684 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14685 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14686 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014687
Victor Stinner8f674cc2013-04-17 23:02:17 +020014688 _PyUnicodeWriter_Init(&ctx.writer);
14689 ctx.writer.min_length = ctx.fmtcnt + 100;
14690 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014691
Guido van Rossumd57fd912000-03-10 22:53:23 +000014692 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014693 ctx.arglen = PyTuple_Size(args);
14694 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014695 }
14696 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014697 ctx.arglen = -1;
14698 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014699 }
Victor Stinnera47082312012-10-04 02:19:54 +020014700 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014701 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014702 ctx.dict = args;
14703 else
14704 ctx.dict = NULL;
14705 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014706
Victor Stinnera47082312012-10-04 02:19:54 +020014707 while (--ctx.fmtcnt >= 0) {
14708 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014709 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014710
14711 nonfmtpos = ctx.fmtpos++;
14712 while (ctx.fmtcnt >= 0 &&
14713 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14714 ctx.fmtpos++;
14715 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014716 }
Victor Stinnera47082312012-10-04 02:19:54 +020014717 if (ctx.fmtcnt < 0) {
14718 ctx.fmtpos--;
14719 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014720 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014721
Victor Stinnercfc4c132013-04-03 01:48:39 +020014722 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14723 nonfmtpos, ctx.fmtpos) < 0)
14724 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014725 }
14726 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014727 ctx.fmtpos++;
14728 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014729 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014730 }
14731 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014732
Victor Stinnera47082312012-10-04 02:19:54 +020014733 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014734 PyErr_SetString(PyExc_TypeError,
14735 "not all arguments converted during string formatting");
14736 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014737 }
14738
Victor Stinnera47082312012-10-04 02:19:54 +020014739 if (ctx.args_owned) {
14740 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014741 }
Victor Stinnera47082312012-10-04 02:19:54 +020014742 Py_DECREF(ctx.fmtstr);
14743 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014744
Benjamin Peterson29060642009-01-31 22:14:21 +000014745 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014746 Py_DECREF(ctx.fmtstr);
14747 _PyUnicodeWriter_Dealloc(&ctx.writer);
14748 if (ctx.args_owned) {
14749 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014750 }
14751 return NULL;
14752}
14753
Jeremy Hylton938ace62002-07-17 16:30:39 +000014754static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014755unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14756
Tim Peters6d6c1a32001-08-02 04:15:00 +000014757static PyObject *
14758unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14759{
Benjamin Peterson29060642009-01-31 22:14:21 +000014760 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014761 static char *kwlist[] = {"object", "encoding", "errors", 0};
14762 char *encoding = NULL;
14763 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014764
Benjamin Peterson14339b62009-01-31 16:36:08 +000014765 if (type != &PyUnicode_Type)
14766 return unicode_subtype_new(type, args, kwds);
14767 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014768 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014769 return NULL;
14770 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014771 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014772 if (encoding == NULL && errors == NULL)
14773 return PyObject_Str(x);
14774 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014775 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014776}
14777
Guido van Rossume023fe02001-08-30 03:12:59 +000014778static PyObject *
14779unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14780{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014781 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014782 Py_ssize_t length, char_size;
14783 int share_wstr, share_utf8;
14784 unsigned int kind;
14785 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014786
Benjamin Peterson14339b62009-01-31 16:36:08 +000014787 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014788
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014789 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014790 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014791 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014792 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014793 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014794 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014795 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014796 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014797
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014798 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014799 if (self == NULL) {
14800 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014801 return NULL;
14802 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014803 kind = PyUnicode_KIND(unicode);
14804 length = PyUnicode_GET_LENGTH(unicode);
14805
14806 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014807#ifdef Py_DEBUG
14808 _PyUnicode_HASH(self) = -1;
14809#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014810 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014811#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014812 _PyUnicode_STATE(self).interned = 0;
14813 _PyUnicode_STATE(self).kind = kind;
14814 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014815 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014816 _PyUnicode_STATE(self).ready = 1;
14817 _PyUnicode_WSTR(self) = NULL;
14818 _PyUnicode_UTF8_LENGTH(self) = 0;
14819 _PyUnicode_UTF8(self) = NULL;
14820 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014821 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014822
14823 share_utf8 = 0;
14824 share_wstr = 0;
14825 if (kind == PyUnicode_1BYTE_KIND) {
14826 char_size = 1;
14827 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14828 share_utf8 = 1;
14829 }
14830 else if (kind == PyUnicode_2BYTE_KIND) {
14831 char_size = 2;
14832 if (sizeof(wchar_t) == 2)
14833 share_wstr = 1;
14834 }
14835 else {
14836 assert(kind == PyUnicode_4BYTE_KIND);
14837 char_size = 4;
14838 if (sizeof(wchar_t) == 4)
14839 share_wstr = 1;
14840 }
14841
14842 /* Ensure we won't overflow the length. */
14843 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14844 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014845 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014846 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014847 data = PyObject_MALLOC((length + 1) * char_size);
14848 if (data == NULL) {
14849 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014850 goto onError;
14851 }
14852
Victor Stinnerc3c74152011-10-02 20:39:55 +020014853 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014854 if (share_utf8) {
14855 _PyUnicode_UTF8_LENGTH(self) = length;
14856 _PyUnicode_UTF8(self) = data;
14857 }
14858 if (share_wstr) {
14859 _PyUnicode_WSTR_LENGTH(self) = length;
14860 _PyUnicode_WSTR(self) = (wchar_t *)data;
14861 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014862
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014863 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014864 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014865 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014866#ifdef Py_DEBUG
14867 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14868#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014869 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014870 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014871
14872onError:
14873 Py_DECREF(unicode);
14874 Py_DECREF(self);
14875 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014876}
14877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014878PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014879"str(object='') -> str\n\
14880str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014881\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014882Create a new string object from the given object. If encoding or\n\
14883errors is specified, then the object must expose a data buffer\n\
14884that will be decoded using the given encoding and error handler.\n\
14885Otherwise, returns the result of object.__str__() (if defined)\n\
14886or repr(object).\n\
14887encoding defaults to sys.getdefaultencoding().\n\
14888errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014889
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014890static PyObject *unicode_iter(PyObject *seq);
14891
Guido van Rossumd57fd912000-03-10 22:53:23 +000014892PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014893 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014894 "str", /* tp_name */
14895 sizeof(PyUnicodeObject), /* tp_size */
14896 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014897 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014898 (destructor)unicode_dealloc, /* tp_dealloc */
14899 0, /* tp_print */
14900 0, /* tp_getattr */
14901 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014902 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014903 unicode_repr, /* tp_repr */
14904 &unicode_as_number, /* tp_as_number */
14905 &unicode_as_sequence, /* tp_as_sequence */
14906 &unicode_as_mapping, /* tp_as_mapping */
14907 (hashfunc) unicode_hash, /* tp_hash*/
14908 0, /* tp_call*/
14909 (reprfunc) unicode_str, /* tp_str */
14910 PyObject_GenericGetAttr, /* tp_getattro */
14911 0, /* tp_setattro */
14912 0, /* tp_as_buffer */
14913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014914 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014915 unicode_doc, /* tp_doc */
14916 0, /* tp_traverse */
14917 0, /* tp_clear */
14918 PyUnicode_RichCompare, /* tp_richcompare */
14919 0, /* tp_weaklistoffset */
14920 unicode_iter, /* tp_iter */
14921 0, /* tp_iternext */
14922 unicode_methods, /* tp_methods */
14923 0, /* tp_members */
14924 0, /* tp_getset */
14925 &PyBaseObject_Type, /* tp_base */
14926 0, /* tp_dict */
14927 0, /* tp_descr_get */
14928 0, /* tp_descr_set */
14929 0, /* tp_dictoffset */
14930 0, /* tp_init */
14931 0, /* tp_alloc */
14932 unicode_new, /* tp_new */
14933 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014934};
14935
14936/* Initialize the Unicode implementation */
14937
Victor Stinner3a50e702011-10-18 21:21:00 +020014938int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014939{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014940 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014941 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014942 0x000A, /* LINE FEED */
14943 0x000D, /* CARRIAGE RETURN */
14944 0x001C, /* FILE SEPARATOR */
14945 0x001D, /* GROUP SEPARATOR */
14946 0x001E, /* RECORD SEPARATOR */
14947 0x0085, /* NEXT LINE */
14948 0x2028, /* LINE SEPARATOR */
14949 0x2029, /* PARAGRAPH SEPARATOR */
14950 };
14951
Fred Drakee4315f52000-05-09 19:53:39 +000014952 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014953 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014954 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014955 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014956 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014957
Guido van Rossumcacfc072002-05-24 19:01:59 +000014958 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014959 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014960
14961 /* initialize the linebreak bloom filter */
14962 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014963 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014964 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014965
Christian Heimes26532f72013-07-20 14:57:16 +020014966 if (PyType_Ready(&EncodingMapType) < 0)
14967 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014968
Benjamin Petersonc4311282012-10-30 23:21:10 -040014969 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14970 Py_FatalError("Can't initialize field name iterator type");
14971
14972 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14973 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014974
Victor Stinner3a50e702011-10-18 21:21:00 +020014975#ifdef HAVE_MBCS
14976 winver.dwOSVersionInfoSize = sizeof(winver);
14977 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14978 PyErr_SetFromWindowsErr(0);
14979 return -1;
14980 }
14981#endif
14982 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014983}
14984
14985/* Finalize the Unicode implementation */
14986
Christian Heimesa156e092008-02-16 07:38:31 +000014987int
14988PyUnicode_ClearFreeList(void)
14989{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014990 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014991}
14992
Guido van Rossumd57fd912000-03-10 22:53:23 +000014993void
Thomas Wouters78890102000-07-22 19:25:51 +000014994_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014995{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014996 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014997
Serhiy Storchaka05997252013-01-26 12:14:02 +020014998 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014999
Serhiy Storchaka05997252013-01-26 12:14:02 +020015000 for (i = 0; i < 256; i++)
15001 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015002 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015003 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015004}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015005
Walter Dörwald16807132007-05-25 13:52:07 +000015006void
15007PyUnicode_InternInPlace(PyObject **p)
15008{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015009 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015010 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015011#ifdef Py_DEBUG
15012 assert(s != NULL);
15013 assert(_PyUnicode_CHECK(s));
15014#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015015 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015016 return;
15017#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015018 /* If it's a subclass, we don't really know what putting
15019 it in the interned dict might do. */
15020 if (!PyUnicode_CheckExact(s))
15021 return;
15022 if (PyUnicode_CHECK_INTERNED(s))
15023 return;
15024 if (interned == NULL) {
15025 interned = PyDict_New();
15026 if (interned == NULL) {
15027 PyErr_Clear(); /* Don't leave an exception */
15028 return;
15029 }
15030 }
15031 /* It might be that the GetItem call fails even
15032 though the key is present in the dictionary,
15033 namely when this happens during a stack overflow. */
15034 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015035 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015037
Victor Stinnerf0335102013-04-14 19:13:03 +020015038 if (t) {
15039 Py_INCREF(t);
15040 Py_DECREF(*p);
15041 *p = t;
15042 return;
15043 }
Walter Dörwald16807132007-05-25 13:52:07 +000015044
Benjamin Peterson14339b62009-01-31 16:36:08 +000015045 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015046 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015047 PyErr_Clear();
15048 PyThreadState_GET()->recursion_critical = 0;
15049 return;
15050 }
15051 PyThreadState_GET()->recursion_critical = 0;
15052 /* The two references in interned are not counted by refcnt.
15053 The deallocator will take care of this */
15054 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015055 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015056}
15057
15058void
15059PyUnicode_InternImmortal(PyObject **p)
15060{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015061 PyUnicode_InternInPlace(p);
15062 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015063 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015064 Py_INCREF(*p);
15065 }
Walter Dörwald16807132007-05-25 13:52:07 +000015066}
15067
15068PyObject *
15069PyUnicode_InternFromString(const char *cp)
15070{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 PyObject *s = PyUnicode_FromString(cp);
15072 if (s == NULL)
15073 return NULL;
15074 PyUnicode_InternInPlace(&s);
15075 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015076}
15077
Alexander Belopolsky40018472011-02-26 01:02:56 +000015078void
15079_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015080{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015081 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015082 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015083 Py_ssize_t i, n;
15084 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015085
Benjamin Peterson14339b62009-01-31 16:36:08 +000015086 if (interned == NULL || !PyDict_Check(interned))
15087 return;
15088 keys = PyDict_Keys(interned);
15089 if (keys == NULL || !PyList_Check(keys)) {
15090 PyErr_Clear();
15091 return;
15092 }
Walter Dörwald16807132007-05-25 13:52:07 +000015093
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15095 detector, interned unicode strings are not forcibly deallocated;
15096 rather, we give them their stolen references back, and then clear
15097 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015098
Benjamin Peterson14339b62009-01-31 16:36:08 +000015099 n = PyList_GET_SIZE(keys);
15100 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015101 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015102 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015103 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015104 if (PyUnicode_READY(s) == -1) {
15105 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015106 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015108 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015109 case SSTATE_NOT_INTERNED:
15110 /* XXX Shouldn't happen */
15111 break;
15112 case SSTATE_INTERNED_IMMORTAL:
15113 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015114 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015115 break;
15116 case SSTATE_INTERNED_MORTAL:
15117 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015118 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015119 break;
15120 default:
15121 Py_FatalError("Inconsistent interned string state.");
15122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015123 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015124 }
15125 fprintf(stderr, "total size of all interned strings: "
15126 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15127 "mortal/immortal\n", mortal_size, immortal_size);
15128 Py_DECREF(keys);
15129 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015130 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015131}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015132
15133
15134/********************* Unicode Iterator **************************/
15135
15136typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015137 PyObject_HEAD
15138 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015139 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015140} unicodeiterobject;
15141
15142static void
15143unicodeiter_dealloc(unicodeiterobject *it)
15144{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 _PyObject_GC_UNTRACK(it);
15146 Py_XDECREF(it->it_seq);
15147 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015148}
15149
15150static int
15151unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15152{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015153 Py_VISIT(it->it_seq);
15154 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015155}
15156
15157static PyObject *
15158unicodeiter_next(unicodeiterobject *it)
15159{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015160 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015161
Benjamin Peterson14339b62009-01-31 16:36:08 +000015162 assert(it != NULL);
15163 seq = it->it_seq;
15164 if (seq == NULL)
15165 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015166 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015168 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15169 int kind = PyUnicode_KIND(seq);
15170 void *data = PyUnicode_DATA(seq);
15171 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15172 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015173 if (item != NULL)
15174 ++it->it_index;
15175 return item;
15176 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015177
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 Py_DECREF(seq);
15179 it->it_seq = NULL;
15180 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015181}
15182
15183static PyObject *
15184unicodeiter_len(unicodeiterobject *it)
15185{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015186 Py_ssize_t len = 0;
15187 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015188 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015190}
15191
15192PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15193
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015194static PyObject *
15195unicodeiter_reduce(unicodeiterobject *it)
15196{
15197 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015198 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015199 it->it_seq, it->it_index);
15200 } else {
15201 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15202 if (u == NULL)
15203 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015204 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015205 }
15206}
15207
15208PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15209
15210static PyObject *
15211unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15212{
15213 Py_ssize_t index = PyLong_AsSsize_t(state);
15214 if (index == -1 && PyErr_Occurred())
15215 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015216 if (it->it_seq != NULL) {
15217 if (index < 0)
15218 index = 0;
15219 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15220 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15221 it->it_index = index;
15222 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015223 Py_RETURN_NONE;
15224}
15225
15226PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15227
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015228static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015229 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015230 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015231 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15232 reduce_doc},
15233 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15234 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015235 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015236};
15237
15238PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015239 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15240 "str_iterator", /* tp_name */
15241 sizeof(unicodeiterobject), /* tp_basicsize */
15242 0, /* tp_itemsize */
15243 /* methods */
15244 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15245 0, /* tp_print */
15246 0, /* tp_getattr */
15247 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015248 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015249 0, /* tp_repr */
15250 0, /* tp_as_number */
15251 0, /* tp_as_sequence */
15252 0, /* tp_as_mapping */
15253 0, /* tp_hash */
15254 0, /* tp_call */
15255 0, /* tp_str */
15256 PyObject_GenericGetAttr, /* tp_getattro */
15257 0, /* tp_setattro */
15258 0, /* tp_as_buffer */
15259 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15260 0, /* tp_doc */
15261 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15262 0, /* tp_clear */
15263 0, /* tp_richcompare */
15264 0, /* tp_weaklistoffset */
15265 PyObject_SelfIter, /* tp_iter */
15266 (iternextfunc)unicodeiter_next, /* tp_iternext */
15267 unicodeiter_methods, /* tp_methods */
15268 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015269};
15270
15271static PyObject *
15272unicode_iter(PyObject *seq)
15273{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015274 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015275
Benjamin Peterson14339b62009-01-31 16:36:08 +000015276 if (!PyUnicode_Check(seq)) {
15277 PyErr_BadInternalCall();
15278 return NULL;
15279 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015280 if (PyUnicode_READY(seq) == -1)
15281 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015282 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15283 if (it == NULL)
15284 return NULL;
15285 it->it_index = 0;
15286 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015287 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015288 _PyObject_GC_TRACK(it);
15289 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015290}
15291
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015292
15293size_t
15294Py_UNICODE_strlen(const Py_UNICODE *u)
15295{
15296 int res = 0;
15297 while(*u++)
15298 res++;
15299 return res;
15300}
15301
15302Py_UNICODE*
15303Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15304{
15305 Py_UNICODE *u = s1;
15306 while ((*u++ = *s2++));
15307 return s1;
15308}
15309
15310Py_UNICODE*
15311Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15312{
15313 Py_UNICODE *u = s1;
15314 while ((*u++ = *s2++))
15315 if (n-- == 0)
15316 break;
15317 return s1;
15318}
15319
15320Py_UNICODE*
15321Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15322{
15323 Py_UNICODE *u1 = s1;
15324 u1 += Py_UNICODE_strlen(u1);
15325 Py_UNICODE_strcpy(u1, s2);
15326 return s1;
15327}
15328
15329int
15330Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15331{
15332 while (*s1 && *s2 && *s1 == *s2)
15333 s1++, s2++;
15334 if (*s1 && *s2)
15335 return (*s1 < *s2) ? -1 : +1;
15336 if (*s1)
15337 return 1;
15338 if (*s2)
15339 return -1;
15340 return 0;
15341}
15342
15343int
15344Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15345{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015346 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015347 for (; n != 0; n--) {
15348 u1 = *s1;
15349 u2 = *s2;
15350 if (u1 != u2)
15351 return (u1 < u2) ? -1 : +1;
15352 if (u1 == '\0')
15353 return 0;
15354 s1++;
15355 s2++;
15356 }
15357 return 0;
15358}
15359
15360Py_UNICODE*
15361Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15362{
15363 const Py_UNICODE *p;
15364 for (p = s; *p; p++)
15365 if (*p == c)
15366 return (Py_UNICODE*)p;
15367 return NULL;
15368}
15369
15370Py_UNICODE*
15371Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15372{
15373 const Py_UNICODE *p;
15374 p = s + Py_UNICODE_strlen(s);
15375 while (p != s) {
15376 p--;
15377 if (*p == c)
15378 return (Py_UNICODE*)p;
15379 }
15380 return NULL;
15381}
Victor Stinner331ea922010-08-10 16:37:20 +000015382
Victor Stinner71133ff2010-09-01 23:43:53 +000015383Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015384PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015385{
Victor Stinner577db2c2011-10-11 22:12:48 +020015386 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015387 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015389 if (!PyUnicode_Check(unicode)) {
15390 PyErr_BadArgument();
15391 return NULL;
15392 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015393 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015394 if (u == NULL)
15395 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015396 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015397 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015398 PyErr_NoMemory();
15399 return NULL;
15400 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015401 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015402 size *= sizeof(Py_UNICODE);
15403 copy = PyMem_Malloc(size);
15404 if (copy == NULL) {
15405 PyErr_NoMemory();
15406 return NULL;
15407 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015408 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015409 return copy;
15410}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015411
Georg Brandl66c221e2010-10-14 07:04:07 +000015412/* A _string module, to export formatter_parser and formatter_field_name_split
15413 to the string.Formatter class implemented in Python. */
15414
15415static PyMethodDef _string_methods[] = {
15416 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15417 METH_O, PyDoc_STR("split the argument as a field name")},
15418 {"formatter_parser", (PyCFunction) formatter_parser,
15419 METH_O, PyDoc_STR("parse the argument as a format string")},
15420 {NULL, NULL}
15421};
15422
15423static struct PyModuleDef _string_module = {
15424 PyModuleDef_HEAD_INIT,
15425 "_string",
15426 PyDoc_STR("string helper module"),
15427 0,
15428 _string_methods,
15429 NULL,
15430 NULL,
15431 NULL,
15432 NULL
15433};
15434
15435PyMODINIT_FUNC
15436PyInit__string(void)
15437{
15438 return PyModule_Create(&_string_module);
15439}
15440
15441
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015442#ifdef __cplusplus
15443}
15444#endif