blob: 15705e10f9d9b536a38e9cd90b4bea6ca9a4223a [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
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300293#include "clinic/unicodeobject.c.h"
294
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300295/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
296 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000298PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000299{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000300#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000303 /* This is actually an illegal character, so it should
304 not be passed to unichr. */
305 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000306#endif
307}
308
Victor Stinner910337b2011-10-03 03:20:16 +0200309#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200310int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100311_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200312{
313 PyASCIIObject *ascii;
314 unsigned int kind;
315
316 assert(PyUnicode_Check(op));
317
318 ascii = (PyASCIIObject *)op;
319 kind = ascii->state.kind;
320
Victor Stinnera3b334d2011-10-03 13:53:37 +0200321 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200322 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(ascii->state.ready == 1);
324 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200325 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200326 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200327 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200328
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 if (ascii->state.compact == 1) {
330 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(kind == PyUnicode_1BYTE_KIND
332 || kind == PyUnicode_2BYTE_KIND
333 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200335 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 }
338 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
340
341 data = unicode->data.any;
342 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100343 assert(ascii->length == 0);
344 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200345 assert(ascii->state.compact == 0);
346 assert(ascii->state.ascii == 0);
347 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100348 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200349 assert(ascii->wstr != NULL);
350 assert(data == NULL);
351 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200352 }
353 else {
354 assert(kind == PyUnicode_1BYTE_KIND
355 || kind == PyUnicode_2BYTE_KIND
356 || kind == PyUnicode_4BYTE_KIND);
357 assert(ascii->state.compact == 0);
358 assert(ascii->state.ready == 1);
359 assert(data != NULL);
360 if (ascii->state.ascii) {
361 assert (compact->utf8 == data);
362 assert (compact->utf8_length == ascii->length);
363 }
364 else
365 assert (compact->utf8 != data);
366 }
367 }
368 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200369 if (
370#if SIZEOF_WCHAR_T == 2
371 kind == PyUnicode_2BYTE_KIND
372#else
373 kind == PyUnicode_4BYTE_KIND
374#endif
375 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200376 {
377 assert(ascii->wstr == data);
378 assert(compact->wstr_length == ascii->length);
379 } else
380 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200382
383 if (compact->utf8 == NULL)
384 assert(compact->utf8_length == 0);
385 if (ascii->wstr == NULL)
386 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200387 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200388 /* check that the best kind is used */
389 if (check_content && kind != PyUnicode_WCHAR_KIND)
390 {
391 Py_ssize_t i;
392 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200393 void *data;
394 Py_UCS4 ch;
395
396 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200397 for (i=0; i < ascii->length; i++)
398 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200399 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200400 if (ch > maxchar)
401 maxchar = ch;
402 }
403 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100404 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200405 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100406 assert(maxchar <= 255);
407 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200408 else
409 assert(maxchar < 128);
410 }
Victor Stinner77faf692011-11-20 18:56:05 +0100411 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200412 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100413 assert(maxchar <= 0xFFFF);
414 }
415 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200416 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100417 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100418 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200419 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200420 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400421 return 1;
422}
Victor Stinner910337b2011-10-03 03:20:16 +0200423#endif
424
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100425static PyObject*
426unicode_result_wchar(PyObject *unicode)
427{
428#ifndef Py_DEBUG
429 Py_ssize_t len;
430
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 len = _PyUnicode_WSTR_LENGTH(unicode);
432 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200434 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100435 }
436
437 if (len == 1) {
438 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100439 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100440 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
441 Py_DECREF(unicode);
442 return latin1_char;
443 }
444 }
445
446 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200447 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100448 return NULL;
449 }
450#else
Victor Stinneraa771272012-10-04 02:32:58 +0200451 assert(Py_REFCNT(unicode) == 1);
452
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100453 /* don't make the result ready in debug mode to ensure that the caller
454 makes the string ready before using it */
455 assert(_PyUnicode_CheckConsistency(unicode, 1));
456#endif
457 return unicode;
458}
459
460static PyObject*
461unicode_result_ready(PyObject *unicode)
462{
463 Py_ssize_t length;
464
465 length = PyUnicode_GET_LENGTH(unicode);
466 if (length == 0) {
467 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200469 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100470 }
471 return unicode_empty;
472 }
473
474 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200475 void *data = PyUnicode_DATA(unicode);
476 int kind = PyUnicode_KIND(unicode);
477 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100478 if (ch < 256) {
479 PyObject *latin1_char = unicode_latin1[ch];
480 if (latin1_char != NULL) {
481 if (unicode != latin1_char) {
482 Py_INCREF(latin1_char);
483 Py_DECREF(unicode);
484 }
485 return latin1_char;
486 }
487 else {
488 assert(_PyUnicode_CheckConsistency(unicode, 1));
489 Py_INCREF(unicode);
490 unicode_latin1[ch] = unicode;
491 return unicode;
492 }
493 }
494 }
495
496 assert(_PyUnicode_CheckConsistency(unicode, 1));
497 return unicode;
498}
499
500static PyObject*
501unicode_result(PyObject *unicode)
502{
503 assert(_PyUnicode_CHECK(unicode));
504 if (PyUnicode_IS_READY(unicode))
505 return unicode_result_ready(unicode);
506 else
507 return unicode_result_wchar(unicode);
508}
509
Victor Stinnerc4b49542011-12-11 22:44:26 +0100510static PyObject*
511unicode_result_unchanged(PyObject *unicode)
512{
513 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500514 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100515 return NULL;
516 Py_INCREF(unicode);
517 return unicode;
518 }
519 else
520 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100521 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100522}
523
Thomas Wouters477c8d52006-05-27 19:21:47 +0000524/* --- Bloom Filters ----------------------------------------------------- */
525
526/* stuff to implement simple "bloom filters" for Unicode characters.
527 to keep things simple, we use a single bitmask, using the least 5
528 bits from each unicode characters as the bit index. */
529
530/* the linebreak mask is set up by Unicode_Init below */
531
Antoine Pitrouf068f942010-01-13 14:19:12 +0000532#if LONG_BIT >= 128
533#define BLOOM_WIDTH 128
534#elif LONG_BIT >= 64
535#define BLOOM_WIDTH 64
536#elif LONG_BIT >= 32
537#define BLOOM_WIDTH 32
538#else
539#error "LONG_BIT is smaller than 32"
540#endif
541
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542#define BLOOM_MASK unsigned long
543
Serhiy Storchaka05997252013-01-26 12:14:02 +0200544static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
Antoine Pitrouf068f942010-01-13 14:19:12 +0000546#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Benjamin Peterson29060642009-01-31 22:14:21 +0000548#define BLOOM_LINEBREAK(ch) \
549 ((ch) < 128U ? ascii_linebreak[(ch)] : \
550 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
Alexander Belopolsky40018472011-02-26 01:02:56 +0000552Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200553make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554{
Victor Stinnera85af502013-04-09 21:53:54 +0200555#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
556 do { \
557 TYPE *data = (TYPE *)PTR; \
558 TYPE *end = data + LEN; \
559 Py_UCS4 ch; \
560 for (; data != end; data++) { \
561 ch = *data; \
562 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
563 } \
564 break; \
565 } while (0)
566
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 /* calculate simple bloom-style bitmask for a given unicode string */
568
Antoine Pitrouf068f942010-01-13 14:19:12 +0000569 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570
571 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200572 switch (kind) {
573 case PyUnicode_1BYTE_KIND:
574 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
575 break;
576 case PyUnicode_2BYTE_KIND:
577 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
578 break;
579 case PyUnicode_4BYTE_KIND:
580 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
581 break;
582 default:
583 assert(0);
584 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200586
587#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200590/* Compilation of templated routines */
591
592#include "stringlib/asciilib.h"
593#include "stringlib/fastsearch.h"
594#include "stringlib/partition.h"
595#include "stringlib/split.h"
596#include "stringlib/count.h"
597#include "stringlib/find.h"
598#include "stringlib/find_max_char.h"
599#include "stringlib/localeutil.h"
600#include "stringlib/undef.h"
601
602#include "stringlib/ucs1lib.h"
603#include "stringlib/fastsearch.h"
604#include "stringlib/partition.h"
605#include "stringlib/split.h"
606#include "stringlib/count.h"
607#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300608#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200609#include "stringlib/find_max_char.h"
610#include "stringlib/localeutil.h"
611#include "stringlib/undef.h"
612
613#include "stringlib/ucs2lib.h"
614#include "stringlib/fastsearch.h"
615#include "stringlib/partition.h"
616#include "stringlib/split.h"
617#include "stringlib/count.h"
618#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300619#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200620#include "stringlib/find_max_char.h"
621#include "stringlib/localeutil.h"
622#include "stringlib/undef.h"
623
624#include "stringlib/ucs4lib.h"
625#include "stringlib/fastsearch.h"
626#include "stringlib/partition.h"
627#include "stringlib/split.h"
628#include "stringlib/count.h"
629#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300630#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200631#include "stringlib/find_max_char.h"
632#include "stringlib/localeutil.h"
633#include "stringlib/undef.h"
634
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200635#include "stringlib/unicodedefs.h"
636#include "stringlib/fastsearch.h"
637#include "stringlib/count.h"
638#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100639#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200640
Guido van Rossumd57fd912000-03-10 22:53:23 +0000641/* --- Unicode Object ----------------------------------------------------- */
642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200643static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200644fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200646Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200647 Py_ssize_t size, Py_UCS4 ch,
648 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200649{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200650 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
651
652 switch (kind) {
653 case PyUnicode_1BYTE_KIND:
654 {
655 Py_UCS1 ch1 = (Py_UCS1) ch;
656 if (ch1 == ch)
657 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
658 else
659 return -1;
660 }
661 case PyUnicode_2BYTE_KIND:
662 {
663 Py_UCS2 ch2 = (Py_UCS2) ch;
664 if (ch2 == ch)
665 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
666 else
667 return -1;
668 }
669 case PyUnicode_4BYTE_KIND:
670 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
671 default:
672 assert(0);
673 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200674 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200675}
676
Victor Stinnerafffce42012-10-03 23:03:17 +0200677#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000678/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200679 earlier.
680
681 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
682 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
683 invalid character in Unicode 6.0. */
684static void
685unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
686{
687 int kind = PyUnicode_KIND(unicode);
688 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
689 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
690 if (length <= old_length)
691 return;
692 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
693}
694#endif
695
Victor Stinnerfe226c02011-10-03 03:52:20 +0200696static PyObject*
697resize_compact(PyObject *unicode, Py_ssize_t length)
698{
699 Py_ssize_t char_size;
700 Py_ssize_t struct_size;
701 Py_ssize_t new_size;
702 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100703 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200704#ifdef Py_DEBUG
705 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
706#endif
707
Victor Stinner79891572012-05-03 13:43:07 +0200708 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200709 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100710 assert(PyUnicode_IS_COMPACT(unicode));
711
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200712 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100713 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200714 struct_size = sizeof(PyASCIIObject);
715 else
716 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200717 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718
Victor Stinnerfe226c02011-10-03 03:52:20 +0200719 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
720 PyErr_NoMemory();
721 return NULL;
722 }
723 new_size = (struct_size + (length + 1) * char_size);
724
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200725 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
726 PyObject_DEL(_PyUnicode_UTF8(unicode));
727 _PyUnicode_UTF8(unicode) = NULL;
728 _PyUnicode_UTF8_LENGTH(unicode) = 0;
729 }
Victor Stinner84def372011-12-11 20:04:56 +0100730 _Py_DEC_REFTOTAL;
731 _Py_ForgetReference(unicode);
732
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300733 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100734 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100735 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 PyErr_NoMemory();
737 return NULL;
738 }
Victor Stinner84def372011-12-11 20:04:56 +0100739 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200740 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100741
Victor Stinnerfe226c02011-10-03 03:52:20 +0200742 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200743 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200744 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100745 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200746 _PyUnicode_WSTR_LENGTH(unicode) = length;
747 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100748 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
749 PyObject_DEL(_PyUnicode_WSTR(unicode));
750 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100751 if (!PyUnicode_IS_ASCII(unicode))
752 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100753 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200754#ifdef Py_DEBUG
755 unicode_fill_invalid(unicode, old_length);
756#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200757 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
758 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200759 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 return unicode;
761}
762
Alexander Belopolsky40018472011-02-26 01:02:56 +0000763static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200764resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000765{
Victor Stinner95663112011-10-04 01:03:50 +0200766 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100767 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200768 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000770
Victor Stinnerfe226c02011-10-03 03:52:20 +0200771 if (PyUnicode_IS_READY(unicode)) {
772 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200773 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200775#ifdef Py_DEBUG
776 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
777#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200778
779 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200780 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200781 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
782 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200783
784 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
785 PyErr_NoMemory();
786 return -1;
787 }
788 new_size = (length + 1) * char_size;
789
Victor Stinner7a9105a2011-12-12 00:13:42 +0100790 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
791 {
792 PyObject_DEL(_PyUnicode_UTF8(unicode));
793 _PyUnicode_UTF8(unicode) = NULL;
794 _PyUnicode_UTF8_LENGTH(unicode) = 0;
795 }
796
Victor Stinnerfe226c02011-10-03 03:52:20 +0200797 data = (PyObject *)PyObject_REALLOC(data, new_size);
798 if (data == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200803 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200804 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200805 _PyUnicode_WSTR_LENGTH(unicode) = length;
806 }
807 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200808 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200809 _PyUnicode_UTF8_LENGTH(unicode) = length;
810 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200811 _PyUnicode_LENGTH(unicode) = length;
812 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200813#ifdef Py_DEBUG
814 unicode_fill_invalid(unicode, old_length);
815#endif
Victor Stinner95663112011-10-04 01:03:50 +0200816 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200817 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200818 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200819 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200820 }
Victor Stinner95663112011-10-04 01:03:50 +0200821 assert(_PyUnicode_WSTR(unicode) != NULL);
822
823 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700824 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200825 PyErr_NoMemory();
826 return -1;
827 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100828 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200829 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100830 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200831 if (!wstr) {
832 PyErr_NoMemory();
833 return -1;
834 }
835 _PyUnicode_WSTR(unicode) = wstr;
836 _PyUnicode_WSTR(unicode)[length] = 0;
837 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200838 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000839 return 0;
840}
841
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842static PyObject*
843resize_copy(PyObject *unicode, Py_ssize_t length)
844{
845 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100846 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200847 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100848
Benjamin Petersonbac79492012-01-14 13:34:47 -0500849 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100850 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200851
852 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
853 if (copy == NULL)
854 return NULL;
855
856 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200857 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200858 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200859 }
860 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200861 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100862
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200863 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200864 if (w == NULL)
865 return NULL;
866 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
867 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200868 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
869 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200870 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200871 }
872}
873
Guido van Rossumd57fd912000-03-10 22:53:23 +0000874/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000875 Ux0000 terminated; some code (e.g. new_identifier)
876 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000877
878 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000879 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880
881*/
882
Alexander Belopolsky40018472011-02-26 01:02:56 +0000883static PyUnicodeObject *
884_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200886 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200887 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888
Thomas Wouters477c8d52006-05-27 19:21:47 +0000889 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000890 if (length == 0 && unicode_empty != NULL) {
891 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200892 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000893 }
894
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000895 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700896 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000897 return (PyUnicodeObject *)PyErr_NoMemory();
898 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200899 if (length < 0) {
900 PyErr_SetString(PyExc_SystemError,
901 "Negative size passed to _PyUnicode_New");
902 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000903 }
904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200905 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
906 if (unicode == NULL)
907 return NULL;
908 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100909
910 _PyUnicode_WSTR_LENGTH(unicode) = length;
911 _PyUnicode_HASH(unicode) = -1;
912 _PyUnicode_STATE(unicode).interned = 0;
913 _PyUnicode_STATE(unicode).kind = 0;
914 _PyUnicode_STATE(unicode).compact = 0;
915 _PyUnicode_STATE(unicode).ready = 0;
916 _PyUnicode_STATE(unicode).ascii = 0;
917 _PyUnicode_DATA_ANY(unicode) = NULL;
918 _PyUnicode_LENGTH(unicode) = 0;
919 _PyUnicode_UTF8(unicode) = NULL;
920 _PyUnicode_UTF8_LENGTH(unicode) = 0;
921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
923 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100924 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000925 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100926 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000927 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200928
Jeremy Hyltond8082792003-09-16 19:41:39 +0000929 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000930 * the caller fails before initializing str -- unicode_resize()
931 * reads str[0], and the Keep-Alive optimization can keep memory
932 * allocated for str alive across a call to unicode_dealloc(unicode).
933 * We don't want unicode_resize to read uninitialized memory in
934 * that case.
935 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200936 _PyUnicode_WSTR(unicode)[0] = 0;
937 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100938
Victor Stinner7931d9a2011-11-04 00:22:48 +0100939 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000940 return unicode;
941}
942
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943static const char*
944unicode_kind_name(PyObject *unicode)
945{
Victor Stinner42dfd712011-10-03 14:41:45 +0200946 /* don't check consistency: unicode_kind_name() is called from
947 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 if (!PyUnicode_IS_COMPACT(unicode))
949 {
950 if (!PyUnicode_IS_READY(unicode))
951 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600952 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200953 {
954 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200955 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200956 return "legacy ascii";
957 else
958 return "legacy latin1";
959 case PyUnicode_2BYTE_KIND:
960 return "legacy UCS2";
961 case PyUnicode_4BYTE_KIND:
962 return "legacy UCS4";
963 default:
964 return "<legacy invalid kind>";
965 }
966 }
967 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600968 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 return "ascii";
972 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200973 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200974 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200975 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200976 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200977 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200978 default:
979 return "<invalid compact kind>";
980 }
981}
982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984/* Functions wrapping macros for use in debugger */
985char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200986 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987}
988
989void *_PyUnicode_compact_data(void *unicode) {
990 return _PyUnicode_COMPACT_DATA(unicode);
991}
992void *_PyUnicode_data(void *unicode){
993 printf("obj %p\n", unicode);
994 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
995 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
996 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
997 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
998 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
999 return PyUnicode_DATA(unicode);
1000}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001001
1002void
1003_PyUnicode_Dump(PyObject *op)
1004{
1005 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001006 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1007 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1008 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001009
Victor Stinnera849a4b2011-10-03 12:12:11 +02001010 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001011 {
1012 if (ascii->state.ascii)
1013 data = (ascii + 1);
1014 else
1015 data = (compact + 1);
1016 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001017 else
1018 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001019 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1020 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001021
Victor Stinnera849a4b2011-10-03 12:12:11 +02001022 if (ascii->wstr == data)
1023 printf("shared ");
1024 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001025
Victor Stinnera3b334d2011-10-03 13:53:37 +02001026 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001027 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001028 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1029 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001030 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1031 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001032 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001033 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001034}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035#endif
1036
1037PyObject *
1038PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1039{
1040 PyObject *obj;
1041 PyCompactUnicodeObject *unicode;
1042 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001043 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001044 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001045 Py_ssize_t char_size;
1046 Py_ssize_t struct_size;
1047
1048 /* Optimization for empty strings */
1049 if (size == 0 && unicode_empty != NULL) {
1050 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001051 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 }
1053
Victor Stinner9e9d6892011-10-04 01:02:02 +02001054 is_ascii = 0;
1055 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 struct_size = sizeof(PyCompactUnicodeObject);
1057 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001058 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059 char_size = 1;
1060 is_ascii = 1;
1061 struct_size = sizeof(PyASCIIObject);
1062 }
1063 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001064 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001065 char_size = 1;
1066 }
1067 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001068 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 char_size = 2;
1070 if (sizeof(wchar_t) == 2)
1071 is_sharing = 1;
1072 }
1073 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001074 if (maxchar > MAX_UNICODE) {
1075 PyErr_SetString(PyExc_SystemError,
1076 "invalid maximum character passed to PyUnicode_New");
1077 return NULL;
1078 }
Victor Stinner8f825062012-04-27 13:55:39 +02001079 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001080 char_size = 4;
1081 if (sizeof(wchar_t) == 4)
1082 is_sharing = 1;
1083 }
1084
1085 /* Ensure we won't overflow the size. */
1086 if (size < 0) {
1087 PyErr_SetString(PyExc_SystemError,
1088 "Negative size passed to PyUnicode_New");
1089 return NULL;
1090 }
1091 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1092 return PyErr_NoMemory();
1093
1094 /* Duplicated allocation code from _PyObject_New() instead of a call to
1095 * PyObject_New() so we are able to allocate space for the object and
1096 * it's data buffer.
1097 */
1098 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1099 if (obj == NULL)
1100 return PyErr_NoMemory();
1101 obj = PyObject_INIT(obj, &PyUnicode_Type);
1102 if (obj == NULL)
1103 return NULL;
1104
1105 unicode = (PyCompactUnicodeObject *)obj;
1106 if (is_ascii)
1107 data = ((PyASCIIObject*)obj) + 1;
1108 else
1109 data = unicode + 1;
1110 _PyUnicode_LENGTH(unicode) = size;
1111 _PyUnicode_HASH(unicode) = -1;
1112 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001113 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001114 _PyUnicode_STATE(unicode).compact = 1;
1115 _PyUnicode_STATE(unicode).ready = 1;
1116 _PyUnicode_STATE(unicode).ascii = is_ascii;
1117 if (is_ascii) {
1118 ((char*)data)[size] = 0;
1119 _PyUnicode_WSTR(unicode) = NULL;
1120 }
Victor Stinner8f825062012-04-27 13:55:39 +02001121 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001122 ((char*)data)[size] = 0;
1123 _PyUnicode_WSTR(unicode) = NULL;
1124 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001126 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001127 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128 else {
1129 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001130 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001131 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001132 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001133 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134 ((Py_UCS4*)data)[size] = 0;
1135 if (is_sharing) {
1136 _PyUnicode_WSTR_LENGTH(unicode) = size;
1137 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1138 }
1139 else {
1140 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1141 _PyUnicode_WSTR(unicode) = NULL;
1142 }
1143 }
Victor Stinner8f825062012-04-27 13:55:39 +02001144#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001145 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001146#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001147 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148 return obj;
1149}
1150
1151#if SIZEOF_WCHAR_T == 2
1152/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1153 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001154 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001155
1156 This function assumes that unicode can hold one more code point than wstr
1157 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001158static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001160 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161{
1162 const wchar_t *iter;
1163 Py_UCS4 *ucs4_out;
1164
Victor Stinner910337b2011-10-03 03:20:16 +02001165 assert(unicode != NULL);
1166 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1168 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1169
1170 for (iter = begin; iter < end; ) {
1171 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1172 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001173 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1174 && (iter+1) < end
1175 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176 {
Victor Stinner551ac952011-11-29 22:58:13 +01001177 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 iter += 2;
1179 }
1180 else {
1181 *ucs4_out++ = *iter;
1182 iter++;
1183 }
1184 }
1185 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1186 _PyUnicode_GET_LENGTH(unicode)));
1187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001188}
1189#endif
1190
Victor Stinnercd9950f2011-10-02 00:34:53 +02001191static int
Victor Stinner488fa492011-12-12 00:01:39 +01001192unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001193{
Victor Stinner488fa492011-12-12 00:01:39 +01001194 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001195 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001196 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001197 return -1;
1198 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001199 return 0;
1200}
1201
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001202static int
1203_copy_characters(PyObject *to, Py_ssize_t to_start,
1204 PyObject *from, Py_ssize_t from_start,
1205 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001207 unsigned int from_kind, to_kind;
1208 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209
Victor Stinneree4544c2012-05-09 22:24:08 +02001210 assert(0 <= how_many);
1211 assert(0 <= from_start);
1212 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001213 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001214 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001215 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216
Victor Stinnerd3f08822012-05-29 12:57:52 +02001217 assert(PyUnicode_Check(to));
1218 assert(PyUnicode_IS_READY(to));
1219 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1220
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001221 if (how_many == 0)
1222 return 0;
1223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001225 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001226 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001227 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228
Victor Stinnerf1852262012-06-16 16:38:26 +02001229#ifdef Py_DEBUG
1230 if (!check_maxchar
1231 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1232 {
1233 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1234 Py_UCS4 ch;
1235 Py_ssize_t i;
1236 for (i=0; i < how_many; i++) {
1237 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1238 assert(ch <= to_maxchar);
1239 }
1240 }
1241#endif
1242
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001243 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001244 if (check_maxchar
1245 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1246 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001247 /* Writing Latin-1 characters into an ASCII string requires to
1248 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001249 Py_UCS4 max_char;
1250 max_char = ucs1lib_find_max_char(from_data,
1251 (Py_UCS1*)from_data + how_many);
1252 if (max_char >= 128)
1253 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001254 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001255 Py_MEMCPY((char*)to_data + to_kind * to_start,
1256 (char*)from_data + from_kind * from_start,
1257 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001259 else if (from_kind == PyUnicode_1BYTE_KIND
1260 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001261 {
1262 _PyUnicode_CONVERT_BYTES(
1263 Py_UCS1, Py_UCS2,
1264 PyUnicode_1BYTE_DATA(from) + from_start,
1265 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1266 PyUnicode_2BYTE_DATA(to) + to_start
1267 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001268 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001269 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001270 && to_kind == PyUnicode_4BYTE_KIND)
1271 {
1272 _PyUnicode_CONVERT_BYTES(
1273 Py_UCS1, Py_UCS4,
1274 PyUnicode_1BYTE_DATA(from) + from_start,
1275 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1276 PyUnicode_4BYTE_DATA(to) + to_start
1277 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001278 }
1279 else if (from_kind == PyUnicode_2BYTE_KIND
1280 && to_kind == PyUnicode_4BYTE_KIND)
1281 {
1282 _PyUnicode_CONVERT_BYTES(
1283 Py_UCS2, Py_UCS4,
1284 PyUnicode_2BYTE_DATA(from) + from_start,
1285 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1286 PyUnicode_4BYTE_DATA(to) + to_start
1287 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001288 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001289 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001290 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1291
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001292 if (!check_maxchar) {
1293 if (from_kind == PyUnicode_2BYTE_KIND
1294 && to_kind == PyUnicode_1BYTE_KIND)
1295 {
1296 _PyUnicode_CONVERT_BYTES(
1297 Py_UCS2, Py_UCS1,
1298 PyUnicode_2BYTE_DATA(from) + from_start,
1299 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1300 PyUnicode_1BYTE_DATA(to) + to_start
1301 );
1302 }
1303 else if (from_kind == PyUnicode_4BYTE_KIND
1304 && to_kind == PyUnicode_1BYTE_KIND)
1305 {
1306 _PyUnicode_CONVERT_BYTES(
1307 Py_UCS4, Py_UCS1,
1308 PyUnicode_4BYTE_DATA(from) + from_start,
1309 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1310 PyUnicode_1BYTE_DATA(to) + to_start
1311 );
1312 }
1313 else if (from_kind == PyUnicode_4BYTE_KIND
1314 && to_kind == PyUnicode_2BYTE_KIND)
1315 {
1316 _PyUnicode_CONVERT_BYTES(
1317 Py_UCS4, Py_UCS2,
1318 PyUnicode_4BYTE_DATA(from) + from_start,
1319 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1320 PyUnicode_2BYTE_DATA(to) + to_start
1321 );
1322 }
1323 else {
1324 assert(0);
1325 return -1;
1326 }
1327 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001328 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001329 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001330 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001331 Py_ssize_t i;
1332
Victor Stinnera0702ab2011-09-29 14:14:38 +02001333 for (i=0; i < how_many; i++) {
1334 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001335 if (ch > to_maxchar)
1336 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001337 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1338 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001339 }
1340 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001341 return 0;
1342}
1343
Victor Stinnerd3f08822012-05-29 12:57:52 +02001344void
1345_PyUnicode_FastCopyCharacters(
1346 PyObject *to, Py_ssize_t to_start,
1347 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001348{
1349 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1350}
1351
1352Py_ssize_t
1353PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1354 PyObject *from, Py_ssize_t from_start,
1355 Py_ssize_t how_many)
1356{
1357 int err;
1358
1359 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1360 PyErr_BadInternalCall();
1361 return -1;
1362 }
1363
Benjamin Petersonbac79492012-01-14 13:34:47 -05001364 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001365 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001366 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001367 return -1;
1368
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001369 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001370 PyErr_SetString(PyExc_IndexError, "string index out of range");
1371 return -1;
1372 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001373 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001374 PyErr_SetString(PyExc_IndexError, "string index out of range");
1375 return -1;
1376 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001377 if (how_many < 0) {
1378 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1379 return -1;
1380 }
1381 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001382 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1383 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001384 "Cannot write %zi characters at %zi "
1385 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001386 how_many, to_start, PyUnicode_GET_LENGTH(to));
1387 return -1;
1388 }
1389
1390 if (how_many == 0)
1391 return 0;
1392
Victor Stinner488fa492011-12-12 00:01:39 +01001393 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001394 return -1;
1395
1396 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1397 if (err) {
1398 PyErr_Format(PyExc_SystemError,
1399 "Cannot copy %s characters "
1400 "into a string of %s characters",
1401 unicode_kind_name(from),
1402 unicode_kind_name(to));
1403 return -1;
1404 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001405 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406}
1407
Victor Stinner17222162011-09-28 22:15:37 +02001408/* Find the maximum code point and count the number of surrogate pairs so a
1409 correct string length can be computed before converting a string to UCS4.
1410 This function counts single surrogates as a character and not as a pair.
1411
1412 Return 0 on success, or -1 on error. */
1413static int
1414find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1415 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416{
1417 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001418 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419
Victor Stinnerc53be962011-10-02 21:33:54 +02001420 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 *num_surrogates = 0;
1422 *maxchar = 0;
1423
1424 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001425#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001426 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1427 && (iter+1) < end
1428 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1429 {
1430 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1431 ++(*num_surrogates);
1432 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 }
1434 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001435#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001436 {
1437 ch = *iter;
1438 iter++;
1439 }
1440 if (ch > *maxchar) {
1441 *maxchar = ch;
1442 if (*maxchar > MAX_UNICODE) {
1443 PyErr_Format(PyExc_ValueError,
1444 "character U+%x is not in range [U+0000; U+10ffff]",
1445 ch);
1446 return -1;
1447 }
1448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001449 }
1450 return 0;
1451}
1452
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001453int
1454_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001455{
1456 wchar_t *end;
1457 Py_UCS4 maxchar = 0;
1458 Py_ssize_t num_surrogates;
1459#if SIZEOF_WCHAR_T == 2
1460 Py_ssize_t length_wo_surrogates;
1461#endif
1462
Georg Brandl7597add2011-10-05 16:36:47 +02001463 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001464 strings were created using _PyObject_New() and where no canonical
1465 representation (the str field) has been set yet aka strings
1466 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001467 assert(_PyUnicode_CHECK(unicode));
1468 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001470 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001471 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001472 /* Actually, it should neither be interned nor be anything else: */
1473 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001475 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001476 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001477 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001479
1480 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001481 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1482 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001483 PyErr_NoMemory();
1484 return -1;
1485 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001486 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 _PyUnicode_WSTR(unicode), end,
1488 PyUnicode_1BYTE_DATA(unicode));
1489 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1490 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1491 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1492 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001493 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001494 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001495 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 }
1497 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001498 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001499 _PyUnicode_UTF8(unicode) = NULL;
1500 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001501 }
1502 PyObject_FREE(_PyUnicode_WSTR(unicode));
1503 _PyUnicode_WSTR(unicode) = NULL;
1504 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1505 }
1506 /* In this case we might have to convert down from 4-byte native
1507 wchar_t to 2-byte unicode. */
1508 else if (maxchar < 65536) {
1509 assert(num_surrogates == 0 &&
1510 "FindMaxCharAndNumSurrogatePairs() messed up");
1511
Victor Stinner506f5922011-09-28 22:34:18 +02001512#if SIZEOF_WCHAR_T == 2
1513 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001514 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001515 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1516 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1517 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001518 _PyUnicode_UTF8(unicode) = NULL;
1519 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001520#else
1521 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001522 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001523 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001524 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001525 PyErr_NoMemory();
1526 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001527 }
Victor Stinner506f5922011-09-28 22:34:18 +02001528 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1529 _PyUnicode_WSTR(unicode), end,
1530 PyUnicode_2BYTE_DATA(unicode));
1531 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1532 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1533 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001534 _PyUnicode_UTF8(unicode) = NULL;
1535 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001536 PyObject_FREE(_PyUnicode_WSTR(unicode));
1537 _PyUnicode_WSTR(unicode) = NULL;
1538 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1539#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 }
1541 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1542 else {
1543#if SIZEOF_WCHAR_T == 2
1544 /* in case the native representation is 2-bytes, we need to allocate a
1545 new normalized 4-byte version. */
1546 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001547 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1548 PyErr_NoMemory();
1549 return -1;
1550 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001551 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1552 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001553 PyErr_NoMemory();
1554 return -1;
1555 }
1556 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1557 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001558 _PyUnicode_UTF8(unicode) = NULL;
1559 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001560 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1561 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001562 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001563 PyObject_FREE(_PyUnicode_WSTR(unicode));
1564 _PyUnicode_WSTR(unicode) = NULL;
1565 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1566#else
1567 assert(num_surrogates == 0);
1568
Victor Stinnerc3c74152011-10-02 20:39:55 +02001569 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001570 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001571 _PyUnicode_UTF8(unicode) = NULL;
1572 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001573 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1574#endif
1575 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1576 }
1577 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001578 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001579 return 0;
1580}
1581
Alexander Belopolsky40018472011-02-26 01:02:56 +00001582static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001583unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001584{
Walter Dörwald16807132007-05-25 13:52:07 +00001585 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001586 case SSTATE_NOT_INTERNED:
1587 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001588
Benjamin Peterson29060642009-01-31 22:14:21 +00001589 case SSTATE_INTERNED_MORTAL:
1590 /* revive dead object temporarily for DelItem */
1591 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001592 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001593 Py_FatalError(
1594 "deletion of interned string failed");
1595 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001596
Benjamin Peterson29060642009-01-31 22:14:21 +00001597 case SSTATE_INTERNED_IMMORTAL:
1598 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001599
Benjamin Peterson29060642009-01-31 22:14:21 +00001600 default:
1601 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001602 }
1603
Victor Stinner03490912011-10-03 23:45:12 +02001604 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001605 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001606 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001607 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001608 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1609 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001611 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001612}
1613
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001614#ifdef Py_DEBUG
1615static int
1616unicode_is_singleton(PyObject *unicode)
1617{
1618 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1619 if (unicode == unicode_empty)
1620 return 1;
1621 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1622 {
1623 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1624 if (ch < 256 && unicode_latin1[ch] == unicode)
1625 return 1;
1626 }
1627 return 0;
1628}
1629#endif
1630
Alexander Belopolsky40018472011-02-26 01:02:56 +00001631static int
Victor Stinner488fa492011-12-12 00:01:39 +01001632unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001633{
Victor Stinner488fa492011-12-12 00:01:39 +01001634 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001635 if (Py_REFCNT(unicode) != 1)
1636 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001637 if (_PyUnicode_HASH(unicode) != -1)
1638 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001639 if (PyUnicode_CHECK_INTERNED(unicode))
1640 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001641 if (!PyUnicode_CheckExact(unicode))
1642 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001643#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001644 /* singleton refcount is greater than 1 */
1645 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001646#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001647 return 1;
1648}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001649
Victor Stinnerfe226c02011-10-03 03:52:20 +02001650static int
1651unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1652{
1653 PyObject *unicode;
1654 Py_ssize_t old_length;
1655
1656 assert(p_unicode != NULL);
1657 unicode = *p_unicode;
1658
1659 assert(unicode != NULL);
1660 assert(PyUnicode_Check(unicode));
1661 assert(0 <= length);
1662
Victor Stinner910337b2011-10-03 03:20:16 +02001663 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001664 old_length = PyUnicode_WSTR_LENGTH(unicode);
1665 else
1666 old_length = PyUnicode_GET_LENGTH(unicode);
1667 if (old_length == length)
1668 return 0;
1669
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001670 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001671 _Py_INCREF_UNICODE_EMPTY();
1672 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001673 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001674 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001675 return 0;
1676 }
1677
Victor Stinner488fa492011-12-12 00:01:39 +01001678 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001679 PyObject *copy = resize_copy(unicode, length);
1680 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001681 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001682 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001683 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001684 }
1685
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001687 PyObject *new_unicode = resize_compact(unicode, length);
1688 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001689 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001690 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001691 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001692 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001693 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001694}
1695
Alexander Belopolsky40018472011-02-26 01:02:56 +00001696int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001697PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001698{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001699 PyObject *unicode;
1700 if (p_unicode == NULL) {
1701 PyErr_BadInternalCall();
1702 return -1;
1703 }
1704 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001705 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001706 {
1707 PyErr_BadInternalCall();
1708 return -1;
1709 }
1710 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001711}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001712
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001713/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001714
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001715 WARNING: The function doesn't copy the terminating null character and
1716 doesn't check the maximum character (may write a latin1 character in an
1717 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001718static void
1719unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1720 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001721{
1722 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1723 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001724 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001725
1726 switch (kind) {
1727 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001729#ifdef Py_DEBUG
1730 if (PyUnicode_IS_ASCII(unicode)) {
1731 Py_UCS4 maxchar = ucs1lib_find_max_char(
1732 (const Py_UCS1*)str,
1733 (const Py_UCS1*)str + len);
1734 assert(maxchar < 128);
1735 }
1736#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001737 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001738 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 }
1740 case PyUnicode_2BYTE_KIND: {
1741 Py_UCS2 *start = (Py_UCS2 *)data + index;
1742 Py_UCS2 *ucs2 = start;
1743 assert(index <= PyUnicode_GET_LENGTH(unicode));
1744
Victor Stinner184252a2012-06-16 02:57:41 +02001745 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001746 *ucs2 = (Py_UCS2)*str;
1747
1748 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001749 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 }
1751 default: {
1752 Py_UCS4 *start = (Py_UCS4 *)data + index;
1753 Py_UCS4 *ucs4 = start;
1754 assert(kind == PyUnicode_4BYTE_KIND);
1755 assert(index <= PyUnicode_GET_LENGTH(unicode));
1756
Victor Stinner184252a2012-06-16 02:57:41 +02001757 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001758 *ucs4 = (Py_UCS4)*str;
1759
1760 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001761 }
1762 }
1763}
1764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765static PyObject*
1766get_latin1_char(unsigned char ch)
1767{
Victor Stinnera464fc12011-10-02 20:39:30 +02001768 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001770 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001771 if (!unicode)
1772 return NULL;
1773 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001774 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 unicode_latin1[ch] = unicode;
1776 }
1777 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001778 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001779}
1780
Victor Stinner985a82a2014-01-03 12:53:47 +01001781static PyObject*
1782unicode_char(Py_UCS4 ch)
1783{
1784 PyObject *unicode;
1785
1786 assert(ch <= MAX_UNICODE);
1787
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001788 if (ch < 256)
1789 return get_latin1_char(ch);
1790
Victor Stinner985a82a2014-01-03 12:53:47 +01001791 unicode = PyUnicode_New(1, ch);
1792 if (unicode == NULL)
1793 return NULL;
1794 switch (PyUnicode_KIND(unicode)) {
1795 case PyUnicode_1BYTE_KIND:
1796 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1797 break;
1798 case PyUnicode_2BYTE_KIND:
1799 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1800 break;
1801 default:
1802 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1803 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1804 }
1805 assert(_PyUnicode_CheckConsistency(unicode, 1));
1806 return unicode;
1807}
1808
Alexander Belopolsky40018472011-02-26 01:02:56 +00001809PyObject *
1810PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001811{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001812 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813 Py_UCS4 maxchar = 0;
1814 Py_ssize_t num_surrogates;
1815
1816 if (u == NULL)
1817 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001818
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001819 /* If the Unicode data is known at construction time, we can apply
1820 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001821
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001822 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001823 if (size == 0)
1824 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001826 /* Single character Unicode objects in the Latin-1 range are
1827 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001828 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001829 return get_latin1_char((unsigned char)*u);
1830
1831 /* If not empty and not single character, copy the Unicode data
1832 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001833 if (find_maxchar_surrogates(u, u + size,
1834 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001835 return NULL;
1836
Victor Stinner8faf8212011-12-08 22:14:11 +01001837 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001838 if (!unicode)
1839 return NULL;
1840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001841 switch (PyUnicode_KIND(unicode)) {
1842 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001843 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001844 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1845 break;
1846 case PyUnicode_2BYTE_KIND:
1847#if Py_UNICODE_SIZE == 2
1848 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1849#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001850 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001851 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1852#endif
1853 break;
1854 case PyUnicode_4BYTE_KIND:
1855#if SIZEOF_WCHAR_T == 2
1856 /* This is the only case which has to process surrogates, thus
1857 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001858 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001859#else
1860 assert(num_surrogates == 0);
1861 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1862#endif
1863 break;
1864 default:
1865 assert(0 && "Impossible state");
1866 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001867
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001868 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001869}
1870
Alexander Belopolsky40018472011-02-26 01:02:56 +00001871PyObject *
1872PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001873{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001874 if (size < 0) {
1875 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001877 return NULL;
1878 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001879 if (u != NULL)
1880 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1881 else
1882 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001883}
1884
Alexander Belopolsky40018472011-02-26 01:02:56 +00001885PyObject *
1886PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001887{
1888 size_t size = strlen(u);
1889 if (size > PY_SSIZE_T_MAX) {
1890 PyErr_SetString(PyExc_OverflowError, "input too long");
1891 return NULL;
1892 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001893 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001894}
1895
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001896PyObject *
1897_PyUnicode_FromId(_Py_Identifier *id)
1898{
1899 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001900 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1901 strlen(id->string),
1902 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001903 if (!id->object)
1904 return NULL;
1905 PyUnicode_InternInPlace(&id->object);
1906 assert(!id->next);
1907 id->next = static_strings;
1908 static_strings = id;
1909 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001910 return id->object;
1911}
1912
1913void
1914_PyUnicode_ClearStaticStrings()
1915{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001916 _Py_Identifier *tmp, *s = static_strings;
1917 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001918 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001919 tmp = s->next;
1920 s->next = NULL;
1921 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001922 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001923 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001924}
1925
Benjamin Peterson0df54292012-03-26 14:50:32 -04001926/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001927
Victor Stinnerd3f08822012-05-29 12:57:52 +02001928PyObject*
1929_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001930{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001931 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001932 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001933 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001934#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001935 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001936#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001937 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001938 }
Victor Stinner785938e2011-12-11 20:09:03 +01001939 unicode = PyUnicode_New(size, 127);
1940 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001941 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001942 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1943 assert(_PyUnicode_CheckConsistency(unicode, 1));
1944 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001945}
1946
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001947static Py_UCS4
1948kind_maxchar_limit(unsigned int kind)
1949{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001950 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001951 case PyUnicode_1BYTE_KIND:
1952 return 0x80;
1953 case PyUnicode_2BYTE_KIND:
1954 return 0x100;
1955 case PyUnicode_4BYTE_KIND:
1956 return 0x10000;
1957 default:
1958 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001959 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001960 }
1961}
1962
Victor Stinnere6abb482012-05-02 01:15:40 +02001963Py_LOCAL_INLINE(Py_UCS4)
1964align_maxchar(Py_UCS4 maxchar)
1965{
1966 if (maxchar <= 127)
1967 return 127;
1968 else if (maxchar <= 255)
1969 return 255;
1970 else if (maxchar <= 65535)
1971 return 65535;
1972 else
1973 return MAX_UNICODE;
1974}
1975
Victor Stinner702c7342011-10-05 13:50:52 +02001976static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001977_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001980 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001981
Serhiy Storchaka678db842013-01-26 12:16:36 +02001982 if (size == 0)
1983 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001984 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001985 if (size == 1)
1986 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001987
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001988 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001989 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990 if (!res)
1991 return NULL;
1992 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001993 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001995}
1996
Victor Stinnere57b1c02011-09-28 22:20:48 +02001997static PyObject*
1998_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999{
2000 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002001 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002
Serhiy Storchaka678db842013-01-26 12:16:36 +02002003 if (size == 0)
2004 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002005 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002006 if (size == 1)
2007 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002008
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002009 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002010 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002011 if (!res)
2012 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002013 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002015 else {
2016 _PyUnicode_CONVERT_BYTES(
2017 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2018 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002019 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 return res;
2021}
2022
Victor Stinnere57b1c02011-09-28 22:20:48 +02002023static PyObject*
2024_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025{
2026 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002027 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002028
Serhiy Storchaka678db842013-01-26 12:16:36 +02002029 if (size == 0)
2030 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002031 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002032 if (size == 1)
2033 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002034
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002035 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002036 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 if (!res)
2038 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002039 if (max_char < 256)
2040 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2041 PyUnicode_1BYTE_DATA(res));
2042 else if (max_char < 0x10000)
2043 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2044 PyUnicode_2BYTE_DATA(res));
2045 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002046 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002047 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 return res;
2049}
2050
2051PyObject*
2052PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2053{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002054 if (size < 0) {
2055 PyErr_SetString(PyExc_ValueError, "size must be positive");
2056 return NULL;
2057 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002058 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002060 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002062 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002064 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002065 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002066 PyErr_SetString(PyExc_SystemError, "invalid kind");
2067 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002068 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002069}
2070
Victor Stinnerece58de2012-04-23 23:36:38 +02002071Py_UCS4
2072_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2073{
2074 enum PyUnicode_Kind kind;
2075 void *startptr, *endptr;
2076
2077 assert(PyUnicode_IS_READY(unicode));
2078 assert(0 <= start);
2079 assert(end <= PyUnicode_GET_LENGTH(unicode));
2080 assert(start <= end);
2081
2082 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2083 return PyUnicode_MAX_CHAR_VALUE(unicode);
2084
2085 if (start == end)
2086 return 127;
2087
Victor Stinner94d558b2012-04-27 22:26:58 +02002088 if (PyUnicode_IS_ASCII(unicode))
2089 return 127;
2090
Victor Stinnerece58de2012-04-23 23:36:38 +02002091 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002092 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002093 endptr = (char *)startptr + end * kind;
2094 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002095 switch(kind) {
2096 case PyUnicode_1BYTE_KIND:
2097 return ucs1lib_find_max_char(startptr, endptr);
2098 case PyUnicode_2BYTE_KIND:
2099 return ucs2lib_find_max_char(startptr, endptr);
2100 case PyUnicode_4BYTE_KIND:
2101 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002102 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002103 assert(0);
2104 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002105 }
2106}
2107
Victor Stinner25a4b292011-10-06 12:31:55 +02002108/* Ensure that a string uses the most efficient storage, if it is not the
2109 case: create a new string with of the right kind. Write NULL into *p_unicode
2110 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002111static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002112unicode_adjust_maxchar(PyObject **p_unicode)
2113{
2114 PyObject *unicode, *copy;
2115 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002116 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002117 unsigned int kind;
2118
2119 assert(p_unicode != NULL);
2120 unicode = *p_unicode;
2121 assert(PyUnicode_IS_READY(unicode));
2122 if (PyUnicode_IS_ASCII(unicode))
2123 return;
2124
2125 len = PyUnicode_GET_LENGTH(unicode);
2126 kind = PyUnicode_KIND(unicode);
2127 if (kind == PyUnicode_1BYTE_KIND) {
2128 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002129 max_char = ucs1lib_find_max_char(u, u + len);
2130 if (max_char >= 128)
2131 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002132 }
2133 else if (kind == PyUnicode_2BYTE_KIND) {
2134 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002135 max_char = ucs2lib_find_max_char(u, u + len);
2136 if (max_char >= 256)
2137 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 }
2139 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002140 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002141 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002142 max_char = ucs4lib_find_max_char(u, u + len);
2143 if (max_char >= 0x10000)
2144 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002145 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002146 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002147 if (copy != NULL)
2148 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002149 Py_DECREF(unicode);
2150 *p_unicode = copy;
2151}
2152
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002154_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002155{
Victor Stinner87af4f22011-11-21 23:03:47 +01002156 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002158
Victor Stinner034f6cf2011-09-30 02:26:44 +02002159 if (!PyUnicode_Check(unicode)) {
2160 PyErr_BadInternalCall();
2161 return NULL;
2162 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002163 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002164 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002165
Victor Stinner87af4f22011-11-21 23:03:47 +01002166 length = PyUnicode_GET_LENGTH(unicode);
2167 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002168 if (!copy)
2169 return NULL;
2170 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2171
Victor Stinner87af4f22011-11-21 23:03:47 +01002172 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2173 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002174 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002175 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002176}
2177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178
Victor Stinnerbc603d12011-10-02 01:00:40 +02002179/* Widen Unicode objects to larger buffers. Don't write terminating null
2180 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002181
2182void*
2183_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2184{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002185 Py_ssize_t len;
2186 void *result;
2187 unsigned int skind;
2188
Benjamin Petersonbac79492012-01-14 13:34:47 -05002189 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002190 return NULL;
2191
2192 len = PyUnicode_GET_LENGTH(s);
2193 skind = PyUnicode_KIND(s);
2194 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002195 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002196 return NULL;
2197 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002198 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002200 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002201 if (!result)
2202 return PyErr_NoMemory();
2203 assert(skind == PyUnicode_1BYTE_KIND);
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS1, Py_UCS2,
2206 PyUnicode_1BYTE_DATA(s),
2207 PyUnicode_1BYTE_DATA(s) + len,
2208 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002211 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002212 if (!result)
2213 return PyErr_NoMemory();
2214 if (skind == PyUnicode_2BYTE_KIND) {
2215 _PyUnicode_CONVERT_BYTES(
2216 Py_UCS2, Py_UCS4,
2217 PyUnicode_2BYTE_DATA(s),
2218 PyUnicode_2BYTE_DATA(s) + len,
2219 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002221 else {
2222 assert(skind == PyUnicode_1BYTE_KIND);
2223 _PyUnicode_CONVERT_BYTES(
2224 Py_UCS1, Py_UCS4,
2225 PyUnicode_1BYTE_DATA(s),
2226 PyUnicode_1BYTE_DATA(s) + len,
2227 result);
2228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002230 default:
2231 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 }
Victor Stinner01698042011-10-04 00:04:26 +02002233 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 return NULL;
2235}
2236
2237static Py_UCS4*
2238as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2239 int copy_null)
2240{
2241 int kind;
2242 void *data;
2243 Py_ssize_t len, targetlen;
2244 if (PyUnicode_READY(string) == -1)
2245 return NULL;
2246 kind = PyUnicode_KIND(string);
2247 data = PyUnicode_DATA(string);
2248 len = PyUnicode_GET_LENGTH(string);
2249 targetlen = len;
2250 if (copy_null)
2251 targetlen++;
2252 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002253 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002254 if (!target) {
2255 PyErr_NoMemory();
2256 return NULL;
2257 }
2258 }
2259 else {
2260 if (targetsize < targetlen) {
2261 PyErr_Format(PyExc_SystemError,
2262 "string is longer than the buffer");
2263 if (copy_null && 0 < targetsize)
2264 target[0] = 0;
2265 return NULL;
2266 }
2267 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002268 if (kind == PyUnicode_1BYTE_KIND) {
2269 Py_UCS1 *start = (Py_UCS1 *) data;
2270 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002272 else if (kind == PyUnicode_2BYTE_KIND) {
2273 Py_UCS2 *start = (Py_UCS2 *) data;
2274 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2275 }
2276 else {
2277 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002279 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002280 if (copy_null)
2281 target[len] = 0;
2282 return target;
2283}
2284
2285Py_UCS4*
2286PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2287 int copy_null)
2288{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002289 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002290 PyErr_BadInternalCall();
2291 return NULL;
2292 }
2293 return as_ucs4(string, target, targetsize, copy_null);
2294}
2295
2296Py_UCS4*
2297PyUnicode_AsUCS4Copy(PyObject *string)
2298{
2299 return as_ucs4(string, NULL, 0, 1);
2300}
2301
2302#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002303
Alexander Belopolsky40018472011-02-26 01:02:56 +00002304PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002305PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002306{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002307 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002308 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002309 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002310 PyErr_BadInternalCall();
2311 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002312 }
2313
Martin v. Löwis790465f2008-04-05 20:41:37 +00002314 if (size == -1) {
2315 size = wcslen(w);
2316 }
2317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002318 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002319}
2320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002321#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002322
Victor Stinner15a11362012-10-06 23:48:20 +02002323/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002324 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2325 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2326#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002327
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002328static int
2329unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2330 Py_ssize_t width, Py_ssize_t precision)
2331{
2332 Py_ssize_t length, fill, arglen;
2333 Py_UCS4 maxchar;
2334
2335 if (PyUnicode_READY(str) == -1)
2336 return -1;
2337
2338 length = PyUnicode_GET_LENGTH(str);
2339 if ((precision == -1 || precision >= length)
2340 && width <= length)
2341 return _PyUnicodeWriter_WriteStr(writer, str);
2342
2343 if (precision != -1)
2344 length = Py_MIN(precision, length);
2345
2346 arglen = Py_MAX(length, width);
2347 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2348 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2349 else
2350 maxchar = writer->maxchar;
2351
2352 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2353 return -1;
2354
2355 if (width > length) {
2356 fill = width - length;
2357 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2358 return -1;
2359 writer->pos += fill;
2360 }
2361
2362 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2363 str, 0, length);
2364 writer->pos += length;
2365 return 0;
2366}
2367
2368static int
2369unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2370 Py_ssize_t width, Py_ssize_t precision)
2371{
2372 /* UTF-8 */
2373 Py_ssize_t length;
2374 PyObject *unicode;
2375 int res;
2376
2377 length = strlen(str);
2378 if (precision != -1)
2379 length = Py_MIN(length, precision);
2380 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2381 if (unicode == NULL)
2382 return -1;
2383
2384 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2385 Py_DECREF(unicode);
2386 return res;
2387}
2388
Victor Stinner96865452011-03-01 23:44:09 +00002389static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002390unicode_fromformat_arg(_PyUnicodeWriter *writer,
2391 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002392{
Victor Stinnere215d962012-10-06 23:03:36 +02002393 const char *p;
2394 Py_ssize_t len;
2395 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002396 Py_ssize_t width;
2397 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002398 int longflag;
2399 int longlongflag;
2400 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002401 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002402
2403 p = f;
2404 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002405 zeropad = 0;
2406 if (*f == '0') {
2407 zeropad = 1;
2408 f++;
2409 }
Victor Stinner96865452011-03-01 23:44:09 +00002410
2411 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002412 width = -1;
2413 if (Py_ISDIGIT((unsigned)*f)) {
2414 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002415 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002416 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002417 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002418 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002419 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002420 return NULL;
2421 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002422 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002423 f++;
2424 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002425 }
2426 precision = -1;
2427 if (*f == '.') {
2428 f++;
2429 if (Py_ISDIGIT((unsigned)*f)) {
2430 precision = (*f - '0');
2431 f++;
2432 while (Py_ISDIGIT((unsigned)*f)) {
2433 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2434 PyErr_SetString(PyExc_ValueError,
2435 "precision too big");
2436 return NULL;
2437 }
2438 precision = (precision * 10) + (*f - '0');
2439 f++;
2440 }
2441 }
Victor Stinner96865452011-03-01 23:44:09 +00002442 if (*f == '%') {
2443 /* "%.3%s" => f points to "3" */
2444 f--;
2445 }
2446 }
2447 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002448 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002449 f--;
2450 }
Victor Stinner96865452011-03-01 23:44:09 +00002451
2452 /* Handle %ld, %lu, %lld and %llu. */
2453 longflag = 0;
2454 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002455 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002456 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002457 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002458 longflag = 1;
2459 ++f;
2460 }
2461#ifdef HAVE_LONG_LONG
2462 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002463 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002464 longlongflag = 1;
2465 f += 2;
2466 }
2467#endif
2468 }
2469 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002470 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002471 size_tflag = 1;
2472 ++f;
2473 }
Victor Stinnere215d962012-10-06 23:03:36 +02002474
2475 if (f[1] == '\0')
2476 writer->overallocate = 0;
2477
2478 switch (*f) {
2479 case 'c':
2480 {
2481 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002482 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002483 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002484 "character argument not in range(0x110000)");
2485 return NULL;
2486 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002487 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002488 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002489 break;
2490 }
2491
2492 case 'i':
2493 case 'd':
2494 case 'u':
2495 case 'x':
2496 {
2497 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002498 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002499 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002500
2501 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002502 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002503 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002504 va_arg(*vargs, unsigned long));
2505#ifdef HAVE_LONG_LONG
2506 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002507 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002508 va_arg(*vargs, unsigned PY_LONG_LONG));
2509#endif
2510 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002511 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002512 va_arg(*vargs, size_t));
2513 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002514 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002515 va_arg(*vargs, unsigned int));
2516 }
2517 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002518 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002519 }
2520 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002521 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002522 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002523 va_arg(*vargs, long));
2524#ifdef HAVE_LONG_LONG
2525 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002526 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002527 va_arg(*vargs, PY_LONG_LONG));
2528#endif
2529 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002530 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002531 va_arg(*vargs, Py_ssize_t));
2532 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002533 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002534 va_arg(*vargs, int));
2535 }
2536 assert(len >= 0);
2537
Victor Stinnere215d962012-10-06 23:03:36 +02002538 if (precision < len)
2539 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002540
2541 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002542 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2543 return NULL;
2544
Victor Stinnere215d962012-10-06 23:03:36 +02002545 if (width > precision) {
2546 Py_UCS4 fillchar;
2547 fill = width - precision;
2548 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002549 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2550 return NULL;
2551 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002552 }
Victor Stinner15a11362012-10-06 23:48:20 +02002553 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002554 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002555 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2556 return NULL;
2557 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002558 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002559
Victor Stinner4a587072013-11-19 12:54:53 +01002560 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2561 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002562 break;
2563 }
2564
2565 case 'p':
2566 {
2567 char number[MAX_LONG_LONG_CHARS];
2568
2569 len = sprintf(number, "%p", va_arg(*vargs, void*));
2570 assert(len >= 0);
2571
2572 /* %p is ill-defined: ensure leading 0x. */
2573 if (number[1] == 'X')
2574 number[1] = 'x';
2575 else if (number[1] != 'x') {
2576 memmove(number + 2, number,
2577 strlen(number) + 1);
2578 number[0] = '0';
2579 number[1] = 'x';
2580 len += 2;
2581 }
2582
Victor Stinner4a587072013-11-19 12:54:53 +01002583 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002584 return NULL;
2585 break;
2586 }
2587
2588 case 's':
2589 {
2590 /* UTF-8 */
2591 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002592 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002593 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002594 break;
2595 }
2596
2597 case 'U':
2598 {
2599 PyObject *obj = va_arg(*vargs, PyObject *);
2600 assert(obj && _PyUnicode_CHECK(obj));
2601
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002602 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002603 return NULL;
2604 break;
2605 }
2606
2607 case 'V':
2608 {
2609 PyObject *obj = va_arg(*vargs, PyObject *);
2610 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002611 if (obj) {
2612 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002613 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002614 return NULL;
2615 }
2616 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002617 assert(str != NULL);
2618 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002619 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002620 }
2621 break;
2622 }
2623
2624 case 'S':
2625 {
2626 PyObject *obj = va_arg(*vargs, PyObject *);
2627 PyObject *str;
2628 assert(obj);
2629 str = PyObject_Str(obj);
2630 if (!str)
2631 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002632 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002633 Py_DECREF(str);
2634 return NULL;
2635 }
2636 Py_DECREF(str);
2637 break;
2638 }
2639
2640 case 'R':
2641 {
2642 PyObject *obj = va_arg(*vargs, PyObject *);
2643 PyObject *repr;
2644 assert(obj);
2645 repr = PyObject_Repr(obj);
2646 if (!repr)
2647 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002648 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002649 Py_DECREF(repr);
2650 return NULL;
2651 }
2652 Py_DECREF(repr);
2653 break;
2654 }
2655
2656 case 'A':
2657 {
2658 PyObject *obj = va_arg(*vargs, PyObject *);
2659 PyObject *ascii;
2660 assert(obj);
2661 ascii = PyObject_ASCII(obj);
2662 if (!ascii)
2663 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002664 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002665 Py_DECREF(ascii);
2666 return NULL;
2667 }
2668 Py_DECREF(ascii);
2669 break;
2670 }
2671
2672 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002673 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002674 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002675 break;
2676
2677 default:
2678 /* if we stumble upon an unknown formatting code, copy the rest
2679 of the format string to the output string. (we cannot just
2680 skip the code, since there's no way to know what's in the
2681 argument list) */
2682 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002683 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002684 return NULL;
2685 f = p+len;
2686 return f;
2687 }
2688
2689 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002690 return f;
2691}
2692
Walter Dörwaldd2034312007-05-18 16:29:38 +00002693PyObject *
2694PyUnicode_FromFormatV(const char *format, va_list vargs)
2695{
Victor Stinnere215d962012-10-06 23:03:36 +02002696 va_list vargs2;
2697 const char *f;
2698 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002699
Victor Stinner8f674cc2013-04-17 23:02:17 +02002700 _PyUnicodeWriter_Init(&writer);
2701 writer.min_length = strlen(format) + 100;
2702 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002703
2704 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2705 Copy it to be able to pass a reference to a subfunction. */
2706 Py_VA_COPY(vargs2, vargs);
2707
2708 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002709 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002710 f = unicode_fromformat_arg(&writer, f, &vargs2);
2711 if (f == NULL)
2712 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002713 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002714 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002715 const char *p;
2716 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002717
Victor Stinnere215d962012-10-06 23:03:36 +02002718 p = f;
2719 do
2720 {
2721 if ((unsigned char)*p > 127) {
2722 PyErr_Format(PyExc_ValueError,
2723 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2724 "string, got a non-ASCII byte: 0x%02x",
2725 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002726 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002727 }
2728 p++;
2729 }
2730 while (*p != '\0' && *p != '%');
2731 len = p - f;
2732
2733 if (*p == '\0')
2734 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002735
2736 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002737 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002738
2739 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002740 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 }
Victor Stinnere215d962012-10-06 23:03:36 +02002742 return _PyUnicodeWriter_Finish(&writer);
2743
2744 fail:
2745 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002746 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002747}
2748
Walter Dörwaldd2034312007-05-18 16:29:38 +00002749PyObject *
2750PyUnicode_FromFormat(const char *format, ...)
2751{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002752 PyObject* ret;
2753 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002754
2755#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002756 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002757#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002758 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002759#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002760 ret = PyUnicode_FromFormatV(format, vargs);
2761 va_end(vargs);
2762 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002763}
2764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002765#ifdef HAVE_WCHAR_H
2766
Victor Stinner5593d8a2010-10-02 11:11:27 +00002767/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2768 convert a Unicode object to a wide character string.
2769
Victor Stinnerd88d9832011-09-06 02:00:05 +02002770 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002771 character) required to convert the unicode object. Ignore size argument.
2772
Victor Stinnerd88d9832011-09-06 02:00:05 +02002773 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002774 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002775 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002776static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002777unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002778 wchar_t *w,
2779 Py_ssize_t size)
2780{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002782 const wchar_t *wstr;
2783
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002784 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002785 if (wstr == NULL)
2786 return -1;
2787
Victor Stinner5593d8a2010-10-02 11:11:27 +00002788 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002789 if (size > res)
2790 size = res + 1;
2791 else
2792 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 return res;
2795 }
2796 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002797 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002798}
2799
2800Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002801PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002802 wchar_t *w,
2803 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002804{
2805 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002806 PyErr_BadInternalCall();
2807 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002808 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002809 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002810}
2811
Victor Stinner137c34c2010-09-29 10:25:54 +00002812wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002813PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002814 Py_ssize_t *size)
2815{
2816 wchar_t* buffer;
2817 Py_ssize_t buflen;
2818
2819 if (unicode == NULL) {
2820 PyErr_BadInternalCall();
2821 return NULL;
2822 }
2823
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002824 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 if (buflen == -1)
2826 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002827 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002828 if (buffer == NULL) {
2829 PyErr_NoMemory();
2830 return NULL;
2831 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002832 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002833 if (buflen == -1) {
2834 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002836 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002837 if (size != NULL)
2838 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002839 return buffer;
2840}
2841
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002842#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002843
Alexander Belopolsky40018472011-02-26 01:02:56 +00002844PyObject *
2845PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002846{
Victor Stinner8faf8212011-12-08 22:14:11 +01002847 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002848 PyErr_SetString(PyExc_ValueError,
2849 "chr() arg not in range(0x110000)");
2850 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002851 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002852
Victor Stinner985a82a2014-01-03 12:53:47 +01002853 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002854}
2855
Alexander Belopolsky40018472011-02-26 01:02:56 +00002856PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002857PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002858{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002859 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002861 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002862 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002863 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002864 Py_INCREF(obj);
2865 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002866 }
2867 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002868 /* For a Unicode subtype that's not a Unicode object,
2869 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002870 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002871 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002872 PyErr_Format(PyExc_TypeError,
2873 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002874 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002875 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002876}
2877
Alexander Belopolsky40018472011-02-26 01:02:56 +00002878PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002879PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002880 const char *encoding,
2881 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002882{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002883 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002884 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002885
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002887 PyErr_BadInternalCall();
2888 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002889 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002890
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002891 /* Decoding bytes objects is the most common case and should be fast */
2892 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002893 if (PyBytes_GET_SIZE(obj) == 0)
2894 _Py_RETURN_UNICODE_EMPTY();
2895 v = PyUnicode_Decode(
2896 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2897 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002898 return v;
2899 }
2900
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002901 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002902 PyErr_SetString(PyExc_TypeError,
2903 "decoding str is not supported");
2904 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002905 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002906
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002907 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2908 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2909 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002910 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002911 Py_TYPE(obj)->tp_name);
2912 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002913 }
Tim Petersced69f82003-09-16 20:30:58 +00002914
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002915 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002916 PyBuffer_Release(&buffer);
2917 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002918 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002919
Serhiy Storchaka05997252013-01-26 12:14:02 +02002920 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002921 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002922 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002923}
2924
Victor Stinner600d3be2010-06-10 12:00:55 +00002925/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002926 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2927 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002928int
2929_Py_normalize_encoding(const char *encoding,
2930 char *lower,
2931 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002932{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002933 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002934 char *l;
2935 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002936
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002937 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002938 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002939 if (lower_len < 6)
2940 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002941 strcpy(lower, "utf-8");
2942 return 1;
2943 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002944 e = encoding;
2945 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002946 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002947 while (*e) {
2948 if (l == l_end)
2949 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002950 if (Py_ISUPPER(*e)) {
2951 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002952 }
2953 else if (*e == '_') {
2954 *l++ = '-';
2955 e++;
2956 }
2957 else {
2958 *l++ = *e++;
2959 }
2960 }
2961 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002962 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002963}
2964
Alexander Belopolsky40018472011-02-26 01:02:56 +00002965PyObject *
2966PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002967 Py_ssize_t size,
2968 const char *encoding,
2969 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002970{
2971 PyObject *buffer = NULL, *unicode;
2972 Py_buffer info;
2973 char lower[11]; /* Enough for any encoding shortcut */
2974
Fred Drakee4315f52000-05-09 19:53:39 +00002975 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002976 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002977 if ((strcmp(lower, "utf-8") == 0) ||
2978 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002979 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002980 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002981 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01002982 (strcmp(lower, "iso-8859-1") == 0) ||
2983 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002984 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002985#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002986 else if (strcmp(lower, "mbcs") == 0)
2987 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002988#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002989 else if (strcmp(lower, "ascii") == 0)
2990 return PyUnicode_DecodeASCII(s, size, errors);
2991 else if (strcmp(lower, "utf-16") == 0)
2992 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2993 else if (strcmp(lower, "utf-32") == 0)
2994 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002996
2997 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002998 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002999 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003000 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003001 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003002 if (buffer == NULL)
3003 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003004 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003005 if (unicode == NULL)
3006 goto onError;
3007 if (!PyUnicode_Check(unicode)) {
3008 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003009 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3010 "use codecs.decode() to decode to arbitrary types",
3011 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003012 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003013 Py_DECREF(unicode);
3014 goto onError;
3015 }
3016 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003017 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003018
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 Py_XDECREF(buffer);
3021 return NULL;
3022}
3023
Alexander Belopolsky40018472011-02-26 01:02:56 +00003024PyObject *
3025PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003026 const char *encoding,
3027 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003028{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003029 if (!PyUnicode_Check(unicode)) {
3030 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003031 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003032 }
3033
3034 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003035 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003036
3037 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003038 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003039}
3040
Alexander Belopolsky40018472011-02-26 01:02:56 +00003041PyObject *
3042PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003043 const char *encoding,
3044 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003045{
3046 PyObject *v;
3047
3048 if (!PyUnicode_Check(unicode)) {
3049 PyErr_BadArgument();
3050 goto onError;
3051 }
3052
3053 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003054 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003055
3056 /* Decode via the codec registry */
3057 v = PyCodec_Decode(unicode, encoding, errors);
3058 if (v == NULL)
3059 goto onError;
3060 if (!PyUnicode_Check(v)) {
3061 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003062 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3063 "use codecs.decode() to decode to arbitrary types",
3064 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003065 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003066 Py_DECREF(v);
3067 goto onError;
3068 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003069 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003070
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003072 return NULL;
3073}
3074
Alexander Belopolsky40018472011-02-26 01:02:56 +00003075PyObject *
3076PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003077 Py_ssize_t size,
3078 const char *encoding,
3079 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080{
3081 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003082
Guido van Rossumd57fd912000-03-10 22:53:23 +00003083 unicode = PyUnicode_FromUnicode(s, size);
3084 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3087 Py_DECREF(unicode);
3088 return v;
3089}
3090
Alexander Belopolsky40018472011-02-26 01:02:56 +00003091PyObject *
3092PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003093 const char *encoding,
3094 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003095{
3096 PyObject *v;
3097
3098 if (!PyUnicode_Check(unicode)) {
3099 PyErr_BadArgument();
3100 goto onError;
3101 }
3102
3103 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003104 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003105
3106 /* Encode via the codec registry */
3107 v = PyCodec_Encode(unicode, encoding, errors);
3108 if (v == NULL)
3109 goto onError;
3110 return v;
3111
Benjamin Peterson29060642009-01-31 22:14:21 +00003112 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003113 return NULL;
3114}
3115
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003116static size_t
3117wcstombs_errorpos(const wchar_t *wstr)
3118{
3119 size_t len;
3120#if SIZEOF_WCHAR_T == 2
3121 wchar_t buf[3];
3122#else
3123 wchar_t buf[2];
3124#endif
3125 char outbuf[MB_LEN_MAX];
3126 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003127
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003128#if SIZEOF_WCHAR_T == 2
3129 buf[2] = 0;
3130#else
3131 buf[1] = 0;
3132#endif
3133 start = wstr;
3134 while (*wstr != L'\0')
3135 {
3136 previous = wstr;
3137#if SIZEOF_WCHAR_T == 2
3138 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3139 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3140 {
3141 buf[0] = wstr[0];
3142 buf[1] = wstr[1];
3143 wstr += 2;
3144 }
3145 else {
3146 buf[0] = *wstr;
3147 buf[1] = 0;
3148 wstr++;
3149 }
3150#else
3151 buf[0] = *wstr;
3152 wstr++;
3153#endif
3154 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003155 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003156 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003157 }
3158
3159 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003160 return 0;
3161}
3162
Victor Stinner1b579672011-12-17 05:47:23 +01003163static int
3164locale_error_handler(const char *errors, int *surrogateescape)
3165{
3166 if (errors == NULL) {
3167 *surrogateescape = 0;
3168 return 0;
3169 }
3170
3171 if (strcmp(errors, "strict") == 0) {
3172 *surrogateescape = 0;
3173 return 0;
3174 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003175 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003176 *surrogateescape = 1;
3177 return 0;
3178 }
3179 PyErr_Format(PyExc_ValueError,
3180 "only 'strict' and 'surrogateescape' error handlers "
3181 "are supported, not '%s'",
3182 errors);
3183 return -1;
3184}
3185
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003186PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003187PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003188{
3189 Py_ssize_t wlen, wlen2;
3190 wchar_t *wstr;
3191 PyObject *bytes = NULL;
3192 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003193 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003194 PyObject *exc;
3195 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003196 int surrogateescape;
3197
3198 if (locale_error_handler(errors, &surrogateescape) < 0)
3199 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003200
3201 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3202 if (wstr == NULL)
3203 return NULL;
3204
3205 wlen2 = wcslen(wstr);
3206 if (wlen2 != wlen) {
3207 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003208 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003209 return NULL;
3210 }
3211
3212 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003213 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003214 char *str;
3215
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003216 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003217 if (str == NULL) {
3218 if (error_pos == (size_t)-1) {
3219 PyErr_NoMemory();
3220 PyMem_Free(wstr);
3221 return NULL;
3222 }
3223 else {
3224 goto encode_error;
3225 }
3226 }
3227 PyMem_Free(wstr);
3228
3229 bytes = PyBytes_FromString(str);
3230 PyMem_Free(str);
3231 }
3232 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003233 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003234 size_t len, len2;
3235
3236 len = wcstombs(NULL, wstr, 0);
3237 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003238 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003239 goto encode_error;
3240 }
3241
3242 bytes = PyBytes_FromStringAndSize(NULL, len);
3243 if (bytes == NULL) {
3244 PyMem_Free(wstr);
3245 return NULL;
3246 }
3247
3248 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3249 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003250 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003251 goto encode_error;
3252 }
3253 PyMem_Free(wstr);
3254 }
3255 return bytes;
3256
3257encode_error:
3258 errmsg = strerror(errno);
3259 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003260
3261 if (error_pos == (size_t)-1)
3262 error_pos = wcstombs_errorpos(wstr);
3263
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003264 PyMem_Free(wstr);
3265 Py_XDECREF(bytes);
3266
Victor Stinner2f197072011-12-17 07:08:30 +01003267 if (errmsg != NULL) {
3268 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003269 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003270 if (wstr != NULL) {
3271 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003272 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003273 } else
3274 errmsg = NULL;
3275 }
3276 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003277 reason = PyUnicode_FromString(
3278 "wcstombs() encountered an unencodable "
3279 "wide character");
3280 if (reason == NULL)
3281 return NULL;
3282
3283 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3284 "locale", unicode,
3285 (Py_ssize_t)error_pos,
3286 (Py_ssize_t)(error_pos+1),
3287 reason);
3288 Py_DECREF(reason);
3289 if (exc != NULL) {
3290 PyCodec_StrictErrors(exc);
3291 Py_XDECREF(exc);
3292 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 return NULL;
3294}
3295
Victor Stinnerad158722010-10-27 00:25:46 +00003296PyObject *
3297PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003298{
Victor Stinner99b95382011-07-04 14:23:54 +02003299#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003300 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003301#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003303#else
Victor Stinner793b5312011-04-27 00:24:21 +02003304 PyInterpreterState *interp = PyThreadState_GET()->interp;
3305 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3306 cannot use it to encode and decode filenames before it is loaded. Load
3307 the Python codec requires to encode at least its own filename. Use the C
3308 version of the locale codec until the codec registry is initialized and
3309 the Python codec is loaded.
3310
3311 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3312 cannot only rely on it: check also interp->fscodec_initialized for
3313 subinterpreters. */
3314 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003315 return PyUnicode_AsEncodedString(unicode,
3316 Py_FileSystemDefaultEncoding,
3317 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003318 }
3319 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003320 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003321 }
Victor Stinnerad158722010-10-27 00:25:46 +00003322#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003323}
3324
Alexander Belopolsky40018472011-02-26 01:02:56 +00003325PyObject *
3326PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003327 const char *encoding,
3328 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003329{
3330 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003331 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003332
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333 if (!PyUnicode_Check(unicode)) {
3334 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003335 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003336 }
Fred Drakee4315f52000-05-09 19:53:39 +00003337
Fred Drakee4315f52000-05-09 19:53:39 +00003338 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003339 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003340 if ((strcmp(lower, "utf-8") == 0) ||
3341 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003342 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003343 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003344 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003345 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003346 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003347 }
Victor Stinner37296e82010-06-10 13:36:23 +00003348 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003349 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003350 (strcmp(lower, "iso-8859-1") == 0) ||
3351 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003353#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003354 else if (strcmp(lower, "mbcs") == 0)
3355 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003356#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003357 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003358 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003360
3361 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003362 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003363 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003364 return NULL;
3365
3366 /* The normal path */
3367 if (PyBytes_Check(v))
3368 return v;
3369
3370 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003371 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003372 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003373 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003374
3375 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003376 "encoder %s returned bytearray instead of bytes; "
3377 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003378 encoding);
3379 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003380 Py_DECREF(v);
3381 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003382 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003383
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003384 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3385 Py_DECREF(v);
3386 return b;
3387 }
3388
3389 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003390 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3391 "use codecs.encode() to encode to arbitrary types",
3392 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003393 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003394 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003395 return NULL;
3396}
3397
Alexander Belopolsky40018472011-02-26 01:02:56 +00003398PyObject *
3399PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003400 const char *encoding,
3401 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003402{
3403 PyObject *v;
3404
3405 if (!PyUnicode_Check(unicode)) {
3406 PyErr_BadArgument();
3407 goto onError;
3408 }
3409
3410 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003411 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003412
3413 /* Encode via the codec registry */
3414 v = PyCodec_Encode(unicode, encoding, errors);
3415 if (v == NULL)
3416 goto onError;
3417 if (!PyUnicode_Check(v)) {
3418 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003419 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3420 "use codecs.encode() to encode to arbitrary types",
3421 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003422 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003423 Py_DECREF(v);
3424 goto onError;
3425 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003426 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003427
Benjamin Peterson29060642009-01-31 22:14:21 +00003428 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003429 return NULL;
3430}
3431
Victor Stinner2f197072011-12-17 07:08:30 +01003432static size_t
3433mbstowcs_errorpos(const char *str, size_t len)
3434{
3435#ifdef HAVE_MBRTOWC
3436 const char *start = str;
3437 mbstate_t mbs;
3438 size_t converted;
3439 wchar_t ch;
3440
3441 memset(&mbs, 0, sizeof mbs);
3442 while (len)
3443 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003444 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003445 if (converted == 0)
3446 /* Reached end of string */
3447 break;
3448 if (converted == (size_t)-1 || converted == (size_t)-2) {
3449 /* Conversion error or incomplete character */
3450 return str - start;
3451 }
3452 else {
3453 str += converted;
3454 len -= converted;
3455 }
3456 }
3457 /* failed to find the undecodable byte sequence */
3458 return 0;
3459#endif
3460 return 0;
3461}
3462
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003463PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003464PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003465 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003466{
3467 wchar_t smallbuf[256];
3468 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3469 wchar_t *wstr;
3470 size_t wlen, wlen2;
3471 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003472 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003473 size_t error_pos;
3474 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003475 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3476 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003477
3478 if (locale_error_handler(errors, &surrogateescape) < 0)
3479 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003481 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3482 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003483 return NULL;
3484 }
3485
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003486 if (surrogateescape) {
3487 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003488 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003489 if (wstr == NULL) {
3490 if (wlen == (size_t)-1)
3491 PyErr_NoMemory();
3492 else
3493 PyErr_SetFromErrno(PyExc_OSError);
3494 return NULL;
3495 }
3496
3497 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003498 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499 }
3500 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003501 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003502#ifndef HAVE_BROKEN_MBSTOWCS
3503 wlen = mbstowcs(NULL, str, 0);
3504#else
3505 wlen = len;
3506#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003507 if (wlen == (size_t)-1)
3508 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003509 if (wlen+1 <= smallbuf_len) {
3510 wstr = smallbuf;
3511 }
3512 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003513 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003514 if (!wstr)
3515 return PyErr_NoMemory();
3516 }
3517
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003518 wlen2 = mbstowcs(wstr, str, wlen+1);
3519 if (wlen2 == (size_t)-1) {
3520 if (wstr != smallbuf)
3521 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003522 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523 }
3524#ifdef HAVE_BROKEN_MBSTOWCS
3525 assert(wlen2 == wlen);
3526#endif
3527 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3528 if (wstr != smallbuf)
3529 PyMem_Free(wstr);
3530 }
3531 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003532
3533decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003534 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003535 errmsg = strerror(errno);
3536 assert(errmsg != NULL);
3537
3538 error_pos = mbstowcs_errorpos(str, len);
3539 if (errmsg != NULL) {
3540 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003541 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003542 if (wstr != NULL) {
3543 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003544 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003545 }
Victor Stinner2f197072011-12-17 07:08:30 +01003546 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003547 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003548 reason = PyUnicode_FromString(
3549 "mbstowcs() encountered an invalid multibyte sequence");
3550 if (reason == NULL)
3551 return NULL;
3552
3553 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3554 "locale", str, len,
3555 (Py_ssize_t)error_pos,
3556 (Py_ssize_t)(error_pos+1),
3557 reason);
3558 Py_DECREF(reason);
3559 if (exc != NULL) {
3560 PyCodec_StrictErrors(exc);
3561 Py_XDECREF(exc);
3562 }
3563 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003564}
3565
3566PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003567PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003568{
3569 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003570 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003571}
3572
3573
3574PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003575PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003576 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003577 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3578}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003579
Christian Heimes5894ba72007-11-04 11:43:14 +00003580PyObject*
3581PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3582{
Victor Stinner99b95382011-07-04 14:23:54 +02003583#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003584 return PyUnicode_DecodeMBCS(s, size, NULL);
3585#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003586 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003587#else
Victor Stinner793b5312011-04-27 00:24:21 +02003588 PyInterpreterState *interp = PyThreadState_GET()->interp;
3589 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3590 cannot use it to encode and decode filenames before it is loaded. Load
3591 the Python codec requires to encode at least its own filename. Use the C
3592 version of the locale codec until the codec registry is initialized and
3593 the Python codec is loaded.
3594
3595 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3596 cannot only rely on it: check also interp->fscodec_initialized for
3597 subinterpreters. */
3598 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003599 return PyUnicode_Decode(s, size,
3600 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003601 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003602 }
3603 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003604 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003605 }
Victor Stinnerad158722010-10-27 00:25:46 +00003606#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003607}
3608
Martin v. Löwis011e8422009-05-05 04:43:17 +00003609
3610int
3611PyUnicode_FSConverter(PyObject* arg, void* addr)
3612{
3613 PyObject *output = NULL;
3614 Py_ssize_t size;
3615 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003616 if (arg == NULL) {
3617 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003618 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003619 return 1;
3620 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003621 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003622 output = arg;
3623 Py_INCREF(output);
3624 }
3625 else {
3626 arg = PyUnicode_FromObject(arg);
3627 if (!arg)
3628 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003629 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003630 Py_DECREF(arg);
3631 if (!output)
3632 return 0;
3633 if (!PyBytes_Check(output)) {
3634 Py_DECREF(output);
3635 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3636 return 0;
3637 }
3638 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003639 size = PyBytes_GET_SIZE(output);
3640 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003641 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003642 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003643 Py_DECREF(output);
3644 return 0;
3645 }
3646 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003647 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003648}
3649
3650
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003651int
3652PyUnicode_FSDecoder(PyObject* arg, void* addr)
3653{
3654 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003655 if (arg == NULL) {
3656 Py_DECREF(*(PyObject**)addr);
3657 return 1;
3658 }
3659 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003660 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003661 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003662 output = arg;
3663 Py_INCREF(output);
3664 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003665 else if (PyObject_CheckBuffer(arg)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003666 arg = PyBytes_FromObject(arg);
3667 if (!arg)
3668 return 0;
3669 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3670 PyBytes_GET_SIZE(arg));
3671 Py_DECREF(arg);
3672 if (!output)
3673 return 0;
3674 if (!PyUnicode_Check(output)) {
3675 Py_DECREF(output);
3676 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3677 return 0;
3678 }
3679 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003680 else {
3681 PyErr_Format(PyExc_TypeError,
3682 "path should be string or bytes, not %.200s",
3683 Py_TYPE(arg)->tp_name);
3684 return 0;
3685 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003686 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003687 Py_DECREF(output);
3688 return 0;
3689 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003690 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003691 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003692 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003693 Py_DECREF(output);
3694 return 0;
3695 }
3696 *(PyObject**)addr = output;
3697 return Py_CLEANUP_SUPPORTED;
3698}
3699
3700
Martin v. Löwis5b222132007-06-10 09:51:05 +00003701char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003702PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003703{
Christian Heimesf3863112007-11-22 07:46:41 +00003704 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003705
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003706 if (!PyUnicode_Check(unicode)) {
3707 PyErr_BadArgument();
3708 return NULL;
3709 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003710 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003711 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003712
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003713 if (PyUnicode_UTF8(unicode) == NULL) {
3714 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003715 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3716 if (bytes == NULL)
3717 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003718 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3719 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003720 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003721 Py_DECREF(bytes);
3722 return NULL;
3723 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003724 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3725 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3726 PyBytes_AS_STRING(bytes),
3727 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003728 Py_DECREF(bytes);
3729 }
3730
3731 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003732 *psize = PyUnicode_UTF8_LENGTH(unicode);
3733 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003734}
3735
3736char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003737PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003738{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3740}
3741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742Py_UNICODE *
3743PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003745 const unsigned char *one_byte;
3746#if SIZEOF_WCHAR_T == 4
3747 const Py_UCS2 *two_bytes;
3748#else
3749 const Py_UCS4 *four_bytes;
3750 const Py_UCS4 *ucs4_end;
3751 Py_ssize_t num_surrogates;
3752#endif
3753 wchar_t *w;
3754 wchar_t *wchar_end;
3755
3756 if (!PyUnicode_Check(unicode)) {
3757 PyErr_BadArgument();
3758 return NULL;
3759 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003760 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003762 assert(_PyUnicode_KIND(unicode) != 0);
3763 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003765 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003767 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3768 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769 num_surrogates = 0;
3770
3771 for (; four_bytes < ucs4_end; ++four_bytes) {
3772 if (*four_bytes > 0xFFFF)
3773 ++num_surrogates;
3774 }
3775
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3777 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3778 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 PyErr_NoMemory();
3780 return NULL;
3781 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003782 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003783
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003784 w = _PyUnicode_WSTR(unicode);
3785 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3786 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003787 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3788 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003789 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003790 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003791 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3792 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793 }
3794 else
3795 *w = *four_bytes;
3796
3797 if (w > wchar_end) {
3798 assert(0 && "Miscalculated string end");
3799 }
3800 }
3801 *w = 0;
3802#else
3803 /* sizeof(wchar_t) == 4 */
3804 Py_FatalError("Impossible unicode object state, wstr and str "
3805 "should share memory already.");
3806 return NULL;
3807#endif
3808 }
3809 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003810 if ((size_t)_PyUnicode_LENGTH(unicode) >
3811 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3812 PyErr_NoMemory();
3813 return NULL;
3814 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003815 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3816 (_PyUnicode_LENGTH(unicode) + 1));
3817 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818 PyErr_NoMemory();
3819 return NULL;
3820 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003821 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3822 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3823 w = _PyUnicode_WSTR(unicode);
3824 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003825
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003826 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3827 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003828 for (; w < wchar_end; ++one_byte, ++w)
3829 *w = *one_byte;
3830 /* null-terminate the wstr */
3831 *w = 0;
3832 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003833 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 for (; w < wchar_end; ++two_bytes, ++w)
3837 *w = *two_bytes;
3838 /* null-terminate the wstr */
3839 *w = 0;
3840#else
3841 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 PyObject_FREE(_PyUnicode_WSTR(unicode));
3843 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 Py_FatalError("Impossible unicode object state, wstr "
3845 "and str should share memory already.");
3846 return NULL;
3847#endif
3848 }
3849 else {
3850 assert(0 && "This should never happen.");
3851 }
3852 }
3853 }
3854 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003855 *size = PyUnicode_WSTR_LENGTH(unicode);
3856 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003857}
3858
Alexander Belopolsky40018472011-02-26 01:02:56 +00003859Py_UNICODE *
3860PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003863}
3864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865
Alexander Belopolsky40018472011-02-26 01:02:56 +00003866Py_ssize_t
3867PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003868{
3869 if (!PyUnicode_Check(unicode)) {
3870 PyErr_BadArgument();
3871 goto onError;
3872 }
3873 return PyUnicode_GET_SIZE(unicode);
3874
Benjamin Peterson29060642009-01-31 22:14:21 +00003875 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003876 return -1;
3877}
3878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003879Py_ssize_t
3880PyUnicode_GetLength(PyObject *unicode)
3881{
Victor Stinner07621332012-06-16 04:53:46 +02003882 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003883 PyErr_BadArgument();
3884 return -1;
3885 }
Victor Stinner07621332012-06-16 04:53:46 +02003886 if (PyUnicode_READY(unicode) == -1)
3887 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003888 return PyUnicode_GET_LENGTH(unicode);
3889}
3890
3891Py_UCS4
3892PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3893{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003894 void *data;
3895 int kind;
3896
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003897 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3898 PyErr_BadArgument();
3899 return (Py_UCS4)-1;
3900 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003901 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003902 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003903 return (Py_UCS4)-1;
3904 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003905 data = PyUnicode_DATA(unicode);
3906 kind = PyUnicode_KIND(unicode);
3907 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908}
3909
3910int
3911PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3912{
3913 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003914 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003915 return -1;
3916 }
Victor Stinner488fa492011-12-12 00:01:39 +01003917 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003918 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003919 PyErr_SetString(PyExc_IndexError, "string index out of range");
3920 return -1;
3921 }
Victor Stinner488fa492011-12-12 00:01:39 +01003922 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003923 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003924 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3925 PyErr_SetString(PyExc_ValueError, "character out of range");
3926 return -1;
3927 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003928 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3929 index, ch);
3930 return 0;
3931}
3932
Alexander Belopolsky40018472011-02-26 01:02:56 +00003933const char *
3934PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003935{
Victor Stinner42cb4622010-09-01 19:39:01 +00003936 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003937}
3938
Victor Stinner554f3f02010-06-16 23:33:54 +00003939/* create or adjust a UnicodeDecodeError */
3940static void
3941make_decode_exception(PyObject **exceptionObject,
3942 const char *encoding,
3943 const char *input, Py_ssize_t length,
3944 Py_ssize_t startpos, Py_ssize_t endpos,
3945 const char *reason)
3946{
3947 if (*exceptionObject == NULL) {
3948 *exceptionObject = PyUnicodeDecodeError_Create(
3949 encoding, input, length, startpos, endpos, reason);
3950 }
3951 else {
3952 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3953 goto onError;
3954 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3955 goto onError;
3956 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3957 goto onError;
3958 }
3959 return;
3960
3961onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003962 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003963}
3964
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003965#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003966/* error handling callback helper:
3967 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003968 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003969 and adjust various state variables.
3970 return 0 on success, -1 on error
3971*/
3972
Alexander Belopolsky40018472011-02-26 01:02:56 +00003973static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003974unicode_decode_call_errorhandler_wchar(
3975 const char *errors, PyObject **errorHandler,
3976 const char *encoding, const char *reason,
3977 const char **input, const char **inend, Py_ssize_t *startinpos,
3978 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3979 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003980{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003981 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003982
3983 PyObject *restuple = NULL;
3984 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003985 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003986 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003987 Py_ssize_t requiredsize;
3988 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003989 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003990 wchar_t *repwstr;
3991 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003992
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003993 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3994 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01003995
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003996 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003997 *errorHandler = PyCodec_LookupError(errors);
3998 if (*errorHandler == NULL)
3999 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004000 }
4001
Victor Stinner554f3f02010-06-16 23:33:54 +00004002 make_decode_exception(exceptionObject,
4003 encoding,
4004 *input, *inend - *input,
4005 *startinpos, *endinpos,
4006 reason);
4007 if (*exceptionObject == NULL)
4008 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004009
4010 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4011 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004012 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004014 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004015 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 }
4017 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004018 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004019
4020 /* Copy back the bytes variables, which might have been modified by the
4021 callback */
4022 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4023 if (!inputobj)
4024 goto onError;
4025 if (!PyBytes_Check(inputobj)) {
4026 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4027 }
4028 *input = PyBytes_AS_STRING(inputobj);
4029 insize = PyBytes_GET_SIZE(inputobj);
4030 *inend = *input + insize;
4031 /* we can DECREF safely, as the exception has another reference,
4032 so the object won't go away. */
4033 Py_DECREF(inputobj);
4034
4035 if (newpos<0)
4036 newpos = insize+newpos;
4037 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004038 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004039 goto onError;
4040 }
4041
4042 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4043 if (repwstr == NULL)
4044 goto onError;
4045 /* need more space? (at least enough for what we
4046 have+the replacement+the rest of the string (starting
4047 at the new input position), so we won't have to check space
4048 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004049 requiredsize = *outpos;
4050 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4051 goto overflow;
4052 requiredsize += repwlen;
4053 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4054 goto overflow;
4055 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004056 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004057 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004058 requiredsize = 2*outsize;
4059 if (unicode_resize(output, requiredsize) < 0)
4060 goto onError;
4061 }
4062 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4063 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004064 *endinpos = newpos;
4065 *inptr = *input + newpos;
4066
4067 /* we made it! */
4068 Py_XDECREF(restuple);
4069 return 0;
4070
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004071 overflow:
4072 PyErr_SetString(PyExc_OverflowError,
4073 "decoded result is too long for a Python string");
4074
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004075 onError:
4076 Py_XDECREF(restuple);
4077 return -1;
4078}
4079#endif /* HAVE_MBCS */
4080
4081static int
4082unicode_decode_call_errorhandler_writer(
4083 const char *errors, PyObject **errorHandler,
4084 const char *encoding, const char *reason,
4085 const char **input, const char **inend, Py_ssize_t *startinpos,
4086 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4087 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4088{
4089 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4090
4091 PyObject *restuple = NULL;
4092 PyObject *repunicode = NULL;
4093 Py_ssize_t insize;
4094 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004095 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004096 PyObject *inputobj = NULL;
4097
4098 if (*errorHandler == NULL) {
4099 *errorHandler = PyCodec_LookupError(errors);
4100 if (*errorHandler == NULL)
4101 goto onError;
4102 }
4103
4104 make_decode_exception(exceptionObject,
4105 encoding,
4106 *input, *inend - *input,
4107 *startinpos, *endinpos,
4108 reason);
4109 if (*exceptionObject == NULL)
4110 goto onError;
4111
4112 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4113 if (restuple == NULL)
4114 goto onError;
4115 if (!PyTuple_Check(restuple)) {
4116 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4117 goto onError;
4118 }
4119 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004120 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004121
4122 /* Copy back the bytes variables, which might have been modified by the
4123 callback */
4124 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4125 if (!inputobj)
4126 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004127 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004129 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004130 *input = PyBytes_AS_STRING(inputobj);
4131 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004132 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004133 /* we can DECREF safely, as the exception has another reference,
4134 so the object won't go away. */
4135 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004136
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004137 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004138 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004139 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004140 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004141 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004142 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004143
Victor Stinner8f674cc2013-04-17 23:02:17 +02004144 if (PyUnicode_READY(repunicode) < 0)
4145 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004146 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004147 if (replen > 1) {
4148 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004149 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004150 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4151 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4152 goto onError;
4153 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004154 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004155 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004156
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004157 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004158 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004160 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004161 Py_XDECREF(restuple);
4162 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004163
Benjamin Peterson29060642009-01-31 22:14:21 +00004164 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004166 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004167}
4168
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004169/* --- UTF-7 Codec -------------------------------------------------------- */
4170
Antoine Pitrou244651a2009-05-04 18:56:13 +00004171/* See RFC2152 for details. We encode conservatively and decode liberally. */
4172
4173/* Three simple macros defining base-64. */
4174
4175/* Is c a base-64 character? */
4176
4177#define IS_BASE64(c) \
4178 (((c) >= 'A' && (c) <= 'Z') || \
4179 ((c) >= 'a' && (c) <= 'z') || \
4180 ((c) >= '0' && (c) <= '9') || \
4181 (c) == '+' || (c) == '/')
4182
4183/* given that c is a base-64 character, what is its base-64 value? */
4184
4185#define FROM_BASE64(c) \
4186 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4187 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4188 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4189 (c) == '+' ? 62 : 63)
4190
4191/* What is the base-64 character of the bottom 6 bits of n? */
4192
4193#define TO_BASE64(n) \
4194 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4195
4196/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4197 * decoded as itself. We are permissive on decoding; the only ASCII
4198 * byte not decoding to itself is the + which begins a base64
4199 * string. */
4200
4201#define DECODE_DIRECT(c) \
4202 ((c) <= 127 && (c) != '+')
4203
4204/* The UTF-7 encoder treats ASCII characters differently according to
4205 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4206 * the above). See RFC2152. This array identifies these different
4207 * sets:
4208 * 0 : "Set D"
4209 * alphanumeric and '(),-./:?
4210 * 1 : "Set O"
4211 * !"#$%&*;<=>@[]^_`{|}
4212 * 2 : "whitespace"
4213 * ht nl cr sp
4214 * 3 : special (must be base64 encoded)
4215 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4216 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004217
Tim Petersced69f82003-09-16 20:30:58 +00004218static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004219char utf7_category[128] = {
4220/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4221 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4222/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4223 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4224/* sp ! " # $ % & ' ( ) * + , - . / */
4225 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4226/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4227 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4228/* @ A B C D E F G H I J K L M N O */
4229 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4230/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4231 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4232/* ` a b c d e f g h i j k l m n o */
4233 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4234/* p q r s t u v w x y z { | } ~ del */
4235 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004236};
4237
Antoine Pitrou244651a2009-05-04 18:56:13 +00004238/* ENCODE_DIRECT: this character should be encoded as itself. The
4239 * answer depends on whether we are encoding set O as itself, and also
4240 * on whether we are encoding whitespace as itself. RFC2152 makes it
4241 * clear that the answers to these questions vary between
4242 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004243
Antoine Pitrou244651a2009-05-04 18:56:13 +00004244#define ENCODE_DIRECT(c, directO, directWS) \
4245 ((c) < 128 && (c) > 0 && \
4246 ((utf7_category[(c)] == 0) || \
4247 (directWS && (utf7_category[(c)] == 2)) || \
4248 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004249
Alexander Belopolsky40018472011-02-26 01:02:56 +00004250PyObject *
4251PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004252 Py_ssize_t size,
4253 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004254{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004255 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4256}
4257
Antoine Pitrou244651a2009-05-04 18:56:13 +00004258/* The decoder. The only state we preserve is our read position,
4259 * i.e. how many characters we have consumed. So if we end in the
4260 * middle of a shift sequence we have to back off the read position
4261 * and the output to the beginning of the sequence, otherwise we lose
4262 * all the shift state (seen bits, number of bits seen, high
4263 * surrogate). */
4264
Alexander Belopolsky40018472011-02-26 01:02:56 +00004265PyObject *
4266PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004267 Py_ssize_t size,
4268 const char *errors,
4269 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004270{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004271 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004272 Py_ssize_t startinpos;
4273 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004275 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004276 const char *errmsg = "";
4277 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004278 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004279 unsigned int base64bits = 0;
4280 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004281 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004282 PyObject *errorHandler = NULL;
4283 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004284
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004285 if (size == 0) {
4286 if (consumed)
4287 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004288 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004290
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004291 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004292 _PyUnicodeWriter_Init(&writer);
4293 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004294
4295 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004296 e = s + size;
4297
4298 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004299 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004300 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004301 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004302
Antoine Pitrou244651a2009-05-04 18:56:13 +00004303 if (inShift) { /* in a base-64 section */
4304 if (IS_BASE64(ch)) { /* consume a base-64 character */
4305 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4306 base64bits += 6;
4307 s++;
4308 if (base64bits >= 16) {
4309 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004310 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004311 base64bits -= 16;
4312 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004313 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004314 if (surrogate) {
4315 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004316 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4317 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004318 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004319 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004320 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004321 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004322 }
4323 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004324 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004325 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004326 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 }
4328 }
Victor Stinner551ac952011-11-29 22:58:13 +01004329 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004330 /* first surrogate */
4331 surrogate = outCh;
4332 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004334 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004335 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336 }
4337 }
4338 }
4339 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004340 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004341 if (base64bits > 0) { /* left-over bits */
4342 if (base64bits >= 6) {
4343 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004344 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 errmsg = "partial character in shift sequence";
4346 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 else {
4349 /* Some bits remain; they should be zero */
4350 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004351 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 errmsg = "non-zero padding bits in shift sequence";
4353 goto utf7Error;
4354 }
4355 }
4356 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004357 if (surrogate && DECODE_DIRECT(ch)) {
4358 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4359 goto onError;
4360 }
4361 surrogate = 0;
4362 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 /* '-' is absorbed; other terminating
4364 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004365 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004367 }
4368 }
4369 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004370 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004371 s++; /* consume '+' */
4372 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004373 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004374 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 }
4377 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004379 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004380 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004382 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 }
4384 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004387 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004390 else {
4391 startinpos = s-starts;
4392 s++;
4393 errmsg = "unexpected special character";
4394 goto utf7Error;
4395 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004397utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004398 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004399 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004400 errors, &errorHandler,
4401 "utf7", errmsg,
4402 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004403 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405 }
4406
Antoine Pitrou244651a2009-05-04 18:56:13 +00004407 /* end of string */
4408
4409 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4410 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004411 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 if (surrogate ||
4413 (base64bits >= 6) ||
4414 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004416 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004417 errors, &errorHandler,
4418 "utf7", "unterminated shift sequence",
4419 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004421 goto onError;
4422 if (s < e)
4423 goto restart;
4424 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004426
4427 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004428 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004429 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004430 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004431 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004432 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004433 writer.kind, writer.data, shiftOutStart);
4434 Py_XDECREF(errorHandler);
4435 Py_XDECREF(exc);
4436 _PyUnicodeWriter_Dealloc(&writer);
4437 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004438 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004439 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 }
4441 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004442 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004444 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004446 Py_XDECREF(errorHandler);
4447 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004448 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004449
Benjamin Peterson29060642009-01-31 22:14:21 +00004450 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004451 Py_XDECREF(errorHandler);
4452 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004453 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004454 return NULL;
4455}
4456
4457
Alexander Belopolsky40018472011-02-26 01:02:56 +00004458PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004459_PyUnicode_EncodeUTF7(PyObject *str,
4460 int base64SetO,
4461 int base64WhiteSpace,
4462 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004463{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004464 int kind;
4465 void *data;
4466 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004467 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004468 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004469 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 unsigned int base64bits = 0;
4471 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 char * out;
4473 char * start;
4474
Benjamin Petersonbac79492012-01-14 13:34:47 -05004475 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004476 return NULL;
4477 kind = PyUnicode_KIND(str);
4478 data = PyUnicode_DATA(str);
4479 len = PyUnicode_GET_LENGTH(str);
4480
4481 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004482 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004484 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004485 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004486 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004487 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488 if (v == NULL)
4489 return NULL;
4490
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004491 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004492 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004493 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 if (inShift) {
4496 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4497 /* shifting out */
4498 if (base64bits) { /* output remaining bits */
4499 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4500 base64buffer = 0;
4501 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502 }
4503 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504 /* Characters not in the BASE64 set implicitly unshift the sequence
4505 so no '-' is required, except if the character is itself a '-' */
4506 if (IS_BASE64(ch) || ch == '-') {
4507 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509 *out++ = (char) ch;
4510 }
4511 else {
4512 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004513 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004514 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004515 else { /* not in a shift sequence */
4516 if (ch == '+') {
4517 *out++ = '+';
4518 *out++ = '-';
4519 }
4520 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4521 *out++ = (char) ch;
4522 }
4523 else {
4524 *out++ = '+';
4525 inShift = 1;
4526 goto encode_char;
4527 }
4528 }
4529 continue;
4530encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004532 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004533
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 /* code first surrogate */
4535 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004536 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004537 while (base64bits >= 6) {
4538 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4539 base64bits -= 6;
4540 }
4541 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004542 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004544 base64bits += 16;
4545 base64buffer = (base64buffer << 16) | ch;
4546 while (base64bits >= 6) {
4547 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4548 base64bits -= 6;
4549 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004550 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004551 if (base64bits)
4552 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4553 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004555 if (_PyBytes_Resize(&v, out - start) < 0)
4556 return NULL;
4557 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004558}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004559PyObject *
4560PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4561 Py_ssize_t size,
4562 int base64SetO,
4563 int base64WhiteSpace,
4564 const char *errors)
4565{
4566 PyObject *result;
4567 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4568 if (tmp == NULL)
4569 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004570 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004571 base64WhiteSpace, errors);
4572 Py_DECREF(tmp);
4573 return result;
4574}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004575
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576#undef IS_BASE64
4577#undef FROM_BASE64
4578#undef TO_BASE64
4579#undef DECODE_DIRECT
4580#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004581
Guido van Rossumd57fd912000-03-10 22:53:23 +00004582/* --- UTF-8 Codec -------------------------------------------------------- */
4583
Alexander Belopolsky40018472011-02-26 01:02:56 +00004584PyObject *
4585PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004586 Py_ssize_t size,
4587 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004588{
Walter Dörwald69652032004-09-07 20:24:22 +00004589 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4590}
4591
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004592#include "stringlib/asciilib.h"
4593#include "stringlib/codecs.h"
4594#include "stringlib/undef.h"
4595
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004596#include "stringlib/ucs1lib.h"
4597#include "stringlib/codecs.h"
4598#include "stringlib/undef.h"
4599
4600#include "stringlib/ucs2lib.h"
4601#include "stringlib/codecs.h"
4602#include "stringlib/undef.h"
4603
4604#include "stringlib/ucs4lib.h"
4605#include "stringlib/codecs.h"
4606#include "stringlib/undef.h"
4607
Antoine Pitrouab868312009-01-10 15:40:25 +00004608/* Mask to quickly check whether a C 'long' contains a
4609 non-ASCII, UTF8-encoded char. */
4610#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004611# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004612#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004613# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004614#else
4615# error C 'long' size should be either 4 or 8!
4616#endif
4617
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004618static Py_ssize_t
4619ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004620{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004621 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004622 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004623
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004624 /*
4625 * Issue #17237: m68k is a bit different from most architectures in
4626 * that objects do not use "natural alignment" - for example, int and
4627 * long are only aligned at 2-byte boundaries. Therefore the assert()
4628 * won't work; also, tests have shown that skipping the "optimised
4629 * version" will even speed up m68k.
4630 */
4631#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004632#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004633 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4634 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004635 /* Fast path, see in STRINGLIB(utf8_decode) for
4636 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004637 /* Help allocation */
4638 const char *_p = p;
4639 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004640 while (_p < aligned_end) {
4641 unsigned long value = *(const unsigned long *) _p;
4642 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004643 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004644 *((unsigned long *)q) = value;
4645 _p += SIZEOF_LONG;
4646 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004647 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004648 p = _p;
4649 while (p < end) {
4650 if ((unsigned char)*p & 0x80)
4651 break;
4652 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004653 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004655 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004656#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004657#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004658 while (p < end) {
4659 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4660 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004661 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004662 /* Help allocation */
4663 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664 while (_p < aligned_end) {
4665 unsigned long value = *(unsigned long *) _p;
4666 if (value & ASCII_CHAR_MASK)
4667 break;
4668 _p += SIZEOF_LONG;
4669 }
4670 p = _p;
4671 if (_p == end)
4672 break;
4673 }
4674 if ((unsigned char)*p & 0x80)
4675 break;
4676 ++p;
4677 }
4678 memcpy(dest, start, p - start);
4679 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004680}
Antoine Pitrouab868312009-01-10 15:40:25 +00004681
Victor Stinner785938e2011-12-11 20:09:03 +01004682PyObject *
4683PyUnicode_DecodeUTF8Stateful(const char *s,
4684 Py_ssize_t size,
4685 const char *errors,
4686 Py_ssize_t *consumed)
4687{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004688 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004689 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004691
4692 Py_ssize_t startinpos;
4693 Py_ssize_t endinpos;
4694 const char *errmsg = "";
4695 PyObject *errorHandler = NULL;
4696 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004697
4698 if (size == 0) {
4699 if (consumed)
4700 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004701 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004702 }
4703
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4705 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004706 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004707 *consumed = 1;
4708 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004709 }
4710
Victor Stinner8f674cc2013-04-17 23:02:17 +02004711 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004712 writer.min_length = size;
4713 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004714 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004715
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004716 writer.pos = ascii_decode(s, end, writer.data);
4717 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004718 while (s < end) {
4719 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004720 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004721 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004722 if (PyUnicode_IS_ASCII(writer.buffer))
4723 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004725 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004727 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004728 } else {
4729 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004730 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 }
4732
4733 switch (ch) {
4734 case 0:
4735 if (s == end || consumed)
4736 goto End;
4737 errmsg = "unexpected end of data";
4738 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004739 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004740 break;
4741 case 1:
4742 errmsg = "invalid start byte";
4743 startinpos = s - starts;
4744 endinpos = startinpos + 1;
4745 break;
4746 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004747 case 3:
4748 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004749 errmsg = "invalid continuation byte";
4750 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004751 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004752 break;
4753 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004754 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 goto onError;
4756 continue;
4757 }
4758
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004759 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760 errors, &errorHandler,
4761 "utf-8", errmsg,
4762 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004763 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004765 }
4766
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 if (consumed)
4769 *consumed = s - starts;
4770
4771 Py_XDECREF(errorHandler);
4772 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004773 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774
4775onError:
4776 Py_XDECREF(errorHandler);
4777 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004778 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004779 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004780}
4781
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004782#ifdef __APPLE__
4783
4784/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004785 used to decode the command line arguments on Mac OS X.
4786
4787 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004788 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004789
4790wchar_t*
4791_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4792{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004793 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004794 wchar_t *unicode;
4795 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004796
4797 /* Note: size will always be longer than the resulting Unicode
4798 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004799 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004800 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004801 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004802 if (!unicode)
4803 return NULL;
4804
4805 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004806 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004808 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004809 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004810#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004812#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004814#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815 if (ch > 0xFF) {
4816#if SIZEOF_WCHAR_T == 4
4817 assert(0);
4818#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004819 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004820 /* compute and append the two surrogates: */
4821 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4822 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4823#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004824 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004825 else {
4826 if (!ch && s == e)
4827 break;
4828 /* surrogateescape */
4829 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4830 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004831 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004832 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004833 return unicode;
4834}
4835
4836#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004838/* Primary internal function which creates utf8 encoded bytes objects.
4839
4840 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004841 and allocate exactly as much space needed at the end. Else allocate the
4842 maximum possible needed (4 result bytes per Unicode character), and return
4843 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004844*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004845PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004846_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004847{
Victor Stinner6099a032011-12-18 14:22:26 +01004848 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004849 void *data;
4850 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004851
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 if (!PyUnicode_Check(unicode)) {
4853 PyErr_BadArgument();
4854 return NULL;
4855 }
4856
4857 if (PyUnicode_READY(unicode) == -1)
4858 return NULL;
4859
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004860 if (PyUnicode_UTF8(unicode))
4861 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4862 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004863
4864 kind = PyUnicode_KIND(unicode);
4865 data = PyUnicode_DATA(unicode);
4866 size = PyUnicode_GET_LENGTH(unicode);
4867
Benjamin Petersonead6b532011-12-20 17:23:42 -06004868 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004869 default:
4870 assert(0);
4871 case PyUnicode_1BYTE_KIND:
4872 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4873 assert(!PyUnicode_IS_ASCII(unicode));
4874 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4875 case PyUnicode_2BYTE_KIND:
4876 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4877 case PyUnicode_4BYTE_KIND:
4878 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004879 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004880}
4881
Alexander Belopolsky40018472011-02-26 01:02:56 +00004882PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4884 Py_ssize_t size,
4885 const char *errors)
4886{
4887 PyObject *v, *unicode;
4888
4889 unicode = PyUnicode_FromUnicode(s, size);
4890 if (unicode == NULL)
4891 return NULL;
4892 v = _PyUnicode_AsUTF8String(unicode, errors);
4893 Py_DECREF(unicode);
4894 return v;
4895}
4896
4897PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004898PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004899{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004900 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004901}
4902
Walter Dörwald41980ca2007-08-16 21:55:45 +00004903/* --- UTF-32 Codec ------------------------------------------------------- */
4904
4905PyObject *
4906PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 Py_ssize_t size,
4908 const char *errors,
4909 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004910{
4911 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4912}
4913
4914PyObject *
4915PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004916 Py_ssize_t size,
4917 const char *errors,
4918 int *byteorder,
4919 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004920{
4921 const char *starts = s;
4922 Py_ssize_t startinpos;
4923 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004924 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004925 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004926 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004927 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004928 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004929 PyObject *errorHandler = NULL;
4930 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004931
Walter Dörwald41980ca2007-08-16 21:55:45 +00004932 q = (unsigned char *)s;
4933 e = q + size;
4934
4935 if (byteorder)
4936 bo = *byteorder;
4937
4938 /* Check for BOM marks (U+FEFF) in the input and adjust current
4939 byte order setting accordingly. In native mode, the leading BOM
4940 mark is skipped, in all other modes, it is copied to the output
4941 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004942 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07004943 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01004944 if (bom == 0x0000FEFF) {
4945 bo = -1;
4946 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004947 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004948 else if (bom == 0xFFFE0000) {
4949 bo = 1;
4950 q += 4;
4951 }
4952 if (byteorder)
4953 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004954 }
4955
Victor Stinnere64322e2012-10-30 23:12:47 +01004956 if (q == e) {
4957 if (consumed)
4958 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004959 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960 }
4961
Victor Stinnere64322e2012-10-30 23:12:47 +01004962#ifdef WORDS_BIGENDIAN
4963 le = bo < 0;
4964#else
4965 le = bo <= 0;
4966#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004967 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004968
Victor Stinner8f674cc2013-04-17 23:02:17 +02004969 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004970 writer.min_length = (e - q + 3) / 4;
4971 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004972 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004973
Victor Stinnere64322e2012-10-30 23:12:47 +01004974 while (1) {
4975 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004976 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004977
Victor Stinnere64322e2012-10-30 23:12:47 +01004978 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004979 enum PyUnicode_Kind kind = writer.kind;
4980 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004981 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004982 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004983 if (le) {
4984 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07004985 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01004986 if (ch > maxch)
4987 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004988 if (kind != PyUnicode_1BYTE_KIND &&
4989 Py_UNICODE_IS_SURROGATE(ch))
4990 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004991 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004992 q += 4;
4993 } while (q <= last);
4994 }
4995 else {
4996 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07004997 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01004998 if (ch > maxch)
4999 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005000 if (kind != PyUnicode_1BYTE_KIND &&
5001 Py_UNICODE_IS_SURROGATE(ch))
5002 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005003 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005004 q += 4;
5005 } while (q <= last);
5006 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005007 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005008 }
5009
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005010 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005011 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005012 startinpos = ((const char *)q) - starts;
5013 endinpos = startinpos + 4;
5014 }
5015 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005016 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005017 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005018 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005019 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005020 startinpos = ((const char *)q) - starts;
5021 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005022 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005023 else {
5024 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005025 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005026 goto onError;
5027 q += 4;
5028 continue;
5029 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005030 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005031 startinpos = ((const char *)q) - starts;
5032 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005034
5035 /* The remaining input chars are ignored if the callback
5036 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005037 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005038 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005039 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005040 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005041 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043 }
5044
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005046 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047
Walter Dörwald41980ca2007-08-16 21:55:45 +00005048 Py_XDECREF(errorHandler);
5049 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005050 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005053 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054 Py_XDECREF(errorHandler);
5055 Py_XDECREF(exc);
5056 return NULL;
5057}
5058
5059PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005060_PyUnicode_EncodeUTF32(PyObject *str,
5061 const char *errors,
5062 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005063{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005064 enum PyUnicode_Kind kind;
5065 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005066 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005067 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005068 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005069#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005070 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005072 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005073#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005074 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005075 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005076 PyObject *errorHandler = NULL;
5077 PyObject *exc = NULL;
5078 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005080 if (!PyUnicode_Check(str)) {
5081 PyErr_BadArgument();
5082 return NULL;
5083 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005084 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005085 return NULL;
5086 kind = PyUnicode_KIND(str);
5087 data = PyUnicode_DATA(str);
5088 len = PyUnicode_GET_LENGTH(str);
5089
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005090 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005091 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005092 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005093 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094 if (v == NULL)
5095 return NULL;
5096
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005097 /* output buffer is 4-bytes aligned */
5098 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5099 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005101 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005102 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005103 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005105 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005106 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005107 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005108 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005109 else
5110 encoding = "utf-32";
5111
5112 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005113 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5114 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115 }
5116
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005117 pos = 0;
5118 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005119 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005120
5121 if (kind == PyUnicode_2BYTE_KIND) {
5122 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5123 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005124 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005125 else {
5126 assert(kind == PyUnicode_4BYTE_KIND);
5127 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5128 &out, native_ordering);
5129 }
5130 if (pos == len)
5131 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005132
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005133 rep = unicode_encode_call_errorhandler(
5134 errors, &errorHandler,
5135 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005136 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005137 if (!rep)
5138 goto error;
5139
5140 if (PyBytes_Check(rep)) {
5141 repsize = PyBytes_GET_SIZE(rep);
5142 if (repsize & 3) {
5143 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005144 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005145 "surrogates not allowed");
5146 goto error;
5147 }
5148 moreunits = repsize / 4;
5149 }
5150 else {
5151 assert(PyUnicode_Check(rep));
5152 if (PyUnicode_READY(rep) < 0)
5153 goto error;
5154 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5155 if (!PyUnicode_IS_ASCII(rep)) {
5156 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005157 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005158 "surrogates not allowed");
5159 goto error;
5160 }
5161 }
5162
5163 /* four bytes are reserved for each surrogate */
5164 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005165 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005166 Py_ssize_t morebytes = 4 * (moreunits - 1);
5167 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5168 /* integer overflow */
5169 PyErr_NoMemory();
5170 goto error;
5171 }
5172 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5173 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005174 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005175 }
5176
5177 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005178 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5179 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005180 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005181 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005182 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5183 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005184 }
5185
5186 Py_CLEAR(rep);
5187 }
5188
5189 /* Cut back to size actually needed. This is necessary for, for example,
5190 encoding of a string containing isolated surrogates and the 'ignore'
5191 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005192 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 if (nsize != PyBytes_GET_SIZE(v))
5194 _PyBytes_Resize(&v, nsize);
5195 Py_XDECREF(errorHandler);
5196 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005197 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005198 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005199 error:
5200 Py_XDECREF(rep);
5201 Py_XDECREF(errorHandler);
5202 Py_XDECREF(exc);
5203 Py_XDECREF(v);
5204 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005205}
5206
Alexander Belopolsky40018472011-02-26 01:02:56 +00005207PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005208PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5209 Py_ssize_t size,
5210 const char *errors,
5211 int byteorder)
5212{
5213 PyObject *result;
5214 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5215 if (tmp == NULL)
5216 return NULL;
5217 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5218 Py_DECREF(tmp);
5219 return result;
5220}
5221
5222PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005223PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005224{
Victor Stinnerb960b342011-11-20 19:12:52 +01005225 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005226}
5227
Guido van Rossumd57fd912000-03-10 22:53:23 +00005228/* --- UTF-16 Codec ------------------------------------------------------- */
5229
Tim Peters772747b2001-08-09 22:21:55 +00005230PyObject *
5231PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 Py_ssize_t size,
5233 const char *errors,
5234 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005235{
Walter Dörwald69652032004-09-07 20:24:22 +00005236 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5237}
5238
5239PyObject *
5240PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005241 Py_ssize_t size,
5242 const char *errors,
5243 int *byteorder,
5244 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005245{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005246 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005247 Py_ssize_t startinpos;
5248 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005249 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005250 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005251 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005252 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005253 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005254 PyObject *errorHandler = NULL;
5255 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005256 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005257
Tim Peters772747b2001-08-09 22:21:55 +00005258 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005259 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005260
5261 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005262 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005263
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005264 /* Check for BOM marks (U+FEFF) in the input and adjust current
5265 byte order setting accordingly. In native mode, the leading BOM
5266 mark is skipped, in all other modes, it is copied to the output
5267 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005268 if (bo == 0 && size >= 2) {
5269 const Py_UCS4 bom = (q[1] << 8) | q[0];
5270 if (bom == 0xFEFF) {
5271 q += 2;
5272 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005273 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005274 else if (bom == 0xFFFE) {
5275 q += 2;
5276 bo = 1;
5277 }
5278 if (byteorder)
5279 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005280 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005281
Antoine Pitrou63065d72012-05-15 23:48:04 +02005282 if (q == e) {
5283 if (consumed)
5284 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005285 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005286 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005287
Christian Heimes743e0cd2012-10-17 23:52:17 +02005288#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005289 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005290 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005291#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005292 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005293 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005294#endif
Tim Peters772747b2001-08-09 22:21:55 +00005295
Antoine Pitrou63065d72012-05-15 23:48:04 +02005296 /* Note: size will always be longer than the resulting Unicode
5297 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005298 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005299 writer.min_length = (e - q + 1) / 2;
5300 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005302
Antoine Pitrou63065d72012-05-15 23:48:04 +02005303 while (1) {
5304 Py_UCS4 ch = 0;
5305 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005306 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005307 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005308 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005309 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005310 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005311 native_ordering);
5312 else
5313 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005314 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005315 native_ordering);
5316 } else if (kind == PyUnicode_2BYTE_KIND) {
5317 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005318 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319 native_ordering);
5320 } else {
5321 assert(kind == PyUnicode_4BYTE_KIND);
5322 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005323 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005324 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005325 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005326 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005327
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328 switch (ch)
5329 {
5330 case 0:
5331 /* remaining byte at the end? (size should be even) */
5332 if (q == e || consumed)
5333 goto End;
5334 errmsg = "truncated data";
5335 startinpos = ((const char *)q) - starts;
5336 endinpos = ((const char *)e) - starts;
5337 break;
5338 /* The remaining input chars are ignored if the callback
5339 chooses to skip the input */
5340 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005341 q -= 2;
5342 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005343 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005344 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005345 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005346 endinpos = ((const char *)e) - starts;
5347 break;
5348 case 2:
5349 errmsg = "illegal encoding";
5350 startinpos = ((const char *)q) - 2 - starts;
5351 endinpos = startinpos + 2;
5352 break;
5353 case 3:
5354 errmsg = "illegal UTF-16 surrogate";
5355 startinpos = ((const char *)q) - 4 - starts;
5356 endinpos = startinpos + 2;
5357 break;
5358 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005359 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005360 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 continue;
5362 }
5363
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005364 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005365 errors,
5366 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005367 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005368 &starts,
5369 (const char **)&e,
5370 &startinpos,
5371 &endinpos,
5372 &exc,
5373 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005374 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005375 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005376 }
5377
Antoine Pitrou63065d72012-05-15 23:48:04 +02005378End:
Walter Dörwald69652032004-09-07 20:24:22 +00005379 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005380 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005381
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005382 Py_XDECREF(errorHandler);
5383 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005384 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005385
Benjamin Peterson29060642009-01-31 22:14:21 +00005386 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005387 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005388 Py_XDECREF(errorHandler);
5389 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005390 return NULL;
5391}
5392
Tim Peters772747b2001-08-09 22:21:55 +00005393PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005394_PyUnicode_EncodeUTF16(PyObject *str,
5395 const char *errors,
5396 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005397{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005398 enum PyUnicode_Kind kind;
5399 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005400 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005401 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005402 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005403 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005404#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005405 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005406#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005407 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005408#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005409 const char *encoding;
5410 Py_ssize_t nsize, pos;
5411 PyObject *errorHandler = NULL;
5412 PyObject *exc = NULL;
5413 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005414
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005415 if (!PyUnicode_Check(str)) {
5416 PyErr_BadArgument();
5417 return NULL;
5418 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005419 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005420 return NULL;
5421 kind = PyUnicode_KIND(str);
5422 data = PyUnicode_DATA(str);
5423 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005424
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005425 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005426 if (kind == PyUnicode_4BYTE_KIND) {
5427 const Py_UCS4 *in = (const Py_UCS4 *)data;
5428 const Py_UCS4 *end = in + len;
5429 while (in < end)
5430 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005431 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005432 }
5433 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005435 nsize = len + pairs + (byteorder == 0);
5436 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437 if (v == NULL)
5438 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005440 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005441 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005442 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005443 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005444 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005445 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005446 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005447
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005448 if (kind == PyUnicode_1BYTE_KIND) {
5449 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5450 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005451 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005452
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005453 if (byteorder < 0)
5454 encoding = "utf-16-le";
5455 else if (byteorder > 0)
5456 encoding = "utf-16-be";
5457 else
5458 encoding = "utf-16";
5459
5460 pos = 0;
5461 while (pos < len) {
5462 Py_ssize_t repsize, moreunits;
5463
5464 if (kind == PyUnicode_2BYTE_KIND) {
5465 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5466 &out, native_ordering);
5467 }
5468 else {
5469 assert(kind == PyUnicode_4BYTE_KIND);
5470 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5471 &out, native_ordering);
5472 }
5473 if (pos == len)
5474 break;
5475
5476 rep = unicode_encode_call_errorhandler(
5477 errors, &errorHandler,
5478 encoding, "surrogates not allowed",
5479 str, &exc, pos, pos + 1, &pos);
5480 if (!rep)
5481 goto error;
5482
5483 if (PyBytes_Check(rep)) {
5484 repsize = PyBytes_GET_SIZE(rep);
5485 if (repsize & 1) {
5486 raise_encode_exception(&exc, encoding,
5487 str, pos - 1, pos,
5488 "surrogates not allowed");
5489 goto error;
5490 }
5491 moreunits = repsize / 2;
5492 }
5493 else {
5494 assert(PyUnicode_Check(rep));
5495 if (PyUnicode_READY(rep) < 0)
5496 goto error;
5497 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5498 if (!PyUnicode_IS_ASCII(rep)) {
5499 raise_encode_exception(&exc, encoding,
5500 str, pos - 1, pos,
5501 "surrogates not allowed");
5502 goto error;
5503 }
5504 }
5505
5506 /* two bytes are reserved for each surrogate */
5507 if (moreunits > 1) {
5508 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5509 Py_ssize_t morebytes = 2 * (moreunits - 1);
5510 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5511 /* integer overflow */
5512 PyErr_NoMemory();
5513 goto error;
5514 }
5515 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5516 goto error;
5517 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5518 }
5519
5520 if (PyBytes_Check(rep)) {
5521 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5522 out += moreunits;
5523 } else /* rep is unicode */ {
5524 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5525 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5526 &out, native_ordering);
5527 }
5528
5529 Py_CLEAR(rep);
5530 }
5531
5532 /* Cut back to size actually needed. This is necessary for, for example,
5533 encoding of a string containing isolated surrogates and the 'ignore' handler
5534 is used. */
5535 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5536 if (nsize != PyBytes_GET_SIZE(v))
5537 _PyBytes_Resize(&v, nsize);
5538 Py_XDECREF(errorHandler);
5539 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005540 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005541 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005542 error:
5543 Py_XDECREF(rep);
5544 Py_XDECREF(errorHandler);
5545 Py_XDECREF(exc);
5546 Py_XDECREF(v);
5547 return NULL;
5548#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005549}
5550
Alexander Belopolsky40018472011-02-26 01:02:56 +00005551PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005552PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5553 Py_ssize_t size,
5554 const char *errors,
5555 int byteorder)
5556{
5557 PyObject *result;
5558 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5559 if (tmp == NULL)
5560 return NULL;
5561 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5562 Py_DECREF(tmp);
5563 return result;
5564}
5565
5566PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005567PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005569 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005570}
5571
5572/* --- Unicode Escape Codec ----------------------------------------------- */
5573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005574/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5575 if all the escapes in the string make it still a valid ASCII string.
5576 Returns -1 if any escapes were found which cause the string to
5577 pop out of ASCII range. Otherwise returns the length of the
5578 required buffer to hold the string.
5579 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005580static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005581length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5582{
5583 const unsigned char *p = (const unsigned char *)s;
5584 const unsigned char *end = p + size;
5585 Py_ssize_t length = 0;
5586
5587 if (size < 0)
5588 return -1;
5589
5590 for (; p < end; ++p) {
5591 if (*p > 127) {
5592 /* Non-ASCII */
5593 return -1;
5594 }
5595 else if (*p != '\\') {
5596 /* Normal character */
5597 ++length;
5598 }
5599 else {
5600 /* Backslash-escape, check next char */
5601 ++p;
5602 /* Escape sequence reaches till end of string or
5603 non-ASCII follow-up. */
5604 if (p >= end || *p > 127)
5605 return -1;
5606 switch (*p) {
5607 case '\n':
5608 /* backslash + \n result in zero characters */
5609 break;
5610 case '\\': case '\'': case '\"':
5611 case 'b': case 'f': case 't':
5612 case 'n': case 'r': case 'v': case 'a':
5613 ++length;
5614 break;
5615 case '0': case '1': case '2': case '3':
5616 case '4': case '5': case '6': case '7':
5617 case 'x': case 'u': case 'U': case 'N':
5618 /* these do not guarantee ASCII characters */
5619 return -1;
5620 default:
5621 /* count the backslash + the other character */
5622 length += 2;
5623 }
5624 }
5625 }
5626 return length;
5627}
5628
Fredrik Lundh06d12682001-01-24 07:59:11 +00005629static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005630
Alexander Belopolsky40018472011-02-26 01:02:56 +00005631PyObject *
5632PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005633 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005634 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005636 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005637 Py_ssize_t startinpos;
5638 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005639 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005640 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005641 char* message;
5642 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643 PyObject *errorHandler = NULL;
5644 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005645 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005646
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005647 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005648 if (len == 0)
5649 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650
5651 /* After length_of_escaped_ascii_string() there are two alternatives,
5652 either the string is pure ASCII with named escapes like \n, etc.
5653 and we determined it's exact size (common case)
5654 or it contains \x, \u, ... escape sequences. then we create a
5655 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005656 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005657 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005658 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005659 }
5660 else {
5661 /* Escaped strings will always be longer than the resulting
5662 Unicode string, so we start with size here and then reduce the
5663 length after conversion to the true value.
5664 (but if the error callback returns a long replacement string
5665 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005666 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005667 }
5668
Guido van Rossumd57fd912000-03-10 22:53:23 +00005669 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005670 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005672
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 while (s < end) {
5674 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005675 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677
5678 /* Non-escape characters are interpreted as Unicode ordinals */
5679 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005680 x = (unsigned char)*s;
5681 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005682 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005683 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 continue;
5685 }
5686
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005687 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 /* \ - Escapes */
5689 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005690 c = *s++;
5691 if (s > end)
5692 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005693
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005694 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695
Benjamin Peterson29060642009-01-31 22:14:21 +00005696 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005697#define WRITECHAR(ch) \
5698 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005699 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005700 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005701 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005702
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005704 case '\\': WRITECHAR('\\'); break;
5705 case '\'': WRITECHAR('\''); break;
5706 case '\"': WRITECHAR('\"'); break;
5707 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005708 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005709 case 'f': WRITECHAR('\014'); break;
5710 case 't': WRITECHAR('\t'); break;
5711 case 'n': WRITECHAR('\n'); break;
5712 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005713 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005714 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005715 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005716 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719 case '0': case '1': case '2': case '3':
5720 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005721 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005722 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005723 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005724 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005725 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005727 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 break;
5729
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 /* hex escapes */
5731 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005733 digits = 2;
5734 message = "truncated \\xXX escape";
5735 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736
Benjamin Peterson29060642009-01-31 22:14:21 +00005737 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005739 digits = 4;
5740 message = "truncated \\uXXXX escape";
5741 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005744 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005745 digits = 8;
5746 message = "truncated \\UXXXXXXXX escape";
5747 hexescape:
5748 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005749 if (end - s < digits) {
5750 /* count only hex digits */
5751 for (; s < end; ++s) {
5752 c = (unsigned char)*s;
5753 if (!Py_ISXDIGIT(c))
5754 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005755 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005756 goto error;
5757 }
5758 for (; digits--; ++s) {
5759 c = (unsigned char)*s;
5760 if (!Py_ISXDIGIT(c))
5761 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005762 chr = (chr<<4) & ~0xF;
5763 if (c >= '0' && c <= '9')
5764 chr += c - '0';
5765 else if (c >= 'a' && c <= 'f')
5766 chr += 10 + c - 'a';
5767 else
5768 chr += 10 + c - 'A';
5769 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005770 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005771 /* _decoding_error will have already written into the
5772 target buffer. */
5773 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005774 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005775 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005776 message = "illegal Unicode character";
5777 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005778 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005779 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005780 break;
5781
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005783 case 'N':
5784 message = "malformed \\N character escape";
5785 if (ucnhash_CAPI == NULL) {
5786 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005787 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5788 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005789 if (ucnhash_CAPI == NULL)
5790 goto ucnhashError;
5791 }
5792 if (*s == '{') {
5793 const char *start = s+1;
5794 /* look for the closing brace */
5795 while (*s != '}' && s < end)
5796 s++;
5797 if (s > start && s < end && *s == '}') {
5798 /* found a name. look it up in the unicode database */
5799 message = "unknown Unicode character name";
5800 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005801 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005802 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005803 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005804 goto store;
5805 }
5806 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005807 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005808
5809 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005810 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005811 message = "\\ at end of string";
5812 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005813 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005814 }
5815 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005816 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005817 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005818 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005819 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005820 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005821 continue;
5822
5823 error:
5824 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005825 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005826 errors, &errorHandler,
5827 "unicodeescape", message,
5828 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005829 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto onError;
5831 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005832 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005833#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005834
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005835 Py_XDECREF(errorHandler);
5836 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005837 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005838
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005840 PyErr_SetString(
5841 PyExc_UnicodeError,
5842 "\\N escapes not supported (can't load unicodedata module)"
5843 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005844 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005845 Py_XDECREF(errorHandler);
5846 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005847 return NULL;
5848
Benjamin Peterson29060642009-01-31 22:14:21 +00005849 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005850 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005851 Py_XDECREF(errorHandler);
5852 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 return NULL;
5854}
5855
5856/* Return a Unicode-Escape string version of the Unicode object.
5857
5858 If quotes is true, the string is enclosed in u"" or u'' quotes as
5859 appropriate.
5860
5861*/
5862
Alexander Belopolsky40018472011-02-26 01:02:56 +00005863PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005864PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005866 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005867 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005869 int kind;
5870 void *data;
5871 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872
Ezio Melottie7f90372012-10-05 03:33:31 +03005873 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005874 escape.
5875
Ezio Melottie7f90372012-10-05 03:33:31 +03005876 For UCS1 strings it's '\xxx', 4 bytes per source character.
5877 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5878 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005879 */
5880
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005881 if (!PyUnicode_Check(unicode)) {
5882 PyErr_BadArgument();
5883 return NULL;
5884 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005885 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886 return NULL;
5887 len = PyUnicode_GET_LENGTH(unicode);
5888 kind = PyUnicode_KIND(unicode);
5889 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005890 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005891 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5892 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5893 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5894 }
5895
5896 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005897 return PyBytes_FromStringAndSize(NULL, 0);
5898
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005899 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005900 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005901
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005902 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 if (repr == NULL)
5907 return NULL;
5908
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005909 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005911 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005912 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005913
Walter Dörwald79e913e2007-05-12 11:08:06 +00005914 /* Escape backslashes */
5915 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 *p++ = '\\';
5917 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005918 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005919 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005920
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005921 /* Map 21-bit characters to '\U00xxxxxx' */
5922 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005923 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005924 *p++ = '\\';
5925 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005926 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5927 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5928 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5929 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5930 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5931 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5932 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5933 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005935 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005936
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005938 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 *p++ = '\\';
5940 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005941 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5942 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5943 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5944 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005946
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005947 /* Map special whitespace to '\t', \n', '\r' */
5948 else if (ch == '\t') {
5949 *p++ = '\\';
5950 *p++ = 't';
5951 }
5952 else if (ch == '\n') {
5953 *p++ = '\\';
5954 *p++ = 'n';
5955 }
5956 else if (ch == '\r') {
5957 *p++ = '\\';
5958 *p++ = 'r';
5959 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005960
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005961 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005962 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005963 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005964 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005965 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5966 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005967 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005968
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 /* Copy everything else as-is */
5970 else
5971 *p++ = (char) ch;
5972 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005974 assert(p - PyBytes_AS_STRING(repr) > 0);
5975 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5976 return NULL;
5977 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978}
5979
Alexander Belopolsky40018472011-02-26 01:02:56 +00005980PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005981PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5982 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005984 PyObject *result;
5985 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5986 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005988 result = PyUnicode_AsUnicodeEscapeString(tmp);
5989 Py_DECREF(tmp);
5990 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991}
5992
5993/* --- Raw Unicode Escape Codec ------------------------------------------- */
5994
Alexander Belopolsky40018472011-02-26 01:02:56 +00005995PyObject *
5996PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005997 Py_ssize_t size,
5998 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006000 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006001 Py_ssize_t startinpos;
6002 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006003 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004 const char *end;
6005 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006006 PyObject *errorHandler = NULL;
6007 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006008
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006009 if (size == 0)
6010 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006011
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 /* Escaped strings will always be longer than the resulting
6013 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006014 length after conversion to the true value. (But decoding error
6015 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006016 _PyUnicodeWriter_Init(&writer);
6017 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006018
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019 end = s + size;
6020 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006021 unsigned char c;
6022 Py_UCS4 x;
6023 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006024 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025
Benjamin Peterson29060642009-01-31 22:14:21 +00006026 /* Non-escape characters are interpreted as Unicode ordinals */
6027 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006028 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006029 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006030 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006032 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006033 startinpos = s-starts;
6034
6035 /* \u-escapes are only interpreted iff the number of leading
6036 backslashes if odd */
6037 bs = s;
6038 for (;s < end;) {
6039 if (*s != '\\')
6040 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006041 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006042 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006043 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 }
6045 if (((s - bs) & 1) == 0 ||
6046 s >= end ||
6047 (*s != 'u' && *s != 'U')) {
6048 continue;
6049 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006050 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 count = *s=='u' ? 4 : 8;
6052 s++;
6053
6054 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 for (x = 0, i = 0; i < count; ++i, ++s) {
6056 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006057 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006059 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 errors, &errorHandler,
6061 "rawunicodeescape", "truncated \\uXXXX",
6062 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006063 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006064 goto onError;
6065 goto nextByte;
6066 }
6067 x = (x<<4) & ~0xF;
6068 if (c >= '0' && c <= '9')
6069 x += c - '0';
6070 else if (c >= 'a' && c <= 'f')
6071 x += 10 + c - 'a';
6072 else
6073 x += 10 + c - 'A';
6074 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006075 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006076 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006077 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006078 }
6079 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006080 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006081 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006082 errors, &errorHandler,
6083 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006085 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006087 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 nextByte:
6089 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006091 Py_XDECREF(errorHandler);
6092 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006093 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006094
Benjamin Peterson29060642009-01-31 22:14:21 +00006095 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006096 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006097 Py_XDECREF(errorHandler);
6098 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006099 return NULL;
6100}
6101
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006102
Alexander Belopolsky40018472011-02-26 01:02:56 +00006103PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006104PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006105{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006106 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 char *p;
6108 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006109 Py_ssize_t expandsize, pos;
6110 int kind;
6111 void *data;
6112 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 if (!PyUnicode_Check(unicode)) {
6115 PyErr_BadArgument();
6116 return NULL;
6117 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006118 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 return NULL;
6120 kind = PyUnicode_KIND(unicode);
6121 data = PyUnicode_DATA(unicode);
6122 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006123 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6124 bytes, and 1 byte characters 4. */
6125 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006126
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006128 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006129
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006130 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 if (repr == NULL)
6132 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006134 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006136 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137 for (pos = 0; pos < len; pos++) {
6138 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006139 /* Map 32-bit characters to '\Uxxxxxxxx' */
6140 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006141 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006142 *p++ = '\\';
6143 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006144 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6145 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6146 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6147 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6148 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6149 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6150 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6151 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006152 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006155 *p++ = '\\';
6156 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006157 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6158 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6159 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6160 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006162 /* Copy everything else as-is */
6163 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006164 *p++ = (char) ch;
6165 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006166
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 assert(p > q);
6168 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006169 return NULL;
6170 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006171}
6172
Alexander Belopolsky40018472011-02-26 01:02:56 +00006173PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006174PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6175 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006176{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006177 PyObject *result;
6178 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6179 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006180 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006181 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6182 Py_DECREF(tmp);
6183 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184}
6185
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006186/* --- Unicode Internal Codec ------------------------------------------- */
6187
Alexander Belopolsky40018472011-02-26 01:02:56 +00006188PyObject *
6189_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006190 Py_ssize_t size,
6191 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006192{
6193 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006194 Py_ssize_t startinpos;
6195 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006196 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006197 const char *end;
6198 const char *reason;
6199 PyObject *errorHandler = NULL;
6200 PyObject *exc = NULL;
6201
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006202 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006203 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006204 1))
6205 return NULL;
6206
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006207 if (size == 0)
6208 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006209
Victor Stinner8f674cc2013-04-17 23:02:17 +02006210 _PyUnicodeWriter_Init(&writer);
6211 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6212 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006213 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006214 }
6215 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006216
Victor Stinner8f674cc2013-04-17 23:02:17 +02006217 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006218 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006219 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006220 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006221 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006222 endinpos = end-starts;
6223 reason = "truncated input";
6224 goto error;
6225 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006226 /* We copy the raw representation one byte at a time because the
6227 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006228 ((char *) &uch)[0] = s[0];
6229 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006230#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006231 ((char *) &uch)[2] = s[2];
6232 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006233#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006234 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006235#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006236 /* We have to sanity check the raw data, otherwise doom looms for
6237 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006238 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006239 endinpos = s - starts + Py_UNICODE_SIZE;
6240 reason = "illegal code point (> 0x10FFFF)";
6241 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006242 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006243#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006244 s += Py_UNICODE_SIZE;
6245#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006246 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006247 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006248 Py_UNICODE uch2;
6249 ((char *) &uch2)[0] = s[0];
6250 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006251 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006252 {
Victor Stinner551ac952011-11-29 22:58:13 +01006253 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006254 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006255 }
6256 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006257#endif
6258
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006259 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006260 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006261 continue;
6262
6263 error:
6264 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006265 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006266 errors, &errorHandler,
6267 "unicode_internal", reason,
6268 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006269 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006270 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006271 }
6272
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006273 Py_XDECREF(errorHandler);
6274 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006275 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006276
Benjamin Peterson29060642009-01-31 22:14:21 +00006277 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006278 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279 Py_XDECREF(errorHandler);
6280 Py_XDECREF(exc);
6281 return NULL;
6282}
6283
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284/* --- Latin-1 Codec ------------------------------------------------------ */
6285
Alexander Belopolsky40018472011-02-26 01:02:56 +00006286PyObject *
6287PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006288 Py_ssize_t size,
6289 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006290{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006292 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293}
6294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006295/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006296static void
6297make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006298 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006299 PyObject *unicode,
6300 Py_ssize_t startpos, Py_ssize_t endpos,
6301 const char *reason)
6302{
6303 if (*exceptionObject == NULL) {
6304 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006305 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006306 encoding, unicode, startpos, endpos, reason);
6307 }
6308 else {
6309 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6310 goto onError;
6311 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6312 goto onError;
6313 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6314 goto onError;
6315 return;
6316 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006317 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006318 }
6319}
6320
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006321/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006322static void
6323raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006324 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006325 PyObject *unicode,
6326 Py_ssize_t startpos, Py_ssize_t endpos,
6327 const char *reason)
6328{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006329 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006330 encoding, unicode, startpos, endpos, reason);
6331 if (*exceptionObject != NULL)
6332 PyCodec_StrictErrors(*exceptionObject);
6333}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006334
6335/* error handling callback helper:
6336 build arguments, call the callback and check the arguments,
6337 put the result into newpos and return the replacement string, which
6338 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006339static PyObject *
6340unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006341 PyObject **errorHandler,
6342 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006343 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006344 Py_ssize_t startpos, Py_ssize_t endpos,
6345 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006346{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006347 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006348 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006349 PyObject *restuple;
6350 PyObject *resunicode;
6351
6352 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006353 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006354 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356 }
6357
Benjamin Petersonbac79492012-01-14 13:34:47 -05006358 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 return NULL;
6360 len = PyUnicode_GET_LENGTH(unicode);
6361
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006362 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006363 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006364 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366
6367 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006372 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006373 Py_DECREF(restuple);
6374 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006375 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006376 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 &resunicode, newpos)) {
6378 Py_DECREF(restuple);
6379 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006380 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006381 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6382 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6383 Py_DECREF(restuple);
6384 return NULL;
6385 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006387 *newpos = len + *newpos;
6388 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006389 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 Py_DECREF(restuple);
6391 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006392 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006393 Py_INCREF(resunicode);
6394 Py_DECREF(restuple);
6395 return resunicode;
6396}
6397
Alexander Belopolsky40018472011-02-26 01:02:56 +00006398static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006399unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006400 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006401 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 /* input state */
6404 Py_ssize_t pos=0, size;
6405 int kind;
6406 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407 /* output object */
6408 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 /* pointer into the output */
6410 char *str;
6411 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006412 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006413 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6414 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006415 PyObject *errorHandler = NULL;
6416 PyObject *exc = NULL;
6417 /* the following variable is used for caching string comparisons
6418 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6419 int known_errorHandler = -1;
6420
Benjamin Petersonbac79492012-01-14 13:34:47 -05006421 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422 return NULL;
6423 size = PyUnicode_GET_LENGTH(unicode);
6424 kind = PyUnicode_KIND(unicode);
6425 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 /* allocate enough for a simple encoding without
6427 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006428 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006429 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006430 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006432 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006433 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 ressize = size;
6435
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006436 while (pos < size) {
6437 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438
Benjamin Peterson29060642009-01-31 22:14:21 +00006439 /* can we encode this? */
6440 if (c<limit) {
6441 /* no overflow check, because we know that the space is enough */
6442 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006443 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006444 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006445 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006446 Py_ssize_t requiredsize;
6447 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006449 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006450 Py_ssize_t collstart = pos;
6451 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006452 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006453 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006454 ++collend;
6455 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6456 if (known_errorHandler==-1) {
6457 if ((errors==NULL) || (!strcmp(errors, "strict")))
6458 known_errorHandler = 1;
6459 else if (!strcmp(errors, "replace"))
6460 known_errorHandler = 2;
6461 else if (!strcmp(errors, "ignore"))
6462 known_errorHandler = 3;
6463 else if (!strcmp(errors, "xmlcharrefreplace"))
6464 known_errorHandler = 4;
6465 else
6466 known_errorHandler = 0;
6467 }
6468 switch (known_errorHandler) {
6469 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006470 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 goto onError;
6472 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006473 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006474 *str++ = '?'; /* fall through */
6475 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 break;
6478 case 4: /* xmlcharrefreplace */
6479 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006480 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006482 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006484 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006485 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006486 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006488 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006489 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006490 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006492 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006493 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006494 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006496 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006497 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006498 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006499 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006500 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006501 if (requiredsize > PY_SSIZE_T_MAX - incr)
6502 goto overflow;
6503 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006505 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6506 goto overflow;
6507 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006508 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006509 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 requiredsize = 2*ressize;
6511 if (_PyBytes_Resize(&res, requiredsize))
6512 goto onError;
6513 str = PyBytes_AS_STRING(res) + respos;
6514 ressize = requiredsize;
6515 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006516 /* generate replacement */
6517 for (i = collstart; i < collend; ++i) {
6518 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006520 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 break;
6522 default:
6523 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006524 encoding, reason, unicode, &exc,
6525 collstart, collend, &newpos);
6526 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006527 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006528 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006529 if (PyBytes_Check(repunicode)) {
6530 /* Directly copy bytes result to output. */
6531 repsize = PyBytes_Size(repunicode);
6532 if (repsize > 1) {
6533 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006534 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006535 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6536 Py_DECREF(repunicode);
6537 goto overflow;
6538 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006539 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6540 Py_DECREF(repunicode);
6541 goto onError;
6542 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006543 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006544 ressize += repsize-1;
6545 }
6546 memcpy(str, PyBytes_AsString(repunicode), repsize);
6547 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006549 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006550 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006551 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 /* need more space? (at least enough for what we
6553 have+the replacement+the rest of the string, so
6554 we won't have to check space for encodable characters) */
6555 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006556 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006557 requiredsize = respos;
6558 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6559 goto overflow;
6560 requiredsize += repsize;
6561 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6562 goto overflow;
6563 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006565 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 requiredsize = 2*ressize;
6567 if (_PyBytes_Resize(&res, requiredsize)) {
6568 Py_DECREF(repunicode);
6569 goto onError;
6570 }
6571 str = PyBytes_AS_STRING(res) + respos;
6572 ressize = requiredsize;
6573 }
6574 /* check if there is anything unencodable in the replacement
6575 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006576 for (i = 0; repsize-->0; ++i, ++str) {
6577 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006579 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 Py_DECREF(repunicode);
6582 goto onError;
6583 }
6584 *str = (char)c;
6585 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006586 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006587 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006588 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006589 }
6590 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006591 /* Resize if we allocated to much */
6592 size = str - PyBytes_AS_STRING(res);
6593 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006594 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006595 if (_PyBytes_Resize(&res, size) < 0)
6596 goto onError;
6597 }
6598
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599 Py_XDECREF(errorHandler);
6600 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006601 return res;
6602
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006603 overflow:
6604 PyErr_SetString(PyExc_OverflowError,
6605 "encoded result is too long for a Python string");
6606
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006607 onError:
6608 Py_XDECREF(res);
6609 Py_XDECREF(errorHandler);
6610 Py_XDECREF(exc);
6611 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006612}
6613
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006615PyObject *
6616PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006617 Py_ssize_t size,
6618 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620 PyObject *result;
6621 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6622 if (unicode == NULL)
6623 return NULL;
6624 result = unicode_encode_ucs1(unicode, errors, 256);
6625 Py_DECREF(unicode);
6626 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627}
6628
Alexander Belopolsky40018472011-02-26 01:02:56 +00006629PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006630_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631{
6632 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 PyErr_BadArgument();
6634 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006636 if (PyUnicode_READY(unicode) == -1)
6637 return NULL;
6638 /* Fast path: if it is a one-byte string, construct
6639 bytes object directly. */
6640 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6641 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6642 PyUnicode_GET_LENGTH(unicode));
6643 /* Non-Latin-1 characters present. Defer to above function to
6644 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006646}
6647
6648PyObject*
6649PyUnicode_AsLatin1String(PyObject *unicode)
6650{
6651 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006652}
6653
6654/* --- 7-bit ASCII Codec -------------------------------------------------- */
6655
Alexander Belopolsky40018472011-02-26 01:02:56 +00006656PyObject *
6657PyUnicode_DecodeASCII(const char *s,
6658 Py_ssize_t size,
6659 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006660{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006662 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006663 int kind;
6664 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006665 Py_ssize_t startinpos;
6666 Py_ssize_t endinpos;
6667 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 const char *e;
6669 PyObject *errorHandler = NULL;
6670 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006671
Guido van Rossumd57fd912000-03-10 22:53:23 +00006672 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006673 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006674
Guido van Rossumd57fd912000-03-10 22:53:23 +00006675 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006676 if (size == 1 && (unsigned char)s[0] < 128)
6677 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006678
Victor Stinner8f674cc2013-04-17 23:02:17 +02006679 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006680 writer.min_length = size;
6681 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006682 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006683
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006684 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006685 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006686 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006687 writer.pos = outpos;
6688 if (writer.pos == size)
6689 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006690
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006691 s += writer.pos;
6692 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006694 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006695 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006696 PyUnicode_WRITE(kind, data, writer.pos, c);
6697 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 ++s;
6699 }
6700 else {
6701 startinpos = s-starts;
6702 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006703 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 errors, &errorHandler,
6705 "ascii", "ordinal not in range(128)",
6706 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006707 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006709 kind = writer.kind;
6710 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713 Py_XDECREF(errorHandler);
6714 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006715 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006716
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006718 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006719 Py_XDECREF(errorHandler);
6720 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721 return NULL;
6722}
6723
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006724/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006725PyObject *
6726PyUnicode_EncodeASCII(const Py_UNICODE *p,
6727 Py_ssize_t size,
6728 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006729{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 PyObject *result;
6731 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6732 if (unicode == NULL)
6733 return NULL;
6734 result = unicode_encode_ucs1(unicode, errors, 128);
6735 Py_DECREF(unicode);
6736 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006737}
6738
Alexander Belopolsky40018472011-02-26 01:02:56 +00006739PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006740_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006741{
6742 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 PyErr_BadArgument();
6744 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006746 if (PyUnicode_READY(unicode) == -1)
6747 return NULL;
6748 /* Fast path: if it is an ASCII-only string, construct bytes object
6749 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006750 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006751 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6752 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006753 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006754}
6755
6756PyObject *
6757PyUnicode_AsASCIIString(PyObject *unicode)
6758{
6759 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760}
6761
Victor Stinner99b95382011-07-04 14:23:54 +02006762#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006763
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006764/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006765
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006766#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006767#define NEED_RETRY
6768#endif
6769
Victor Stinner3a50e702011-10-18 21:21:00 +02006770#ifndef WC_ERR_INVALID_CHARS
6771# define WC_ERR_INVALID_CHARS 0x0080
6772#endif
6773
6774static char*
6775code_page_name(UINT code_page, PyObject **obj)
6776{
6777 *obj = NULL;
6778 if (code_page == CP_ACP)
6779 return "mbcs";
6780 if (code_page == CP_UTF7)
6781 return "CP_UTF7";
6782 if (code_page == CP_UTF8)
6783 return "CP_UTF8";
6784
6785 *obj = PyBytes_FromFormat("cp%u", code_page);
6786 if (*obj == NULL)
6787 return NULL;
6788 return PyBytes_AS_STRING(*obj);
6789}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006790
Victor Stinner3a50e702011-10-18 21:21:00 +02006791static DWORD
6792decode_code_page_flags(UINT code_page)
6793{
6794 if (code_page == CP_UTF7) {
6795 /* The CP_UTF7 decoder only supports flags=0 */
6796 return 0;
6797 }
6798 else
6799 return MB_ERR_INVALID_CHARS;
6800}
6801
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006802/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006803 * Decode a byte string from a Windows code page into unicode object in strict
6804 * mode.
6805 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006806 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6807 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006808 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006809static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006810decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006811 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006812 const char *in,
6813 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006814{
Victor Stinner3a50e702011-10-18 21:21:00 +02006815 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006816 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006817 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006818
6819 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006820 assert(insize > 0);
6821 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6822 if (outsize <= 0)
6823 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006824
6825 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006826 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006827 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006828 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006829 if (*v == NULL)
6830 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006831 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006832 }
6833 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006834 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006835 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006836 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006838 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006839 }
6840
6841 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006842 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6843 if (outsize <= 0)
6844 goto error;
6845 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006846
Victor Stinner3a50e702011-10-18 21:21:00 +02006847error:
6848 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6849 return -2;
6850 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006851 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006852}
6853
Victor Stinner3a50e702011-10-18 21:21:00 +02006854/*
6855 * Decode a byte string from a code page into unicode object with an error
6856 * handler.
6857 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006858 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006859 * UnicodeDecodeError exception and returns -1 on error.
6860 */
6861static int
6862decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006863 PyObject **v,
6864 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006865 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006866{
6867 const char *startin = in;
6868 const char *endin = in + size;
6869 const DWORD flags = decode_code_page_flags(code_page);
6870 /* Ideally, we should get reason from FormatMessage. This is the Windows
6871 2000 English version of the message. */
6872 const char *reason = "No mapping for the Unicode character exists "
6873 "in the target code page.";
6874 /* each step cannot decode more than 1 character, but a character can be
6875 represented as a surrogate pair */
6876 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006877 int insize;
6878 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006879 PyObject *errorHandler = NULL;
6880 PyObject *exc = NULL;
6881 PyObject *encoding_obj = NULL;
6882 char *encoding;
6883 DWORD err;
6884 int ret = -1;
6885
6886 assert(size > 0);
6887
6888 encoding = code_page_name(code_page, &encoding_obj);
6889 if (encoding == NULL)
6890 return -1;
6891
Victor Stinner7d00cc12014-03-17 23:08:06 +01006892 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006893 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6894 UnicodeDecodeError. */
6895 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6896 if (exc != NULL) {
6897 PyCodec_StrictErrors(exc);
6898 Py_CLEAR(exc);
6899 }
6900 goto error;
6901 }
6902
6903 if (*v == NULL) {
6904 /* Create unicode object */
6905 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6906 PyErr_NoMemory();
6907 goto error;
6908 }
Victor Stinnerab595942011-12-17 04:59:06 +01006909 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006910 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006911 if (*v == NULL)
6912 goto error;
6913 startout = PyUnicode_AS_UNICODE(*v);
6914 }
6915 else {
6916 /* Extend unicode object */
6917 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6918 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6919 PyErr_NoMemory();
6920 goto error;
6921 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006922 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006923 goto error;
6924 startout = PyUnicode_AS_UNICODE(*v) + n;
6925 }
6926
6927 /* Decode the byte string character per character */
6928 out = startout;
6929 while (in < endin)
6930 {
6931 /* Decode a character */
6932 insize = 1;
6933 do
6934 {
6935 outsize = MultiByteToWideChar(code_page, flags,
6936 in, insize,
6937 buffer, Py_ARRAY_LENGTH(buffer));
6938 if (outsize > 0)
6939 break;
6940 err = GetLastError();
6941 if (err != ERROR_NO_UNICODE_TRANSLATION
6942 && err != ERROR_INSUFFICIENT_BUFFER)
6943 {
6944 PyErr_SetFromWindowsErr(0);
6945 goto error;
6946 }
6947 insize++;
6948 }
6949 /* 4=maximum length of a UTF-8 sequence */
6950 while (insize <= 4 && (in + insize) <= endin);
6951
6952 if (outsize <= 0) {
6953 Py_ssize_t startinpos, endinpos, outpos;
6954
Victor Stinner7d00cc12014-03-17 23:08:06 +01006955 /* last character in partial decode? */
6956 if (in + insize >= endin && !final)
6957 break;
6958
Victor Stinner3a50e702011-10-18 21:21:00 +02006959 startinpos = in - startin;
6960 endinpos = startinpos + 1;
6961 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006962 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006963 errors, &errorHandler,
6964 encoding, reason,
6965 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006966 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006967 {
6968 goto error;
6969 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006970 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 }
6972 else {
6973 in += insize;
6974 memcpy(out, buffer, outsize * sizeof(wchar_t));
6975 out += outsize;
6976 }
6977 }
6978
6979 /* write a NUL character at the end */
6980 *out = 0;
6981
6982 /* Extend unicode object */
6983 outsize = out - startout;
6984 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006985 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006986 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02006987 /* (in - startin) <= size and size is an int */
6988 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02006989
6990error:
6991 Py_XDECREF(encoding_obj);
6992 Py_XDECREF(errorHandler);
6993 Py_XDECREF(exc);
6994 return ret;
6995}
6996
Victor Stinner3a50e702011-10-18 21:21:00 +02006997static PyObject *
6998decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006999 const char *s, Py_ssize_t size,
7000 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007001{
Victor Stinner76a31a62011-11-04 00:05:13 +01007002 PyObject *v = NULL;
7003 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007004
Victor Stinner3a50e702011-10-18 21:21:00 +02007005 if (code_page < 0) {
7006 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7007 return NULL;
7008 }
7009
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007010 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007011 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007012
Victor Stinner76a31a62011-11-04 00:05:13 +01007013 do
7014 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007015#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007016 if (size > INT_MAX) {
7017 chunk_size = INT_MAX;
7018 final = 0;
7019 done = 0;
7020 }
7021 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007022#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007023 {
7024 chunk_size = (int)size;
7025 final = (consumed == NULL);
7026 done = 1;
7027 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007028
Victor Stinner76a31a62011-11-04 00:05:13 +01007029 if (chunk_size == 0 && done) {
7030 if (v != NULL)
7031 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007032 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007033 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034
Victor Stinner76a31a62011-11-04 00:05:13 +01007035 converted = decode_code_page_strict(code_page, &v,
7036 s, chunk_size);
7037 if (converted == -2)
7038 converted = decode_code_page_errors(code_page, &v,
7039 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007040 errors, final);
7041 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007042
7043 if (converted < 0) {
7044 Py_XDECREF(v);
7045 return NULL;
7046 }
7047
7048 if (consumed)
7049 *consumed += converted;
7050
7051 s += converted;
7052 size -= converted;
7053 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007054
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007055 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007056}
7057
Alexander Belopolsky40018472011-02-26 01:02:56 +00007058PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007059PyUnicode_DecodeCodePageStateful(int code_page,
7060 const char *s,
7061 Py_ssize_t size,
7062 const char *errors,
7063 Py_ssize_t *consumed)
7064{
7065 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7066}
7067
7068PyObject *
7069PyUnicode_DecodeMBCSStateful(const char *s,
7070 Py_ssize_t size,
7071 const char *errors,
7072 Py_ssize_t *consumed)
7073{
7074 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7075}
7076
7077PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007078PyUnicode_DecodeMBCS(const char *s,
7079 Py_ssize_t size,
7080 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007081{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007082 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7083}
7084
Victor Stinner3a50e702011-10-18 21:21:00 +02007085static DWORD
7086encode_code_page_flags(UINT code_page, const char *errors)
7087{
7088 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007089 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 }
7091 else if (code_page == CP_UTF7) {
7092 /* CP_UTF7 only supports flags=0 */
7093 return 0;
7094 }
7095 else {
7096 if (errors != NULL && strcmp(errors, "replace") == 0)
7097 return 0;
7098 else
7099 return WC_NO_BEST_FIT_CHARS;
7100 }
7101}
7102
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 * Encode a Unicode string to a Windows code page into a byte string in strict
7105 * mode.
7106 *
7107 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007108 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007110static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007111encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007112 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114{
Victor Stinner554f3f02010-06-16 23:33:54 +00007115 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 BOOL *pusedDefaultChar = &usedDefaultChar;
7117 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007118 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007119 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007120 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 const DWORD flags = encode_code_page_flags(code_page, NULL);
7122 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007123 /* Create a substring so that we can get the UTF-16 representation
7124 of just the slice under consideration. */
7125 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126
Martin v. Löwis3d325192011-11-04 18:23:06 +01007127 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007128
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007130 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007131 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007132 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007133
Victor Stinner2fc507f2011-11-04 20:06:39 +01007134 substring = PyUnicode_Substring(unicode, offset, offset+len);
7135 if (substring == NULL)
7136 return -1;
7137 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7138 if (p == NULL) {
7139 Py_DECREF(substring);
7140 return -1;
7141 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007142 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007143
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007144 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007146 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 NULL, 0,
7148 NULL, pusedDefaultChar);
7149 if (outsize <= 0)
7150 goto error;
7151 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007152 if (pusedDefaultChar && *pusedDefaultChar) {
7153 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007154 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007155 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007156
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007158 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007160 if (*outbytes == NULL) {
7161 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007162 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007163 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007164 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007165 }
7166 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007167 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 const Py_ssize_t n = PyBytes_Size(*outbytes);
7169 if (outsize > PY_SSIZE_T_MAX - n) {
7170 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007171 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007172 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007174 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7175 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007177 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007179 }
7180
7181 /* Do the conversion */
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 out, outsize,
7185 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007186 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 if (outsize <= 0)
7188 goto error;
7189 if (pusedDefaultChar && *pusedDefaultChar)
7190 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007191 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007192
Victor Stinner3a50e702011-10-18 21:21:00 +02007193error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007194 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7196 return -2;
7197 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007198 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007199}
7200
Victor Stinner3a50e702011-10-18 21:21:00 +02007201/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007202 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007203 * error handler.
7204 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007205 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 * -1 on other error.
7207 */
7208static int
7209encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007210 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007211 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007212{
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 Py_ssize_t pos = unicode_offset;
7215 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 /* Ideally, we should get reason from FormatMessage. This is the Windows
7217 2000 English version of the message. */
7218 const char *reason = "invalid character";
7219 /* 4=maximum length of a UTF-8 sequence */
7220 char buffer[4];
7221 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7222 Py_ssize_t outsize;
7223 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 PyObject *errorHandler = NULL;
7225 PyObject *exc = NULL;
7226 PyObject *encoding_obj = NULL;
7227 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007228 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 PyObject *rep;
7230 int ret = -1;
7231
7232 assert(insize > 0);
7233
7234 encoding = code_page_name(code_page, &encoding_obj);
7235 if (encoding == NULL)
7236 return -1;
7237
7238 if (errors == NULL || strcmp(errors, "strict") == 0) {
7239 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7240 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007241 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 if (exc != NULL) {
7243 PyCodec_StrictErrors(exc);
7244 Py_DECREF(exc);
7245 }
7246 Py_XDECREF(encoding_obj);
7247 return -1;
7248 }
7249
7250 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7251 pusedDefaultChar = &usedDefaultChar;
7252 else
7253 pusedDefaultChar = NULL;
7254
7255 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7256 PyErr_NoMemory();
7257 goto error;
7258 }
7259 outsize = insize * Py_ARRAY_LENGTH(buffer);
7260
7261 if (*outbytes == NULL) {
7262 /* Create string object */
7263 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7264 if (*outbytes == NULL)
7265 goto error;
7266 out = PyBytes_AS_STRING(*outbytes);
7267 }
7268 else {
7269 /* Extend string object */
7270 Py_ssize_t n = PyBytes_Size(*outbytes);
7271 if (n > PY_SSIZE_T_MAX - outsize) {
7272 PyErr_NoMemory();
7273 goto error;
7274 }
7275 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7276 goto error;
7277 out = PyBytes_AS_STRING(*outbytes) + n;
7278 }
7279
7280 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007281 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007282 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007283 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7284 wchar_t chars[2];
7285 int charsize;
7286 if (ch < 0x10000) {
7287 chars[0] = (wchar_t)ch;
7288 charsize = 1;
7289 }
7290 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007291 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7292 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007293 charsize = 2;
7294 }
7295
Victor Stinner3a50e702011-10-18 21:21:00 +02007296 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007297 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007298 buffer, Py_ARRAY_LENGTH(buffer),
7299 NULL, pusedDefaultChar);
7300 if (outsize > 0) {
7301 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7302 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007303 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 memcpy(out, buffer, outsize);
7305 out += outsize;
7306 continue;
7307 }
7308 }
7309 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7310 PyErr_SetFromWindowsErr(0);
7311 goto error;
7312 }
7313
Victor Stinner3a50e702011-10-18 21:21:00 +02007314 rep = unicode_encode_call_errorhandler(
7315 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007316 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007317 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 if (rep == NULL)
7319 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007320 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007321
7322 if (PyBytes_Check(rep)) {
7323 outsize = PyBytes_GET_SIZE(rep);
7324 if (outsize != 1) {
7325 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7326 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7327 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7328 Py_DECREF(rep);
7329 goto error;
7330 }
7331 out = PyBytes_AS_STRING(*outbytes) + offset;
7332 }
7333 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7334 out += outsize;
7335 }
7336 else {
7337 Py_ssize_t i;
7338 enum PyUnicode_Kind kind;
7339 void *data;
7340
Benjamin Petersonbac79492012-01-14 13:34:47 -05007341 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007342 Py_DECREF(rep);
7343 goto error;
7344 }
7345
7346 outsize = PyUnicode_GET_LENGTH(rep);
7347 if (outsize != 1) {
7348 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7349 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7350 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7351 Py_DECREF(rep);
7352 goto error;
7353 }
7354 out = PyBytes_AS_STRING(*outbytes) + offset;
7355 }
7356 kind = PyUnicode_KIND(rep);
7357 data = PyUnicode_DATA(rep);
7358 for (i=0; i < outsize; i++) {
7359 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7360 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007361 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007362 encoding, unicode,
7363 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 "unable to encode error handler result to ASCII");
7365 Py_DECREF(rep);
7366 goto error;
7367 }
7368 *out = (unsigned char)ch;
7369 out++;
7370 }
7371 }
7372 Py_DECREF(rep);
7373 }
7374 /* write a NUL byte */
7375 *out = 0;
7376 outsize = out - PyBytes_AS_STRING(*outbytes);
7377 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7378 if (_PyBytes_Resize(outbytes, outsize) < 0)
7379 goto error;
7380 ret = 0;
7381
7382error:
7383 Py_XDECREF(encoding_obj);
7384 Py_XDECREF(errorHandler);
7385 Py_XDECREF(exc);
7386 return ret;
7387}
7388
Victor Stinner3a50e702011-10-18 21:21:00 +02007389static PyObject *
7390encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007391 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 const char *errors)
7393{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007394 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007396 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007397 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007398
Victor Stinner29dacf22015-01-26 16:41:32 +01007399 if (!PyUnicode_Check(unicode)) {
7400 PyErr_BadArgument();
7401 return NULL;
7402 }
7403
Benjamin Petersonbac79492012-01-14 13:34:47 -05007404 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007405 return NULL;
7406 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007407
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 if (code_page < 0) {
7409 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7410 return NULL;
7411 }
7412
Martin v. Löwis3d325192011-11-04 18:23:06 +01007413 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007414 return PyBytes_FromStringAndSize(NULL, 0);
7415
Victor Stinner7581cef2011-11-03 22:32:33 +01007416 offset = 0;
7417 do
7418 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007419#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007420 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007421 chunks. */
7422 if (len > INT_MAX/2) {
7423 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007424 done = 0;
7425 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007426 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007427#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007428 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007429 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007430 done = 1;
7431 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432
Victor Stinner76a31a62011-11-04 00:05:13 +01007433 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007434 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007435 errors);
7436 if (ret == -2)
7437 ret = encode_code_page_errors(code_page, &outbytes,
7438 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007439 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007440 if (ret < 0) {
7441 Py_XDECREF(outbytes);
7442 return NULL;
7443 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007444
Victor Stinner7581cef2011-11-03 22:32:33 +01007445 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007446 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007447 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007448
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 return outbytes;
7450}
7451
7452PyObject *
7453PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7454 Py_ssize_t size,
7455 const char *errors)
7456{
Victor Stinner7581cef2011-11-03 22:32:33 +01007457 PyObject *unicode, *res;
7458 unicode = PyUnicode_FromUnicode(p, size);
7459 if (unicode == NULL)
7460 return NULL;
7461 res = encode_code_page(CP_ACP, unicode, errors);
7462 Py_DECREF(unicode);
7463 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007464}
7465
7466PyObject *
7467PyUnicode_EncodeCodePage(int code_page,
7468 PyObject *unicode,
7469 const char *errors)
7470{
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007472}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007473
Alexander Belopolsky40018472011-02-26 01:02:56 +00007474PyObject *
7475PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007476{
Victor Stinner7581cef2011-11-03 22:32:33 +01007477 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007478}
7479
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007480#undef NEED_RETRY
7481
Victor Stinner99b95382011-07-04 14:23:54 +02007482#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007483
Guido van Rossumd57fd912000-03-10 22:53:23 +00007484/* --- Character Mapping Codec -------------------------------------------- */
7485
Victor Stinnerfb161b12013-04-18 01:44:27 +02007486static int
7487charmap_decode_string(const char *s,
7488 Py_ssize_t size,
7489 PyObject *mapping,
7490 const char *errors,
7491 _PyUnicodeWriter *writer)
7492{
7493 const char *starts = s;
7494 const char *e;
7495 Py_ssize_t startinpos, endinpos;
7496 PyObject *errorHandler = NULL, *exc = NULL;
7497 Py_ssize_t maplen;
7498 enum PyUnicode_Kind mapkind;
7499 void *mapdata;
7500 Py_UCS4 x;
7501 unsigned char ch;
7502
7503 if (PyUnicode_READY(mapping) == -1)
7504 return -1;
7505
7506 maplen = PyUnicode_GET_LENGTH(mapping);
7507 mapdata = PyUnicode_DATA(mapping);
7508 mapkind = PyUnicode_KIND(mapping);
7509
7510 e = s + size;
7511
7512 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7513 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7514 * is disabled in encoding aliases, latin1 is preferred because
7515 * its implementation is faster. */
7516 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7517 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7518 Py_UCS4 maxchar = writer->maxchar;
7519
7520 assert (writer->kind == PyUnicode_1BYTE_KIND);
7521 while (s < e) {
7522 ch = *s;
7523 x = mapdata_ucs1[ch];
7524 if (x > maxchar) {
7525 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7526 goto onError;
7527 maxchar = writer->maxchar;
7528 outdata = (Py_UCS1 *)writer->data;
7529 }
7530 outdata[writer->pos] = x;
7531 writer->pos++;
7532 ++s;
7533 }
7534 return 0;
7535 }
7536
7537 while (s < e) {
7538 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7539 enum PyUnicode_Kind outkind = writer->kind;
7540 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7541 if (outkind == PyUnicode_1BYTE_KIND) {
7542 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7543 Py_UCS4 maxchar = writer->maxchar;
7544 while (s < e) {
7545 ch = *s;
7546 x = mapdata_ucs2[ch];
7547 if (x > maxchar)
7548 goto Error;
7549 outdata[writer->pos] = x;
7550 writer->pos++;
7551 ++s;
7552 }
7553 break;
7554 }
7555 else if (outkind == PyUnicode_2BYTE_KIND) {
7556 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7557 while (s < e) {
7558 ch = *s;
7559 x = mapdata_ucs2[ch];
7560 if (x == 0xFFFE)
7561 goto Error;
7562 outdata[writer->pos] = x;
7563 writer->pos++;
7564 ++s;
7565 }
7566 break;
7567 }
7568 }
7569 ch = *s;
7570
7571 if (ch < maplen)
7572 x = PyUnicode_READ(mapkind, mapdata, ch);
7573 else
7574 x = 0xfffe; /* invalid value */
7575Error:
7576 if (x == 0xfffe)
7577 {
7578 /* undefined mapping */
7579 startinpos = s-starts;
7580 endinpos = startinpos+1;
7581 if (unicode_decode_call_errorhandler_writer(
7582 errors, &errorHandler,
7583 "charmap", "character maps to <undefined>",
7584 &starts, &e, &startinpos, &endinpos, &exc, &s,
7585 writer)) {
7586 goto onError;
7587 }
7588 continue;
7589 }
7590
7591 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7592 goto onError;
7593 ++s;
7594 }
7595 Py_XDECREF(errorHandler);
7596 Py_XDECREF(exc);
7597 return 0;
7598
7599onError:
7600 Py_XDECREF(errorHandler);
7601 Py_XDECREF(exc);
7602 return -1;
7603}
7604
7605static int
7606charmap_decode_mapping(const char *s,
7607 Py_ssize_t size,
7608 PyObject *mapping,
7609 const char *errors,
7610 _PyUnicodeWriter *writer)
7611{
7612 const char *starts = s;
7613 const char *e;
7614 Py_ssize_t startinpos, endinpos;
7615 PyObject *errorHandler = NULL, *exc = NULL;
7616 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007617 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007618
7619 e = s + size;
7620
7621 while (s < e) {
7622 ch = *s;
7623
7624 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7625 key = PyLong_FromLong((long)ch);
7626 if (key == NULL)
7627 goto onError;
7628
7629 item = PyObject_GetItem(mapping, key);
7630 Py_DECREF(key);
7631 if (item == NULL) {
7632 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7633 /* No mapping found means: mapping is undefined. */
7634 PyErr_Clear();
7635 goto Undefined;
7636 } else
7637 goto onError;
7638 }
7639
7640 /* Apply mapping */
7641 if (item == Py_None)
7642 goto Undefined;
7643 if (PyLong_Check(item)) {
7644 long value = PyLong_AS_LONG(item);
7645 if (value == 0xFFFE)
7646 goto Undefined;
7647 if (value < 0 || value > MAX_UNICODE) {
7648 PyErr_Format(PyExc_TypeError,
7649 "character mapping must be in range(0x%lx)",
7650 (unsigned long)MAX_UNICODE + 1);
7651 goto onError;
7652 }
7653
7654 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7655 goto onError;
7656 }
7657 else if (PyUnicode_Check(item)) {
7658 if (PyUnicode_READY(item) == -1)
7659 goto onError;
7660 if (PyUnicode_GET_LENGTH(item) == 1) {
7661 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7662 if (value == 0xFFFE)
7663 goto Undefined;
7664 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7665 goto onError;
7666 }
7667 else {
7668 writer->overallocate = 1;
7669 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7670 goto onError;
7671 }
7672 }
7673 else {
7674 /* wrong return value */
7675 PyErr_SetString(PyExc_TypeError,
7676 "character mapping must return integer, None or str");
7677 goto onError;
7678 }
7679 Py_CLEAR(item);
7680 ++s;
7681 continue;
7682
7683Undefined:
7684 /* undefined mapping */
7685 Py_CLEAR(item);
7686 startinpos = s-starts;
7687 endinpos = startinpos+1;
7688 if (unicode_decode_call_errorhandler_writer(
7689 errors, &errorHandler,
7690 "charmap", "character maps to <undefined>",
7691 &starts, &e, &startinpos, &endinpos, &exc, &s,
7692 writer)) {
7693 goto onError;
7694 }
7695 }
7696 Py_XDECREF(errorHandler);
7697 Py_XDECREF(exc);
7698 return 0;
7699
7700onError:
7701 Py_XDECREF(item);
7702 Py_XDECREF(errorHandler);
7703 Py_XDECREF(exc);
7704 return -1;
7705}
7706
Alexander Belopolsky40018472011-02-26 01:02:56 +00007707PyObject *
7708PyUnicode_DecodeCharmap(const char *s,
7709 Py_ssize_t size,
7710 PyObject *mapping,
7711 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007712{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007713 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007714
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715 /* Default to Latin-1 */
7716 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007717 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007718
Guido van Rossumd57fd912000-03-10 22:53:23 +00007719 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007720 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007721 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007722 writer.min_length = size;
7723 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007724 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007725
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007726 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007727 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7728 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007729 }
7730 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007731 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7732 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007733 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007734 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007735
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007737 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007738 return NULL;
7739}
7740
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007741/* Charmap encoding: the lookup table */
7742
Alexander Belopolsky40018472011-02-26 01:02:56 +00007743struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007744 PyObject_HEAD
7745 unsigned char level1[32];
7746 int count2, count3;
7747 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007748};
7749
7750static PyObject*
7751encoding_map_size(PyObject *obj, PyObject* args)
7752{
7753 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007754 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007755 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007756}
7757
7758static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007759 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 PyDoc_STR("Return the size (in bytes) of this object") },
7761 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007762};
7763
7764static void
7765encoding_map_dealloc(PyObject* o)
7766{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007767 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007768}
7769
7770static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007771 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007772 "EncodingMap", /*tp_name*/
7773 sizeof(struct encoding_map), /*tp_basicsize*/
7774 0, /*tp_itemsize*/
7775 /* methods */
7776 encoding_map_dealloc, /*tp_dealloc*/
7777 0, /*tp_print*/
7778 0, /*tp_getattr*/
7779 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007780 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007781 0, /*tp_repr*/
7782 0, /*tp_as_number*/
7783 0, /*tp_as_sequence*/
7784 0, /*tp_as_mapping*/
7785 0, /*tp_hash*/
7786 0, /*tp_call*/
7787 0, /*tp_str*/
7788 0, /*tp_getattro*/
7789 0, /*tp_setattro*/
7790 0, /*tp_as_buffer*/
7791 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7792 0, /*tp_doc*/
7793 0, /*tp_traverse*/
7794 0, /*tp_clear*/
7795 0, /*tp_richcompare*/
7796 0, /*tp_weaklistoffset*/
7797 0, /*tp_iter*/
7798 0, /*tp_iternext*/
7799 encoding_map_methods, /*tp_methods*/
7800 0, /*tp_members*/
7801 0, /*tp_getset*/
7802 0, /*tp_base*/
7803 0, /*tp_dict*/
7804 0, /*tp_descr_get*/
7805 0, /*tp_descr_set*/
7806 0, /*tp_dictoffset*/
7807 0, /*tp_init*/
7808 0, /*tp_alloc*/
7809 0, /*tp_new*/
7810 0, /*tp_free*/
7811 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007812};
7813
7814PyObject*
7815PyUnicode_BuildEncodingMap(PyObject* string)
7816{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007817 PyObject *result;
7818 struct encoding_map *mresult;
7819 int i;
7820 int need_dict = 0;
7821 unsigned char level1[32];
7822 unsigned char level2[512];
7823 unsigned char *mlevel1, *mlevel2, *mlevel3;
7824 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007825 int kind;
7826 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007827 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007828 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007830 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007831 PyErr_BadArgument();
7832 return NULL;
7833 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007834 kind = PyUnicode_KIND(string);
7835 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007836 length = PyUnicode_GET_LENGTH(string);
7837 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838 memset(level1, 0xFF, sizeof level1);
7839 memset(level2, 0xFF, sizeof level2);
7840
7841 /* If there isn't a one-to-one mapping of NULL to \0,
7842 or if there are non-BMP characters, we need to use
7843 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007844 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007845 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007846 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007847 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007848 ch = PyUnicode_READ(kind, data, i);
7849 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007850 need_dict = 1;
7851 break;
7852 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007853 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854 /* unmapped character */
7855 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007856 l1 = ch >> 11;
7857 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858 if (level1[l1] == 0xFF)
7859 level1[l1] = count2++;
7860 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007861 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007862 }
7863
7864 if (count2 >= 0xFF || count3 >= 0xFF)
7865 need_dict = 1;
7866
7867 if (need_dict) {
7868 PyObject *result = PyDict_New();
7869 PyObject *key, *value;
7870 if (!result)
7871 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007872 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007873 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007874 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 if (!key || !value)
7876 goto failed1;
7877 if (PyDict_SetItem(result, key, value) == -1)
7878 goto failed1;
7879 Py_DECREF(key);
7880 Py_DECREF(value);
7881 }
7882 return result;
7883 failed1:
7884 Py_XDECREF(key);
7885 Py_XDECREF(value);
7886 Py_DECREF(result);
7887 return NULL;
7888 }
7889
7890 /* Create a three-level trie */
7891 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7892 16*count2 + 128*count3 - 1);
7893 if (!result)
7894 return PyErr_NoMemory();
7895 PyObject_Init(result, &EncodingMapType);
7896 mresult = (struct encoding_map*)result;
7897 mresult->count2 = count2;
7898 mresult->count3 = count3;
7899 mlevel1 = mresult->level1;
7900 mlevel2 = mresult->level23;
7901 mlevel3 = mresult->level23 + 16*count2;
7902 memcpy(mlevel1, level1, 32);
7903 memset(mlevel2, 0xFF, 16*count2);
7904 memset(mlevel3, 0, 128*count3);
7905 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007906 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007907 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007908 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7909 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007910 /* unmapped character */
7911 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007912 o1 = ch>>11;
7913 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007914 i2 = 16*mlevel1[o1] + o2;
7915 if (mlevel2[i2] == 0xFF)
7916 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007917 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918 i3 = 128*mlevel2[i2] + o3;
7919 mlevel3[i3] = i;
7920 }
7921 return result;
7922}
7923
7924static int
Victor Stinner22168992011-11-20 17:09:18 +01007925encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007926{
7927 struct encoding_map *map = (struct encoding_map*)mapping;
7928 int l1 = c>>11;
7929 int l2 = (c>>7) & 0xF;
7930 int l3 = c & 0x7F;
7931 int i;
7932
Victor Stinner22168992011-11-20 17:09:18 +01007933 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007934 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007935 if (c == 0)
7936 return 0;
7937 /* level 1*/
7938 i = map->level1[l1];
7939 if (i == 0xFF) {
7940 return -1;
7941 }
7942 /* level 2*/
7943 i = map->level23[16*i+l2];
7944 if (i == 0xFF) {
7945 return -1;
7946 }
7947 /* level 3 */
7948 i = map->level23[16*map->count2 + 128*i + l3];
7949 if (i == 0) {
7950 return -1;
7951 }
7952 return i;
7953}
7954
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007955/* Lookup the character ch in the mapping. If the character
7956 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007957 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007958static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007959charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007960{
Christian Heimes217cfd12007-12-02 14:31:20 +00007961 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007962 PyObject *x;
7963
7964 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007965 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007966 x = PyObject_GetItem(mapping, w);
7967 Py_DECREF(w);
7968 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7970 /* No mapping found means: mapping is undefined. */
7971 PyErr_Clear();
7972 x = Py_None;
7973 Py_INCREF(x);
7974 return x;
7975 } else
7976 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007977 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007978 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007979 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007980 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 long value = PyLong_AS_LONG(x);
7982 if (value < 0 || value > 255) {
7983 PyErr_SetString(PyExc_TypeError,
7984 "character mapping must be in range(256)");
7985 Py_DECREF(x);
7986 return NULL;
7987 }
7988 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007989 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007990 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007992 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 /* wrong return value */
7994 PyErr_Format(PyExc_TypeError,
7995 "character mapping must return integer, bytes or None, not %.400s",
7996 x->ob_type->tp_name);
7997 Py_DECREF(x);
7998 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999 }
8000}
8001
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008003charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008004{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008005 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8006 /* exponentially overallocate to minimize reallocations */
8007 if (requiredsize < 2*outsize)
8008 requiredsize = 2*outsize;
8009 if (_PyBytes_Resize(outobj, requiredsize))
8010 return -1;
8011 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012}
8013
Benjamin Peterson14339b62009-01-31 16:36:08 +00008014typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008016} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008017/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008018 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008019 space is available. Return a new reference to the object that
8020 was put in the output buffer, or Py_None, if the mapping was undefined
8021 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008022 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008023static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008024charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008025 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008026{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027 PyObject *rep;
8028 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008029 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008030
Christian Heimes90aa7642007-12-19 02:45:37 +00008031 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034 if (res == -1)
8035 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 if (outsize<requiredsize)
8037 if (charmapencode_resize(outobj, outpos, requiredsize))
8038 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008039 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 outstart[(*outpos)++] = (char)res;
8041 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042 }
8043
8044 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008045 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008048 Py_DECREF(rep);
8049 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008051 if (PyLong_Check(rep)) {
8052 Py_ssize_t requiredsize = *outpos+1;
8053 if (outsize<requiredsize)
8054 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8055 Py_DECREF(rep);
8056 return enc_EXCEPTION;
8057 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008058 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008060 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 else {
8062 const char *repchars = PyBytes_AS_STRING(rep);
8063 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8064 Py_ssize_t requiredsize = *outpos+repsize;
8065 if (outsize<requiredsize)
8066 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8067 Py_DECREF(rep);
8068 return enc_EXCEPTION;
8069 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008070 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 memcpy(outstart + *outpos, repchars, repsize);
8072 *outpos += repsize;
8073 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008074 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008075 Py_DECREF(rep);
8076 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008077}
8078
8079/* handle an error in PyUnicode_EncodeCharmap
8080 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008081static int
8082charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008083 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008084 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008085 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008086 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008087{
8088 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008089 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008090 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008091 enum PyUnicode_Kind kind;
8092 void *data;
8093 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008094 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008095 Py_ssize_t collstartpos = *inpos;
8096 Py_ssize_t collendpos = *inpos+1;
8097 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008098 char *encoding = "charmap";
8099 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008101 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008102 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103
Benjamin Petersonbac79492012-01-14 13:34:47 -05008104 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008105 return -1;
8106 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107 /* find all unencodable characters */
8108 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008109 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008110 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008111 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008112 val = encoding_map_lookup(ch, mapping);
8113 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008114 break;
8115 ++collendpos;
8116 continue;
8117 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008118
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8120 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 if (rep==NULL)
8122 return -1;
8123 else if (rep!=Py_None) {
8124 Py_DECREF(rep);
8125 break;
8126 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008127 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008129 }
8130 /* cache callback name lookup
8131 * (if not done yet, i.e. it's the first error) */
8132 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008133 if ((errors==NULL) || (!strcmp(errors, "strict")))
8134 *known_errorHandler = 1;
8135 else if (!strcmp(errors, "replace"))
8136 *known_errorHandler = 2;
8137 else if (!strcmp(errors, "ignore"))
8138 *known_errorHandler = 3;
8139 else if (!strcmp(errors, "xmlcharrefreplace"))
8140 *known_errorHandler = 4;
8141 else
8142 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008143 }
8144 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008145 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008146 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 return -1;
8148 case 2: /* replace */
8149 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 x = charmapencode_output('?', mapping, res, respos);
8151 if (x==enc_EXCEPTION) {
8152 return -1;
8153 }
8154 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008155 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 return -1;
8157 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008158 }
8159 /* fall through */
8160 case 3: /* ignore */
8161 *inpos = collendpos;
8162 break;
8163 case 4: /* xmlcharrefreplace */
8164 /* generate replacement (temporarily (mis)uses p) */
8165 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 char buffer[2+29+1+1];
8167 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008168 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 for (cp = buffer; *cp; ++cp) {
8170 x = charmapencode_output(*cp, mapping, res, respos);
8171 if (x==enc_EXCEPTION)
8172 return -1;
8173 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008174 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 return -1;
8176 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 }
8178 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008179 *inpos = collendpos;
8180 break;
8181 default:
8182 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008183 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008185 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008187 if (PyBytes_Check(repunicode)) {
8188 /* Directly copy bytes result to output. */
8189 Py_ssize_t outsize = PyBytes_Size(*res);
8190 Py_ssize_t requiredsize;
8191 repsize = PyBytes_Size(repunicode);
8192 requiredsize = *respos + repsize;
8193 if (requiredsize > outsize)
8194 /* Make room for all additional bytes. */
8195 if (charmapencode_resize(res, respos, requiredsize)) {
8196 Py_DECREF(repunicode);
8197 return -1;
8198 }
8199 memcpy(PyBytes_AsString(*res) + *respos,
8200 PyBytes_AsString(repunicode), repsize);
8201 *respos += repsize;
8202 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008203 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008204 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008205 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008207 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008208 Py_DECREF(repunicode);
8209 return -1;
8210 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008211 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008212 data = PyUnicode_DATA(repunicode);
8213 kind = PyUnicode_KIND(repunicode);
8214 for (index = 0; index < repsize; index++) {
8215 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8216 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008217 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008218 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 return -1;
8220 }
8221 else if (x==enc_FAILED) {
8222 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008223 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 return -1;
8225 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008226 }
8227 *inpos = newpos;
8228 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229 }
8230 return 0;
8231}
8232
Alexander Belopolsky40018472011-02-26 01:02:56 +00008233PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008234_PyUnicode_EncodeCharmap(PyObject *unicode,
8235 PyObject *mapping,
8236 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008237{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 /* output object */
8239 PyObject *res = NULL;
8240 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008241 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008242 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008244 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008245 PyObject *errorHandler = NULL;
8246 PyObject *exc = NULL;
8247 /* the following variable is used for caching string comparisons
8248 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8249 * 3=ignore, 4=xmlcharrefreplace */
8250 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008251 void *data;
8252 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008253
Benjamin Petersonbac79492012-01-14 13:34:47 -05008254 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008255 return NULL;
8256 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008257 data = PyUnicode_DATA(unicode);
8258 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008259
Guido van Rossumd57fd912000-03-10 22:53:23 +00008260 /* Default to Latin-1 */
8261 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008262 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008264 /* allocate enough for a simple encoding without
8265 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008266 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008267 if (res == NULL)
8268 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008269 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008271
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008273 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008275 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 if (x==enc_EXCEPTION) /* error */
8277 goto onError;
8278 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 &exc,
8281 &known_errorHandler, &errorHandler, errors,
8282 &res, &respos)) {
8283 goto onError;
8284 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008285 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 else
8287 /* done with this character => adjust input position */
8288 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008289 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008292 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008293 if (_PyBytes_Resize(&res, respos) < 0)
8294 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008295
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296 Py_XDECREF(exc);
8297 Py_XDECREF(errorHandler);
8298 return res;
8299
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008301 Py_XDECREF(res);
8302 Py_XDECREF(exc);
8303 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304 return NULL;
8305}
8306
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008307/* Deprecated */
8308PyObject *
8309PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8310 Py_ssize_t size,
8311 PyObject *mapping,
8312 const char *errors)
8313{
8314 PyObject *result;
8315 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8316 if (unicode == NULL)
8317 return NULL;
8318 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8319 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008320 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321}
8322
Alexander Belopolsky40018472011-02-26 01:02:56 +00008323PyObject *
8324PyUnicode_AsCharmapString(PyObject *unicode,
8325 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008326{
8327 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 PyErr_BadArgument();
8329 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008331 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008332}
8333
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008335static void
8336make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008337 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008338 Py_ssize_t startpos, Py_ssize_t endpos,
8339 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008341 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342 *exceptionObject = _PyUnicodeTranslateError_Create(
8343 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344 }
8345 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8347 goto onError;
8348 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8349 goto onError;
8350 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8351 goto onError;
8352 return;
8353 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008354 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008355 }
8356}
8357
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358/* error handling callback helper:
8359 build arguments, call the callback and check the arguments,
8360 put the result into newpos and return the replacement string, which
8361 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008362static PyObject *
8363unicode_translate_call_errorhandler(const char *errors,
8364 PyObject **errorHandler,
8365 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008366 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008367 Py_ssize_t startpos, Py_ssize_t endpos,
8368 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008370 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008372 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 PyObject *restuple;
8374 PyObject *resunicode;
8375
8376 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 }
8381
8382 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386
8387 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008392 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 Py_DECREF(restuple);
8394 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008395 }
8396 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 &resunicode, &i_newpos)) {
8398 Py_DECREF(restuple);
8399 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008401 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008402 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008403 else
8404 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008405 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008406 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 Py_DECREF(restuple);
8408 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008409 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 Py_INCREF(resunicode);
8411 Py_DECREF(restuple);
8412 return resunicode;
8413}
8414
8415/* Lookup the character ch in the mapping and put the result in result,
8416 which must be decrefed by the caller.
8417 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008418static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420{
Christian Heimes217cfd12007-12-02 14:31:20 +00008421 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 PyObject *x;
8423
8424 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426 x = PyObject_GetItem(mapping, w);
8427 Py_DECREF(w);
8428 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8430 /* No mapping found means: use 1:1 mapping. */
8431 PyErr_Clear();
8432 *result = NULL;
8433 return 0;
8434 } else
8435 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 }
8437 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 *result = x;
8439 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008441 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008443 if (value < 0 || value > MAX_UNICODE) {
8444 PyErr_Format(PyExc_ValueError,
8445 "character mapping must be in range(0x%x)",
8446 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 Py_DECREF(x);
8448 return -1;
8449 }
8450 *result = x;
8451 return 0;
8452 }
8453 else if (PyUnicode_Check(x)) {
8454 *result = x;
8455 return 0;
8456 }
8457 else {
8458 /* wrong return value */
8459 PyErr_SetString(PyExc_TypeError,
8460 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008461 Py_DECREF(x);
8462 return -1;
8463 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008464}
Victor Stinner1194ea02014-04-04 19:37:40 +02008465
8466/* lookup the character, write the result into the writer.
8467 Return 1 if the result was written into the writer, return 0 if the mapping
8468 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008469static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008470charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8471 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472{
Victor Stinner1194ea02014-04-04 19:37:40 +02008473 PyObject *item;
8474
8475 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008477
8478 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008480 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008481 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008483 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008485
8486 if (item == Py_None) {
8487 Py_DECREF(item);
8488 return 0;
8489 }
8490
8491 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008492 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8493 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8494 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008495 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8496 Py_DECREF(item);
8497 return -1;
8498 }
8499 Py_DECREF(item);
8500 return 1;
8501 }
8502
8503 if (!PyUnicode_Check(item)) {
8504 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008506 }
8507
8508 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8509 Py_DECREF(item);
8510 return -1;
8511 }
8512
8513 Py_DECREF(item);
8514 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515}
8516
Victor Stinner89a76ab2014-04-05 11:44:04 +02008517static int
8518unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8519 Py_UCS1 *translate)
8520{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008521 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008522 int ret = 0;
8523
Victor Stinner89a76ab2014-04-05 11:44:04 +02008524 if (charmaptranslate_lookup(ch, mapping, &item)) {
8525 return -1;
8526 }
8527
8528 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008529 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008530 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008531 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008532 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008533 /* not found => default to 1:1 mapping */
8534 translate[ch] = ch;
8535 return 1;
8536 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008537 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008538 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008539 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8540 used it */
8541 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008542 /* invalid character or character outside ASCII:
8543 skip the fast translate */
8544 goto exit;
8545 }
8546 translate[ch] = (Py_UCS1)replace;
8547 }
8548 else if (PyUnicode_Check(item)) {
8549 Py_UCS4 replace;
8550
8551 if (PyUnicode_READY(item) == -1) {
8552 Py_DECREF(item);
8553 return -1;
8554 }
8555 if (PyUnicode_GET_LENGTH(item) != 1)
8556 goto exit;
8557
8558 replace = PyUnicode_READ_CHAR(item, 0);
8559 if (replace > 127)
8560 goto exit;
8561 translate[ch] = (Py_UCS1)replace;
8562 }
8563 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008564 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008565 goto exit;
8566 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008567 ret = 1;
8568
Benjamin Peterson1365de72014-04-07 20:15:41 -04008569 exit:
8570 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008571 return ret;
8572}
8573
8574/* Fast path for ascii => ascii translation. Return 1 if the whole string
8575 was translated into writer, return 0 if the input string was partially
8576 translated into writer, raise an exception and return -1 on error. */
8577static int
8578unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008579 _PyUnicodeWriter *writer, int ignore,
8580 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008581{
Victor Stinner872b2912014-04-05 14:27:07 +02008582 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008583 Py_ssize_t len;
8584 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008585 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008586
Victor Stinner89a76ab2014-04-05 11:44:04 +02008587 len = PyUnicode_GET_LENGTH(input);
8588
Victor Stinner872b2912014-04-05 14:27:07 +02008589 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008590
8591 in = PyUnicode_1BYTE_DATA(input);
8592 end = in + len;
8593
8594 assert(PyUnicode_IS_ASCII(writer->buffer));
8595 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8596 out = PyUnicode_1BYTE_DATA(writer->buffer);
8597
Victor Stinner872b2912014-04-05 14:27:07 +02008598 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008599 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008600 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008601 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008602 int translate = unicode_fast_translate_lookup(mapping, ch,
8603 ascii_table);
8604 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008605 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008606 if (translate == 0)
8607 goto exit;
8608 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008609 }
Victor Stinner872b2912014-04-05 14:27:07 +02008610 if (ch2 == 0xfe) {
8611 if (ignore)
8612 continue;
8613 goto exit;
8614 }
8615 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008616 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008617 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008618 }
Victor Stinner872b2912014-04-05 14:27:07 +02008619 res = 1;
8620
8621exit:
8622 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008623 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008624 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008625}
8626
Alexander Belopolsky40018472011-02-26 01:02:56 +00008627PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628_PyUnicode_TranslateCharmap(PyObject *input,
8629 PyObject *mapping,
8630 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008633 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 Py_ssize_t size, i;
8635 int kind;
8636 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008637 _PyUnicodeWriter writer;
8638 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 char *reason = "character maps to <undefined>";
8640 PyObject *errorHandler = NULL;
8641 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008642 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008643 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644
Guido van Rossumd57fd912000-03-10 22:53:23 +00008645 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 PyErr_BadArgument();
8647 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008650 if (PyUnicode_READY(input) == -1)
8651 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008652 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653 kind = PyUnicode_KIND(input);
8654 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655
8656 if (size == 0) {
8657 Py_INCREF(input);
8658 return input;
8659 }
8660
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 /* allocate enough for a simple 1:1 translation without
8662 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008663 _PyUnicodeWriter_Init(&writer);
8664 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008666
Victor Stinner872b2912014-04-05 14:27:07 +02008667 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8668
Victor Stinner33798672016-03-01 21:59:58 +01008669 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008670 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008671 if (PyUnicode_IS_ASCII(input)) {
8672 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8673 if (res < 0) {
8674 _PyUnicodeWriter_Dealloc(&writer);
8675 return NULL;
8676 }
8677 if (res == 1)
8678 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008679 }
Victor Stinner33798672016-03-01 21:59:58 +01008680 else {
8681 i = 0;
8682 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008683
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008686 int translate;
8687 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8688 Py_ssize_t newpos;
8689 /* startpos for collecting untranslatable chars */
8690 Py_ssize_t collstart;
8691 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008692 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008693
Victor Stinner1194ea02014-04-04 19:37:40 +02008694 ch = PyUnicode_READ(kind, data, i);
8695 translate = charmaptranslate_output(ch, mapping, &writer);
8696 if (translate < 0)
8697 goto onError;
8698
8699 if (translate != 0) {
8700 /* it worked => adjust input pointer */
8701 ++i;
8702 continue;
8703 }
8704
8705 /* untranslatable character */
8706 collstart = i;
8707 collend = i+1;
8708
8709 /* find all untranslatable characters */
8710 while (collend < size) {
8711 PyObject *x;
8712 ch = PyUnicode_READ(kind, data, collend);
8713 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008714 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008715 Py_XDECREF(x);
8716 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008718 ++collend;
8719 }
8720
8721 if (ignore) {
8722 i = collend;
8723 }
8724 else {
8725 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8726 reason, input, &exc,
8727 collstart, collend, &newpos);
8728 if (repunicode == NULL)
8729 goto onError;
8730 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008731 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008732 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008733 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008734 Py_DECREF(repunicode);
8735 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008736 }
8737 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 Py_XDECREF(exc);
8739 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008740 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008743 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744 Py_XDECREF(exc);
8745 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 return NULL;
8747}
8748
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749/* Deprecated. Use PyUnicode_Translate instead. */
8750PyObject *
8751PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8752 Py_ssize_t size,
8753 PyObject *mapping,
8754 const char *errors)
8755{
Christian Heimes5f520f42012-09-11 14:03:25 +02008756 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008757 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8758 if (!unicode)
8759 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008760 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8761 Py_DECREF(unicode);
8762 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763}
8764
Alexander Belopolsky40018472011-02-26 01:02:56 +00008765PyObject *
8766PyUnicode_Translate(PyObject *str,
8767 PyObject *mapping,
8768 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008769{
8770 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008771
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772 str = PyUnicode_FromObject(str);
8773 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008774 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008776 Py_DECREF(str);
8777 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008778}
Tim Petersced69f82003-09-16 20:30:58 +00008779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008781fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782{
8783 /* No need to call PyUnicode_READY(self) because this function is only
8784 called as a callback from fixup() which does it already. */
8785 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8786 const int kind = PyUnicode_KIND(self);
8787 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008788 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008789 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 Py_ssize_t i;
8791
8792 for (i = 0; i < len; ++i) {
8793 ch = PyUnicode_READ(kind, data, i);
8794 fixed = 0;
8795 if (ch > 127) {
8796 if (Py_UNICODE_ISSPACE(ch))
8797 fixed = ' ';
8798 else {
8799 const int decimal = Py_UNICODE_TODECIMAL(ch);
8800 if (decimal >= 0)
8801 fixed = '0' + decimal;
8802 }
8803 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008804 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008805 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806 PyUnicode_WRITE(kind, data, i, fixed);
8807 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008808 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008809 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008811 }
8812
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008813 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814}
8815
8816PyObject *
8817_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8818{
8819 if (!PyUnicode_Check(unicode)) {
8820 PyErr_BadInternalCall();
8821 return NULL;
8822 }
8823 if (PyUnicode_READY(unicode) == -1)
8824 return NULL;
8825 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8826 /* If the string is already ASCII, just return the same string */
8827 Py_INCREF(unicode);
8828 return unicode;
8829 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008830 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831}
8832
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008833PyObject *
8834PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8835 Py_ssize_t length)
8836{
Victor Stinnerf0124502011-11-21 23:12:56 +01008837 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008838 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008839 Py_UCS4 maxchar;
8840 enum PyUnicode_Kind kind;
8841 void *data;
8842
Victor Stinner99d7ad02012-02-22 13:37:39 +01008843 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008844 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008845 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008846 if (ch > 127) {
8847 int decimal = Py_UNICODE_TODECIMAL(ch);
8848 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008849 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008850 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008851 }
8852 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008853
8854 /* Copy to a new string */
8855 decimal = PyUnicode_New(length, maxchar);
8856 if (decimal == NULL)
8857 return decimal;
8858 kind = PyUnicode_KIND(decimal);
8859 data = PyUnicode_DATA(decimal);
8860 /* Iterate over code points */
8861 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008862 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008863 if (ch > 127) {
8864 int decimal = Py_UNICODE_TODECIMAL(ch);
8865 if (decimal >= 0)
8866 ch = '0' + decimal;
8867 }
8868 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008870 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008871}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008872/* --- Decimal Encoder ---------------------------------------------------- */
8873
Alexander Belopolsky40018472011-02-26 01:02:56 +00008874int
8875PyUnicode_EncodeDecimal(Py_UNICODE *s,
8876 Py_ssize_t length,
8877 char *output,
8878 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008879{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008880 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008881 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008882 enum PyUnicode_Kind kind;
8883 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008884
8885 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008886 PyErr_BadArgument();
8887 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008888 }
8889
Victor Stinner42bf7752011-11-21 22:52:58 +01008890 unicode = PyUnicode_FromUnicode(s, length);
8891 if (unicode == NULL)
8892 return -1;
8893
Benjamin Petersonbac79492012-01-14 13:34:47 -05008894 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008895 Py_DECREF(unicode);
8896 return -1;
8897 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008898 kind = PyUnicode_KIND(unicode);
8899 data = PyUnicode_DATA(unicode);
8900
Victor Stinnerb84d7232011-11-22 01:50:07 +01008901 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008902 PyObject *exc;
8903 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008904 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008905 Py_ssize_t startpos;
8906
8907 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008908
Benjamin Peterson29060642009-01-31 22:14:21 +00008909 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008910 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008911 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008912 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008913 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008914 decimal = Py_UNICODE_TODECIMAL(ch);
8915 if (decimal >= 0) {
8916 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008917 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 continue;
8919 }
8920 if (0 < ch && ch < 256) {
8921 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008922 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 continue;
8924 }
Victor Stinner6345be92011-11-25 20:09:01 +01008925
Victor Stinner42bf7752011-11-21 22:52:58 +01008926 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008927 exc = NULL;
8928 raise_encode_exception(&exc, "decimal", unicode,
8929 startpos, startpos+1,
8930 "invalid decimal Unicode string");
8931 Py_XDECREF(exc);
8932 Py_DECREF(unicode);
8933 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008934 }
8935 /* 0-terminate the output string */
8936 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008937 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008938 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008939}
8940
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941/* --- Helpers ------------------------------------------------------------ */
8942
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008943/* helper macro to fixup start/end slice values */
8944#define ADJUST_INDICES(start, end, len) \
8945 if (end > len) \
8946 end = len; \
8947 else if (end < 0) { \
8948 end += len; \
8949 if (end < 0) \
8950 end = 0; \
8951 } \
8952 if (start < 0) { \
8953 start += len; \
8954 if (start < 0) \
8955 start = 0; \
8956 }
8957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008959any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960 Py_ssize_t start,
8961 Py_ssize_t end)
8962{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008963 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 void *buf1, *buf2;
8965 Py_ssize_t len1, len2, result;
8966
8967 kind1 = PyUnicode_KIND(s1);
8968 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008969 if (kind1 < kind2)
8970 return -1;
8971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 len1 = PyUnicode_GET_LENGTH(s1);
8973 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008974 ADJUST_INDICES(start, end, len1);
8975 if (end - start < len2)
8976 return -1;
8977
8978 buf1 = PyUnicode_DATA(s1);
8979 buf2 = PyUnicode_DATA(s2);
8980 if (len2 == 1) {
8981 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
8982 result = findchar((const char *)buf1 + kind1*start,
8983 kind1, end - start, ch, direction);
8984 if (result == -1)
8985 return -1;
8986 else
8987 return start + result;
8988 }
8989
8990 if (kind2 != kind1) {
8991 buf2 = _PyUnicode_AsKind(s2, kind1);
8992 if (!buf2)
8993 return -2;
8994 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008995
Victor Stinner794d5672011-10-10 03:21:36 +02008996 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008997 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02008998 case PyUnicode_1BYTE_KIND:
8999 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9000 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9001 else
9002 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9003 break;
9004 case PyUnicode_2BYTE_KIND:
9005 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9006 break;
9007 case PyUnicode_4BYTE_KIND:
9008 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9009 break;
9010 default:
9011 assert(0); result = -2;
9012 }
9013 }
9014 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009015 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009016 case PyUnicode_1BYTE_KIND:
9017 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9018 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9019 else
9020 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9021 break;
9022 case PyUnicode_2BYTE_KIND:
9023 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9024 break;
9025 case PyUnicode_4BYTE_KIND:
9026 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9027 break;
9028 default:
9029 assert(0); result = -2;
9030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031 }
9032
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009033 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009034 PyMem_Free(buf2);
9035
9036 return result;
9037}
9038
9039Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009040_PyUnicode_InsertThousandsGrouping(
9041 PyObject *unicode, Py_ssize_t index,
9042 Py_ssize_t n_buffer,
9043 void *digits, Py_ssize_t n_digits,
9044 Py_ssize_t min_width,
9045 const char *grouping, PyObject *thousands_sep,
9046 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047{
Victor Stinner41a863c2012-02-24 00:37:51 +01009048 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009049 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009050 Py_ssize_t thousands_sep_len;
9051 Py_ssize_t len;
9052
9053 if (unicode != NULL) {
9054 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009055 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009056 }
9057 else {
9058 kind = PyUnicode_1BYTE_KIND;
9059 data = NULL;
9060 }
9061 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9062 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9063 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9064 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009065 if (thousands_sep_kind < kind) {
9066 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9067 if (!thousands_sep_data)
9068 return -1;
9069 }
9070 else {
9071 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9072 if (!data)
9073 return -1;
9074 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009075 }
9076
Benjamin Petersonead6b532011-12-20 17:23:42 -06009077 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009079 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009080 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009081 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009082 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009083 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009084 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009085 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009086 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009087 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009088 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009089 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009091 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009092 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009094 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009095 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009097 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009098 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009100 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 break;
9102 default:
9103 assert(0);
9104 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009105 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009106 if (unicode != NULL && thousands_sep_kind != kind) {
9107 if (thousands_sep_kind < kind)
9108 PyMem_Free(thousands_sep_data);
9109 else
9110 PyMem_Free(data);
9111 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009112 if (unicode == NULL) {
9113 *maxchar = 127;
9114 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009115 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009116 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009117 }
9118 }
9119 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120}
9121
9122
Alexander Belopolsky40018472011-02-26 01:02:56 +00009123Py_ssize_t
9124PyUnicode_Count(PyObject *str,
9125 PyObject *substr,
9126 Py_ssize_t start,
9127 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009128{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009129 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009130 PyObject* str_obj;
9131 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009132 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 void *buf1 = NULL, *buf2 = NULL;
9134 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009135
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009136 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009137 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009138 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009139 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009140 if (!sub_obj) {
9141 Py_DECREF(str_obj);
9142 return -1;
9143 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009144 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009145 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009146 Py_DECREF(str_obj);
9147 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009148 }
Tim Petersced69f82003-09-16 20:30:58 +00009149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009150 kind1 = PyUnicode_KIND(str_obj);
9151 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009152 if (kind1 < kind2) {
9153 Py_DECREF(sub_obj);
9154 Py_DECREF(str_obj);
9155 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009156 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009158 len1 = PyUnicode_GET_LENGTH(str_obj);
9159 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009160 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009161 if (end - start < len2) {
9162 Py_DECREF(sub_obj);
9163 Py_DECREF(str_obj);
9164 return 0;
9165 }
9166
9167 buf1 = PyUnicode_DATA(str_obj);
9168 buf2 = PyUnicode_DATA(sub_obj);
9169 if (kind2 != kind1) {
9170 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9171 if (!buf2)
9172 goto onError;
9173 }
9174
9175 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009176 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009177 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9178 result = asciilib_count(
9179 ((Py_UCS1*)buf1) + start, end - start,
9180 buf2, len2, PY_SSIZE_T_MAX
9181 );
9182 else
9183 result = ucs1lib_count(
9184 ((Py_UCS1*)buf1) + start, end - start,
9185 buf2, len2, PY_SSIZE_T_MAX
9186 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187 break;
9188 case PyUnicode_2BYTE_KIND:
9189 result = ucs2lib_count(
9190 ((Py_UCS2*)buf1) + start, end - start,
9191 buf2, len2, PY_SSIZE_T_MAX
9192 );
9193 break;
9194 case PyUnicode_4BYTE_KIND:
9195 result = ucs4lib_count(
9196 ((Py_UCS4*)buf1) + start, end - start,
9197 buf2, len2, PY_SSIZE_T_MAX
9198 );
9199 break;
9200 default:
9201 assert(0); result = 0;
9202 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009203
9204 Py_DECREF(sub_obj);
9205 Py_DECREF(str_obj);
9206
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009207 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 PyMem_Free(buf2);
9209
Guido van Rossumd57fd912000-03-10 22:53:23 +00009210 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 onError:
9212 Py_DECREF(sub_obj);
9213 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009214 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 PyMem_Free(buf2);
9216 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009217}
9218
Alexander Belopolsky40018472011-02-26 01:02:56 +00009219Py_ssize_t
9220PyUnicode_Find(PyObject *str,
9221 PyObject *sub,
9222 Py_ssize_t start,
9223 Py_ssize_t end,
9224 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009225{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009226 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009227
Guido van Rossumd57fd912000-03-10 22:53:23 +00009228 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009229 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009230 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009231 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009232 if (!sub) {
9233 Py_DECREF(str);
9234 return -2;
9235 }
9236 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9237 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009238 Py_DECREF(str);
9239 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240 }
Tim Petersced69f82003-09-16 20:30:58 +00009241
Victor Stinner794d5672011-10-10 03:21:36 +02009242 result = any_find_slice(direction,
9243 str, sub, start, end
9244 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009245
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009247 Py_DECREF(sub);
9248
Guido van Rossumd57fd912000-03-10 22:53:23 +00009249 return result;
9250}
9251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252Py_ssize_t
9253PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9254 Py_ssize_t start, Py_ssize_t end,
9255 int direction)
9256{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009257 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009258 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (PyUnicode_READY(str) == -1)
9260 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009261 if (start < 0 || end < 0) {
9262 PyErr_SetString(PyExc_IndexError, "string index out of range");
9263 return -2;
9264 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 if (end > PyUnicode_GET_LENGTH(str))
9266 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009267 if (start >= end)
9268 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009270 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9271 kind, end-start, ch, direction);
9272 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009274 else
9275 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276}
9277
Alexander Belopolsky40018472011-02-26 01:02:56 +00009278static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009279tailmatch(PyObject *self,
9280 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009281 Py_ssize_t start,
9282 Py_ssize_t end,
9283 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 int kind_self;
9286 int kind_sub;
9287 void *data_self;
9288 void *data_sub;
9289 Py_ssize_t offset;
9290 Py_ssize_t i;
9291 Py_ssize_t end_sub;
9292
9293 if (PyUnicode_READY(self) == -1 ||
9294 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009295 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9298 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009300 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009302 if (PyUnicode_GET_LENGTH(substring) == 0)
9303 return 1;
9304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 kind_self = PyUnicode_KIND(self);
9306 data_self = PyUnicode_DATA(self);
9307 kind_sub = PyUnicode_KIND(substring);
9308 data_sub = PyUnicode_DATA(substring);
9309 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9310
9311 if (direction > 0)
9312 offset = end;
9313 else
9314 offset = start;
9315
9316 if (PyUnicode_READ(kind_self, data_self, offset) ==
9317 PyUnicode_READ(kind_sub, data_sub, 0) &&
9318 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9319 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9320 /* If both are of the same kind, memcmp is sufficient */
9321 if (kind_self == kind_sub) {
9322 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009323 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 data_sub,
9325 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009326 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009328 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009329 else {
9330 /* We do not need to compare 0 and len(substring)-1 because
9331 the if statement above ensured already that they are equal
9332 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 for (i = 1; i < end_sub; ++i) {
9334 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9335 PyUnicode_READ(kind_sub, data_sub, i))
9336 return 0;
9337 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009338 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009339 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009340 }
9341
9342 return 0;
9343}
9344
Alexander Belopolsky40018472011-02-26 01:02:56 +00009345Py_ssize_t
9346PyUnicode_Tailmatch(PyObject *str,
9347 PyObject *substr,
9348 Py_ssize_t start,
9349 Py_ssize_t end,
9350 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009352 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009353
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354 str = PyUnicode_FromObject(str);
9355 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009356 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357 substr = PyUnicode_FromObject(substr);
9358 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009359 Py_DECREF(str);
9360 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361 }
Tim Petersced69f82003-09-16 20:30:58 +00009362
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009363 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009364 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009365 Py_DECREF(str);
9366 Py_DECREF(substr);
9367 return result;
9368}
9369
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370/* Apply fixfct filter to the Unicode object self and return a
9371 reference to the modified object */
9372
Alexander Belopolsky40018472011-02-26 01:02:56 +00009373static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009374fixup(PyObject *self,
9375 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 PyObject *u;
9378 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009379 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009381 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009384 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009385
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 /* fix functions return the new maximum character in a string,
9387 if the kind of the resulting unicode object does not change,
9388 everything is fine. Otherwise we need to change the string kind
9389 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009390 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009391
9392 if (maxchar_new == 0) {
9393 /* no changes */;
9394 if (PyUnicode_CheckExact(self)) {
9395 Py_DECREF(u);
9396 Py_INCREF(self);
9397 return self;
9398 }
9399 else
9400 return u;
9401 }
9402
Victor Stinnere6abb482012-05-02 01:15:40 +02009403 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404
Victor Stinnereaab6042011-12-11 22:22:39 +01009405 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009407
9408 /* In case the maximum character changed, we need to
9409 convert the string to the new category. */
9410 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9411 if (v == NULL) {
9412 Py_DECREF(u);
9413 return NULL;
9414 }
9415 if (maxchar_new > maxchar_old) {
9416 /* If the maxchar increased so that the kind changed, not all
9417 characters are representable anymore and we need to fix the
9418 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009419 _PyUnicode_FastCopyCharacters(v, 0,
9420 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009421 maxchar_old = fixfct(v);
9422 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 }
9424 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009425 _PyUnicode_FastCopyCharacters(v, 0,
9426 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009428 Py_DECREF(u);
9429 assert(_PyUnicode_CheckConsistency(v, 1));
9430 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431}
9432
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009433static PyObject *
9434ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009435{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009436 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9437 char *resdata, *data = PyUnicode_DATA(self);
9438 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009439
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009440 res = PyUnicode_New(len, 127);
9441 if (res == NULL)
9442 return NULL;
9443 resdata = PyUnicode_DATA(res);
9444 if (lower)
9445 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009447 _Py_bytes_upper(resdata, data, len);
9448 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009449}
9450
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009452handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009454 Py_ssize_t j;
9455 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009456 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009457 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009458
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009459 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9460
9461 where ! is a negation and \p{xxx} is a character with property xxx.
9462 */
9463 for (j = i - 1; j >= 0; j--) {
9464 c = PyUnicode_READ(kind, data, j);
9465 if (!_PyUnicode_IsCaseIgnorable(c))
9466 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009468 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9469 if (final_sigma) {
9470 for (j = i + 1; j < length; j++) {
9471 c = PyUnicode_READ(kind, data, j);
9472 if (!_PyUnicode_IsCaseIgnorable(c))
9473 break;
9474 }
9475 final_sigma = j == length || !_PyUnicode_IsCased(c);
9476 }
9477 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478}
9479
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009480static int
9481lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9482 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009484 /* Obscure special case. */
9485 if (c == 0x3A3) {
9486 mapped[0] = handle_capital_sigma(kind, data, length, i);
9487 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009489 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490}
9491
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009492static Py_ssize_t
9493do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009495 Py_ssize_t i, k = 0;
9496 int n_res, j;
9497 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009498
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009499 c = PyUnicode_READ(kind, data, 0);
9500 n_res = _PyUnicode_ToUpperFull(c, mapped);
9501 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009502 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009503 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009505 for (i = 1; i < length; i++) {
9506 c = PyUnicode_READ(kind, data, i);
9507 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9508 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009509 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009510 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009511 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009512 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009513 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514}
9515
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009516static Py_ssize_t
9517do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9518 Py_ssize_t i, k = 0;
9519
9520 for (i = 0; i < length; i++) {
9521 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9522 int n_res, j;
9523 if (Py_UNICODE_ISUPPER(c)) {
9524 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9525 }
9526 else if (Py_UNICODE_ISLOWER(c)) {
9527 n_res = _PyUnicode_ToUpperFull(c, mapped);
9528 }
9529 else {
9530 n_res = 1;
9531 mapped[0] = c;
9532 }
9533 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009534 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009535 res[k++] = mapped[j];
9536 }
9537 }
9538 return k;
9539}
9540
9541static Py_ssize_t
9542do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9543 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009545 Py_ssize_t i, k = 0;
9546
9547 for (i = 0; i < length; i++) {
9548 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9549 int n_res, j;
9550 if (lower)
9551 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9552 else
9553 n_res = _PyUnicode_ToUpperFull(c, mapped);
9554 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009555 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009556 res[k++] = mapped[j];
9557 }
9558 }
9559 return k;
9560}
9561
9562static Py_ssize_t
9563do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9564{
9565 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9566}
9567
9568static Py_ssize_t
9569do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9570{
9571 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9572}
9573
Benjamin Petersone51757f2012-01-12 21:10:29 -05009574static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009575do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9576{
9577 Py_ssize_t i, k = 0;
9578
9579 for (i = 0; i < length; i++) {
9580 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9581 Py_UCS4 mapped[3];
9582 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9583 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009584 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009585 res[k++] = mapped[j];
9586 }
9587 }
9588 return k;
9589}
9590
9591static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009592do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9593{
9594 Py_ssize_t i, k = 0;
9595 int previous_is_cased;
9596
9597 previous_is_cased = 0;
9598 for (i = 0; i < length; i++) {
9599 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9600 Py_UCS4 mapped[3];
9601 int n_res, j;
9602
9603 if (previous_is_cased)
9604 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9605 else
9606 n_res = _PyUnicode_ToTitleFull(c, mapped);
9607
9608 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009609 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009610 res[k++] = mapped[j];
9611 }
9612
9613 previous_is_cased = _PyUnicode_IsCased(c);
9614 }
9615 return k;
9616}
9617
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009618static PyObject *
9619case_operation(PyObject *self,
9620 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9621{
9622 PyObject *res = NULL;
9623 Py_ssize_t length, newlength = 0;
9624 int kind, outkind;
9625 void *data, *outdata;
9626 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9627
Benjamin Petersoneea48462012-01-16 14:28:50 -05009628 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009629
9630 kind = PyUnicode_KIND(self);
9631 data = PyUnicode_DATA(self);
9632 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009633 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009634 PyErr_SetString(PyExc_OverflowError, "string is too long");
9635 return NULL;
9636 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009637 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638 if (tmp == NULL)
9639 return PyErr_NoMemory();
9640 newlength = perform(kind, data, length, tmp, &maxchar);
9641 res = PyUnicode_New(newlength, maxchar);
9642 if (res == NULL)
9643 goto leave;
9644 tmpend = tmp + newlength;
9645 outdata = PyUnicode_DATA(res);
9646 outkind = PyUnicode_KIND(res);
9647 switch (outkind) {
9648 case PyUnicode_1BYTE_KIND:
9649 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9650 break;
9651 case PyUnicode_2BYTE_KIND:
9652 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9653 break;
9654 case PyUnicode_4BYTE_KIND:
9655 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9656 break;
9657 default:
9658 assert(0);
9659 break;
9660 }
9661 leave:
9662 PyMem_FREE(tmp);
9663 return res;
9664}
9665
Tim Peters8ce9f162004-08-27 01:49:32 +00009666PyObject *
9667PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009669 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009670 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009671 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009672 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009673 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9674 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009675 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009676 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009677 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009679 int use_memcpy;
9680 unsigned char *res_data = NULL, *sep_data = NULL;
9681 PyObject *last_obj;
9682 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009683
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009684 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009685 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009686 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009687 }
9688
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009689 /* NOTE: the following code can't call back into Python code,
9690 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009691 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009692
Tim Peters05eba1f2004-08-27 21:32:02 +00009693 seqlen = PySequence_Fast_GET_SIZE(fseq);
9694 /* If empty sequence, return u"". */
9695 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009696 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009697 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009698 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009699
Tim Peters05eba1f2004-08-27 21:32:02 +00009700 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009701 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009702 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009703 if (seqlen == 1) {
9704 if (PyUnicode_CheckExact(items[0])) {
9705 res = items[0];
9706 Py_INCREF(res);
9707 Py_DECREF(fseq);
9708 return res;
9709 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009710 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009711 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009712 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009713 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009714 /* Set up sep and seplen */
9715 if (separator == NULL) {
9716 /* fall back to a blank space separator */
9717 sep = PyUnicode_FromOrdinal(' ');
9718 if (!sep)
9719 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009720 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009721 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009722 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009723 else {
9724 if (!PyUnicode_Check(separator)) {
9725 PyErr_Format(PyExc_TypeError,
9726 "separator: expected str instance,"
9727 " %.80s found",
9728 Py_TYPE(separator)->tp_name);
9729 goto onError;
9730 }
9731 if (PyUnicode_READY(separator))
9732 goto onError;
9733 sep = separator;
9734 seplen = PyUnicode_GET_LENGTH(separator);
9735 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9736 /* inc refcount to keep this code path symmetric with the
9737 above case of a blank separator */
9738 Py_INCREF(sep);
9739 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009741 }
9742
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009743 /* There are at least two things to join, or else we have a subclass
9744 * of str in the sequence.
9745 * Do a pre-pass to figure out the total amount of space we'll
9746 * need (sz), and see whether all argument are strings.
9747 */
9748 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009749#ifdef Py_DEBUG
9750 use_memcpy = 0;
9751#else
9752 use_memcpy = 1;
9753#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009754 for (i = 0; i < seqlen; i++) {
9755 const Py_ssize_t old_sz = sz;
9756 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009757 if (!PyUnicode_Check(item)) {
9758 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009759 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009760 " %.80s found",
9761 i, Py_TYPE(item)->tp_name);
9762 goto onError;
9763 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009764 if (PyUnicode_READY(item) == -1)
9765 goto onError;
9766 sz += PyUnicode_GET_LENGTH(item);
9767 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009768 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009769 if (i != 0)
9770 sz += seplen;
9771 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9772 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009773 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009774 goto onError;
9775 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009776 if (use_memcpy && last_obj != NULL) {
9777 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9778 use_memcpy = 0;
9779 }
9780 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009781 }
Tim Petersced69f82003-09-16 20:30:58 +00009782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009783 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009784 if (res == NULL)
9785 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009786
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009787 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009788#ifdef Py_DEBUG
9789 use_memcpy = 0;
9790#else
9791 if (use_memcpy) {
9792 res_data = PyUnicode_1BYTE_DATA(res);
9793 kind = PyUnicode_KIND(res);
9794 if (seplen != 0)
9795 sep_data = PyUnicode_1BYTE_DATA(sep);
9796 }
9797#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009798 if (use_memcpy) {
9799 for (i = 0; i < seqlen; ++i) {
9800 Py_ssize_t itemlen;
9801 item = items[i];
9802
9803 /* Copy item, and maybe the separator. */
9804 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009805 Py_MEMCPY(res_data,
9806 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009807 kind * seplen);
9808 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009809 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009810
9811 itemlen = PyUnicode_GET_LENGTH(item);
9812 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009813 Py_MEMCPY(res_data,
9814 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009815 kind * itemlen);
9816 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009817 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009818 }
9819 assert(res_data == PyUnicode_1BYTE_DATA(res)
9820 + kind * PyUnicode_GET_LENGTH(res));
9821 }
9822 else {
9823 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9824 Py_ssize_t itemlen;
9825 item = items[i];
9826
9827 /* Copy item, and maybe the separator. */
9828 if (i && seplen != 0) {
9829 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9830 res_offset += seplen;
9831 }
9832
9833 itemlen = PyUnicode_GET_LENGTH(item);
9834 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009835 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009836 res_offset += itemlen;
9837 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009838 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009839 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009840 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009841
Tim Peters05eba1f2004-08-27 21:32:02 +00009842 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009844 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846
Benjamin Peterson29060642009-01-31 22:14:21 +00009847 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009848 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009850 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851 return NULL;
9852}
9853
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854#define FILL(kind, data, value, start, length) \
9855 do { \
9856 Py_ssize_t i_ = 0; \
9857 assert(kind != PyUnicode_WCHAR_KIND); \
9858 switch ((kind)) { \
9859 case PyUnicode_1BYTE_KIND: { \
9860 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009861 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 break; \
9863 } \
9864 case PyUnicode_2BYTE_KIND: { \
9865 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9866 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9867 break; \
9868 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009869 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9871 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9872 break; \
9873 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009874 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 } \
9876 } while (0)
9877
Victor Stinnerd3f08822012-05-29 12:57:52 +02009878void
9879_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9880 Py_UCS4 fill_char)
9881{
9882 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9883 const void *data = PyUnicode_DATA(unicode);
9884 assert(PyUnicode_IS_READY(unicode));
9885 assert(unicode_modifiable(unicode));
9886 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9887 assert(start >= 0);
9888 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9889 FILL(kind, data, fill_char, start, length);
9890}
9891
Victor Stinner3fe55312012-01-04 00:33:50 +01009892Py_ssize_t
9893PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9894 Py_UCS4 fill_char)
9895{
9896 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009897
9898 if (!PyUnicode_Check(unicode)) {
9899 PyErr_BadInternalCall();
9900 return -1;
9901 }
9902 if (PyUnicode_READY(unicode) == -1)
9903 return -1;
9904 if (unicode_check_modifiable(unicode))
9905 return -1;
9906
Victor Stinnerd3f08822012-05-29 12:57:52 +02009907 if (start < 0) {
9908 PyErr_SetString(PyExc_IndexError, "string index out of range");
9909 return -1;
9910 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009911 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9912 PyErr_SetString(PyExc_ValueError,
9913 "fill character is bigger than "
9914 "the string maximum character");
9915 return -1;
9916 }
9917
9918 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9919 length = Py_MIN(maxlen, length);
9920 if (length <= 0)
9921 return 0;
9922
Victor Stinnerd3f08822012-05-29 12:57:52 +02009923 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009924 return length;
9925}
9926
Victor Stinner9310abb2011-10-05 00:59:23 +02009927static PyObject *
9928pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009929 Py_ssize_t left,
9930 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 PyObject *u;
9934 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009935 int kind;
9936 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937
9938 if (left < 0)
9939 left = 0;
9940 if (right < 0)
9941 right = 0;
9942
Victor Stinnerc4b49542011-12-11 22:44:26 +01009943 if (left == 0 && right == 0)
9944 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9947 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009948 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9949 return NULL;
9950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009952 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009954 if (!u)
9955 return NULL;
9956
9957 kind = PyUnicode_KIND(u);
9958 data = PyUnicode_DATA(u);
9959 if (left)
9960 FILL(kind, data, fill, 0, left);
9961 if (right)
9962 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009963 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009964 assert(_PyUnicode_CheckConsistency(u, 1));
9965 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966}
9967
Alexander Belopolsky40018472011-02-26 01:02:56 +00009968PyObject *
9969PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009970{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009972
9973 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009974 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009975 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009976 if (PyUnicode_READY(string) == -1) {
9977 Py_DECREF(string);
9978 return NULL;
9979 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980
Benjamin Petersonead6b532011-12-20 17:23:42 -06009981 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009983 if (PyUnicode_IS_ASCII(string))
9984 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009985 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009986 PyUnicode_GET_LENGTH(string), keepends);
9987 else
9988 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009989 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009990 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 break;
9992 case PyUnicode_2BYTE_KIND:
9993 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009994 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 PyUnicode_GET_LENGTH(string), keepends);
9996 break;
9997 case PyUnicode_4BYTE_KIND:
9998 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009999 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010000 PyUnicode_GET_LENGTH(string), keepends);
10001 break;
10002 default:
10003 assert(0);
10004 list = 0;
10005 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010006 Py_DECREF(string);
10007 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008}
10009
Alexander Belopolsky40018472011-02-26 01:02:56 +000010010static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010011split(PyObject *self,
10012 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010013 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010015 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016 void *buf1, *buf2;
10017 Py_ssize_t len1, len2;
10018 PyObject* out;
10019
Guido van Rossumd57fd912000-03-10 22:53:23 +000010020 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010021 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023 if (PyUnicode_READY(self) == -1)
10024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010027 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010029 if (PyUnicode_IS_ASCII(self))
10030 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010031 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010032 PyUnicode_GET_LENGTH(self), maxcount
10033 );
10034 else
10035 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010036 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010037 PyUnicode_GET_LENGTH(self), maxcount
10038 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 case PyUnicode_2BYTE_KIND:
10040 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010041 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 PyUnicode_GET_LENGTH(self), maxcount
10043 );
10044 case PyUnicode_4BYTE_KIND:
10045 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010046 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 PyUnicode_GET_LENGTH(self), maxcount
10048 );
10049 default:
10050 assert(0);
10051 return NULL;
10052 }
10053
10054 if (PyUnicode_READY(substring) == -1)
10055 return NULL;
10056
10057 kind1 = PyUnicode_KIND(self);
10058 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 len1 = PyUnicode_GET_LENGTH(self);
10060 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010061 if (kind1 < kind2 || len1 < len2) {
10062 out = PyList_New(1);
10063 if (out == NULL)
10064 return NULL;
10065 Py_INCREF(self);
10066 PyList_SET_ITEM(out, 0, self);
10067 return out;
10068 }
10069 buf1 = PyUnicode_DATA(self);
10070 buf2 = PyUnicode_DATA(substring);
10071 if (kind2 != kind1) {
10072 buf2 = _PyUnicode_AsKind(substring, kind1);
10073 if (!buf2)
10074 return NULL;
10075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010077 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010079 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10080 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010081 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010082 else
10083 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010084 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 break;
10086 case PyUnicode_2BYTE_KIND:
10087 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010088 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 break;
10090 case PyUnicode_4BYTE_KIND:
10091 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010092 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 break;
10094 default:
10095 out = NULL;
10096 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010097 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 PyMem_Free(buf2);
10099 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010100}
10101
Alexander Belopolsky40018472011-02-26 01:02:56 +000010102static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010103rsplit(PyObject *self,
10104 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010105 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010106{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010107 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 void *buf1, *buf2;
10109 Py_ssize_t len1, len2;
10110 PyObject* out;
10111
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010112 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010113 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 if (PyUnicode_READY(self) == -1)
10116 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010119 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010121 if (PyUnicode_IS_ASCII(self))
10122 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010123 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 PyUnicode_GET_LENGTH(self), maxcount
10125 );
10126 else
10127 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010128 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010129 PyUnicode_GET_LENGTH(self), maxcount
10130 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 case PyUnicode_2BYTE_KIND:
10132 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010133 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 PyUnicode_GET_LENGTH(self), maxcount
10135 );
10136 case PyUnicode_4BYTE_KIND:
10137 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010138 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 PyUnicode_GET_LENGTH(self), maxcount
10140 );
10141 default:
10142 assert(0);
10143 return NULL;
10144 }
10145
10146 if (PyUnicode_READY(substring) == -1)
10147 return NULL;
10148
10149 kind1 = PyUnicode_KIND(self);
10150 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 len1 = PyUnicode_GET_LENGTH(self);
10152 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010153 if (kind1 < kind2 || len1 < len2) {
10154 out = PyList_New(1);
10155 if (out == NULL)
10156 return NULL;
10157 Py_INCREF(self);
10158 PyList_SET_ITEM(out, 0, self);
10159 return out;
10160 }
10161 buf1 = PyUnicode_DATA(self);
10162 buf2 = PyUnicode_DATA(substring);
10163 if (kind2 != kind1) {
10164 buf2 = _PyUnicode_AsKind(substring, kind1);
10165 if (!buf2)
10166 return NULL;
10167 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010169 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010171 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10172 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010173 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010174 else
10175 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010176 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 break;
10178 case PyUnicode_2BYTE_KIND:
10179 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010180 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 break;
10182 case PyUnicode_4BYTE_KIND:
10183 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010184 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 break;
10186 default:
10187 out = NULL;
10188 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010189 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 PyMem_Free(buf2);
10191 return out;
10192}
10193
10194static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010195anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10196 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010198 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010200 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10201 return asciilib_find(buf1, len1, buf2, len2, offset);
10202 else
10203 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 case PyUnicode_2BYTE_KIND:
10205 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10206 case PyUnicode_4BYTE_KIND:
10207 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10208 }
10209 assert(0);
10210 return -1;
10211}
10212
10213static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010214anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10215 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010217 switch (kind) {
10218 case PyUnicode_1BYTE_KIND:
10219 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10220 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10221 else
10222 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10223 case PyUnicode_2BYTE_KIND:
10224 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10225 case PyUnicode_4BYTE_KIND:
10226 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10227 }
10228 assert(0);
10229 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010230}
10231
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010232static void
10233replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10234 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10235{
10236 int kind = PyUnicode_KIND(u);
10237 void *data = PyUnicode_DATA(u);
10238 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10239 if (kind == PyUnicode_1BYTE_KIND) {
10240 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10241 (Py_UCS1 *)data + len,
10242 u1, u2, maxcount);
10243 }
10244 else if (kind == PyUnicode_2BYTE_KIND) {
10245 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10246 (Py_UCS2 *)data + len,
10247 u1, u2, maxcount);
10248 }
10249 else {
10250 assert(kind == PyUnicode_4BYTE_KIND);
10251 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10252 (Py_UCS4 *)data + len,
10253 u1, u2, maxcount);
10254 }
10255}
10256
Alexander Belopolsky40018472011-02-26 01:02:56 +000010257static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258replace(PyObject *self, PyObject *str1,
10259 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010260{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 PyObject *u;
10262 char *sbuf = PyUnicode_DATA(self);
10263 char *buf1 = PyUnicode_DATA(str1);
10264 char *buf2 = PyUnicode_DATA(str2);
10265 int srelease = 0, release1 = 0, release2 = 0;
10266 int skind = PyUnicode_KIND(self);
10267 int kind1 = PyUnicode_KIND(str1);
10268 int kind2 = PyUnicode_KIND(str2);
10269 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10270 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10271 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010272 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010273 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274
10275 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010276 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010278 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279
Victor Stinner59de0ee2011-10-07 10:01:28 +020010280 if (str1 == str2)
10281 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282
Victor Stinner49a0a212011-10-12 23:46:10 +020010283 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010284 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10285 if (maxchar < maxchar_str1)
10286 /* substring too wide to be present */
10287 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010288 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10289 /* Replacing str1 with str2 may cause a maxchar reduction in the
10290 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010291 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010292 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010295 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010297 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010299 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010300 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010301 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010302
Victor Stinner69ed0f42013-04-09 21:48:24 +020010303 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010304 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010305 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010306 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010307 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010309 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010311
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010312 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10313 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010314 }
10315 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 int rkind = skind;
10317 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010318 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 if (kind1 < rkind) {
10321 /* widen substring */
10322 buf1 = _PyUnicode_AsKind(str1, rkind);
10323 if (!buf1) goto error;
10324 release1 = 1;
10325 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010327 if (i < 0)
10328 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 if (rkind > kind2) {
10330 /* widen replacement */
10331 buf2 = _PyUnicode_AsKind(str2, rkind);
10332 if (!buf2) goto error;
10333 release2 = 1;
10334 }
10335 else if (rkind < kind2) {
10336 /* widen self and buf1 */
10337 rkind = kind2;
10338 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010339 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 sbuf = _PyUnicode_AsKind(self, rkind);
10341 if (!sbuf) goto error;
10342 srelease = 1;
10343 buf1 = _PyUnicode_AsKind(str1, rkind);
10344 if (!buf1) goto error;
10345 release1 = 1;
10346 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010347 u = PyUnicode_New(slen, maxchar);
10348 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010350 assert(PyUnicode_KIND(u) == rkind);
10351 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010352
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010353 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010354 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010355 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010357 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010359
10360 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010361 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010362 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010363 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010364 if (i == -1)
10365 break;
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 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010371 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010372 }
10373 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010374 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010375 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 int rkind = skind;
10377 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010380 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 buf1 = _PyUnicode_AsKind(str1, rkind);
10382 if (!buf1) goto error;
10383 release1 = 1;
10384 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010385 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010386 if (n == 0)
10387 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010389 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 buf2 = _PyUnicode_AsKind(str2, rkind);
10391 if (!buf2) goto error;
10392 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010395 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 rkind = kind2;
10397 sbuf = _PyUnicode_AsKind(self, rkind);
10398 if (!sbuf) goto error;
10399 srelease = 1;
10400 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010401 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 buf1 = _PyUnicode_AsKind(str1, rkind);
10403 if (!buf1) goto error;
10404 release1 = 1;
10405 }
10406 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10407 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010408 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 PyErr_SetString(PyExc_OverflowError,
10410 "replace string is too long");
10411 goto error;
10412 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010413 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010414 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010415 _Py_INCREF_UNICODE_EMPTY();
10416 if (!unicode_empty)
10417 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010418 u = unicode_empty;
10419 goto done;
10420 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010421 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 PyErr_SetString(PyExc_OverflowError,
10423 "replace string is too long");
10424 goto error;
10425 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010426 u = PyUnicode_New(new_size, maxchar);
10427 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010429 assert(PyUnicode_KIND(u) == rkind);
10430 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 ires = i = 0;
10432 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010433 while (n-- > 0) {
10434 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010435 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010436 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010437 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010438 if (j == -1)
10439 break;
10440 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010441 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010442 memcpy(res + rkind * ires,
10443 sbuf + rkind * i,
10444 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010446 }
10447 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010449 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010451 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010455 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010457 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 memcpy(res + rkind * ires,
10459 sbuf + rkind * i,
10460 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010461 }
10462 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 /* interleave */
10464 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010465 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010467 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010469 if (--n <= 0)
10470 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 memcpy(res + rkind * ires,
10472 sbuf + rkind * i,
10473 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 ires++;
10475 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010477 memcpy(res + rkind * ires,
10478 sbuf + rkind * i,
10479 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010480 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010481 }
10482
10483 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010484 unicode_adjust_maxchar(&u);
10485 if (u == NULL)
10486 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010488
10489 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 if (srelease)
10491 PyMem_FREE(sbuf);
10492 if (release1)
10493 PyMem_FREE(buf1);
10494 if (release2)
10495 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010496 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010498
Benjamin Peterson29060642009-01-31 22:14:21 +000010499 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 /* nothing to replace; return original string (when possible) */
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 Stinnerc4b49542011-12-11 22:44:26 +010010507 return unicode_result_unchanged(self);
10508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 error:
10510 if (srelease && sbuf)
10511 PyMem_FREE(sbuf);
10512 if (release1 && buf1)
10513 PyMem_FREE(buf1);
10514 if (release2 && buf2)
10515 PyMem_FREE(buf2);
10516 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517}
10518
10519/* --- Unicode Object Methods --------------------------------------------- */
10520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010521PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010522 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523\n\
10524Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010525characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010526
10527static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010528unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010530 if (PyUnicode_READY(self) == -1)
10531 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010532 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010533}
10534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010535PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010536 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537\n\
10538Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010539have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540
10541static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010542unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010544 if (PyUnicode_READY(self) == -1)
10545 return NULL;
10546 if (PyUnicode_GET_LENGTH(self) == 0)
10547 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010548 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549}
10550
Benjamin Petersond5890c82012-01-14 13:23:30 -050010551PyDoc_STRVAR(casefold__doc__,
10552 "S.casefold() -> str\n\
10553\n\
10554Return a version of S suitable for caseless comparisons.");
10555
10556static PyObject *
10557unicode_casefold(PyObject *self)
10558{
10559 if (PyUnicode_READY(self) == -1)
10560 return NULL;
10561 if (PyUnicode_IS_ASCII(self))
10562 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010563 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010564}
10565
10566
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010567/* Argument converter. Coerces to a single unicode character */
10568
10569static int
10570convert_uc(PyObject *obj, void *addr)
10571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010573 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010574
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575 uniobj = PyUnicode_FromObject(obj);
10576 if (uniobj == NULL) {
10577 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010578 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010579 return 0;
10580 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010582 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010583 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010584 Py_DECREF(uniobj);
10585 return 0;
10586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010588 Py_DECREF(uniobj);
10589 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010590}
10591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010592PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010593 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010595Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010596done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010597
10598static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010599unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010601 Py_ssize_t marg, left;
10602 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 Py_UCS4 fillchar = ' ';
10604
Victor Stinnere9a29352011-10-01 02:14:59 +020010605 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607
Benjamin Petersonbac79492012-01-14 13:34:47 -050010608 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609 return NULL;
10610
Victor Stinnerc4b49542011-12-11 22:44:26 +010010611 if (PyUnicode_GET_LENGTH(self) >= width)
10612 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613
Victor Stinnerc4b49542011-12-11 22:44:26 +010010614 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615 left = marg / 2 + (marg & width & 1);
10616
Victor Stinner9310abb2011-10-05 00:59:23 +020010617 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618}
10619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620/* This function assumes that str1 and str2 are readied by the caller. */
10621
Marc-André Lemburge5034372000-08-08 08:04:29 +000010622static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010623unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010624{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010625#define COMPARE(TYPE1, TYPE2) \
10626 do { \
10627 TYPE1* p1 = (TYPE1 *)data1; \
10628 TYPE2* p2 = (TYPE2 *)data2; \
10629 TYPE1* end = p1 + len; \
10630 Py_UCS4 c1, c2; \
10631 for (; p1 != end; p1++, p2++) { \
10632 c1 = *p1; \
10633 c2 = *p2; \
10634 if (c1 != c2) \
10635 return (c1 < c2) ? -1 : 1; \
10636 } \
10637 } \
10638 while (0)
10639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 int kind1, kind2;
10641 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010642 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 kind1 = PyUnicode_KIND(str1);
10645 kind2 = PyUnicode_KIND(str2);
10646 data1 = PyUnicode_DATA(str1);
10647 data2 = PyUnicode_DATA(str2);
10648 len1 = PyUnicode_GET_LENGTH(str1);
10649 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010650 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010651
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010652 switch(kind1) {
10653 case PyUnicode_1BYTE_KIND:
10654 {
10655 switch(kind2) {
10656 case PyUnicode_1BYTE_KIND:
10657 {
10658 int cmp = memcmp(data1, data2, len);
10659 /* normalize result of memcmp() into the range [-1; 1] */
10660 if (cmp < 0)
10661 return -1;
10662 if (cmp > 0)
10663 return 1;
10664 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010665 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010666 case PyUnicode_2BYTE_KIND:
10667 COMPARE(Py_UCS1, Py_UCS2);
10668 break;
10669 case PyUnicode_4BYTE_KIND:
10670 COMPARE(Py_UCS1, Py_UCS4);
10671 break;
10672 default:
10673 assert(0);
10674 }
10675 break;
10676 }
10677 case PyUnicode_2BYTE_KIND:
10678 {
10679 switch(kind2) {
10680 case PyUnicode_1BYTE_KIND:
10681 COMPARE(Py_UCS2, Py_UCS1);
10682 break;
10683 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010684 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010685 COMPARE(Py_UCS2, Py_UCS2);
10686 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010687 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010688 case PyUnicode_4BYTE_KIND:
10689 COMPARE(Py_UCS2, Py_UCS4);
10690 break;
10691 default:
10692 assert(0);
10693 }
10694 break;
10695 }
10696 case PyUnicode_4BYTE_KIND:
10697 {
10698 switch(kind2) {
10699 case PyUnicode_1BYTE_KIND:
10700 COMPARE(Py_UCS4, Py_UCS1);
10701 break;
10702 case PyUnicode_2BYTE_KIND:
10703 COMPARE(Py_UCS4, Py_UCS2);
10704 break;
10705 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010706 {
10707#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10708 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10709 /* normalize result of wmemcmp() into the range [-1; 1] */
10710 if (cmp < 0)
10711 return -1;
10712 if (cmp > 0)
10713 return 1;
10714#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010715 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010716#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010717 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010718 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010719 default:
10720 assert(0);
10721 }
10722 break;
10723 }
10724 default:
10725 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010726 }
10727
Victor Stinner770e19e2012-10-04 22:59:45 +020010728 if (len1 == len2)
10729 return 0;
10730 if (len1 < len2)
10731 return -1;
10732 else
10733 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010734
10735#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010736}
10737
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010738Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010739unicode_compare_eq(PyObject *str1, PyObject *str2)
10740{
10741 int kind;
10742 void *data1, *data2;
10743 Py_ssize_t len;
10744 int cmp;
10745
Victor Stinnere5567ad2012-10-23 02:48:49 +020010746 len = PyUnicode_GET_LENGTH(str1);
10747 if (PyUnicode_GET_LENGTH(str2) != len)
10748 return 0;
10749 kind = PyUnicode_KIND(str1);
10750 if (PyUnicode_KIND(str2) != kind)
10751 return 0;
10752 data1 = PyUnicode_DATA(str1);
10753 data2 = PyUnicode_DATA(str2);
10754
10755 cmp = memcmp(data1, data2, len * kind);
10756 return (cmp == 0);
10757}
10758
10759
Alexander Belopolsky40018472011-02-26 01:02:56 +000010760int
10761PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010763 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10764 if (PyUnicode_READY(left) == -1 ||
10765 PyUnicode_READY(right) == -1)
10766 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010767
10768 /* a string is equal to itself */
10769 if (left == right)
10770 return 0;
10771
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010772 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010774 PyErr_Format(PyExc_TypeError,
10775 "Can't compare %.100s and %.100s",
10776 left->ob_type->tp_name,
10777 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778 return -1;
10779}
10780
Martin v. Löwis5b222132007-06-10 09:51:05 +000010781int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010782_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10783{
10784 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10785 if (right_str == NULL)
10786 return -1;
10787 return PyUnicode_Compare(left, right_str);
10788}
10789
10790int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010791PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 Py_ssize_t i;
10794 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 Py_UCS4 chr;
10796
Victor Stinner910337b2011-10-03 03:20:16 +020010797 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 if (PyUnicode_READY(uni) == -1)
10799 return -1;
10800 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010801 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010802 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010803 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010804 size_t len, len2 = strlen(str);
10805 int cmp;
10806
10807 len = Py_MIN(len1, len2);
10808 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010809 if (cmp != 0) {
10810 if (cmp < 0)
10811 return -1;
10812 else
10813 return 1;
10814 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010815 if (len1 > len2)
10816 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010817 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010818 return -1; /* str is longer */
10819 return 0;
10820 }
10821 else {
10822 void *data = PyUnicode_DATA(uni);
10823 /* Compare Unicode string and source character set string */
10824 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010825 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010826 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10827 /* This check keeps Python strings that end in '\0' from comparing equal
10828 to C strings identical up to that point. */
10829 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10830 return 1; /* uni is longer */
10831 if (str[i])
10832 return -1; /* str is longer */
10833 return 0;
10834 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010835}
10836
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010837static int
10838non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10839{
10840 size_t i, len;
10841 const wchar_t *p;
10842 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10843 if (strlen(str) != len)
10844 return 0;
10845 p = _PyUnicode_WSTR(unicode);
10846 assert(p);
10847 for (i = 0; i < len; i++) {
10848 unsigned char c = (unsigned char)str[i];
10849 if (c > 128 || p[i] != (wchar_t)c)
10850 return 0;
10851 }
10852 return 1;
10853}
10854
10855int
10856_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
10857{
10858 size_t len;
10859 assert(_PyUnicode_CHECK(unicode));
10860 if (PyUnicode_READY(unicode) == -1) {
10861 /* Memory error or bad data */
10862 PyErr_Clear();
10863 return non_ready_unicode_equal_to_ascii_string(unicode, str);
10864 }
10865 if (!PyUnicode_IS_ASCII(unicode))
10866 return 0;
10867 len = (size_t)PyUnicode_GET_LENGTH(unicode);
10868 return strlen(str) == len &&
10869 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
10870}
10871
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020010872int
10873_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
10874{
10875 PyObject *right_uni;
10876 Py_hash_t hash;
10877
10878 assert(_PyUnicode_CHECK(left));
10879 assert(right->string);
10880
10881 if (PyUnicode_READY(left) == -1) {
10882 /* memory error or bad data */
10883 PyErr_Clear();
10884 return non_ready_unicode_equal_to_ascii_string(left, right->string);
10885 }
10886
10887 if (!PyUnicode_IS_ASCII(left))
10888 return 0;
10889
10890 right_uni = _PyUnicode_FromId(right); /* borrowed */
10891 if (right_uni == NULL) {
10892 /* memory error or bad data */
10893 PyErr_Clear();
10894 return _PyUnicode_EqualToASCIIString(left, right->string);
10895 }
10896
10897 if (left == right_uni)
10898 return 1;
10899
10900 if (PyUnicode_CHECK_INTERNED(left))
10901 return 0;
10902
10903 assert(_PyUnicode_HASH(right_uni) != 1);
10904 hash = _PyUnicode_HASH(left);
10905 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
10906 return 0;
10907
10908 return unicode_compare_eq(left, right_uni);
10909}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010910
Benjamin Peterson29060642009-01-31 22:14:21 +000010911#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010912 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010913
Alexander Belopolsky40018472011-02-26 01:02:56 +000010914PyObject *
10915PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010916{
10917 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010918 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010919
Victor Stinnere5567ad2012-10-23 02:48:49 +020010920 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10921 Py_RETURN_NOTIMPLEMENTED;
10922
10923 if (PyUnicode_READY(left) == -1 ||
10924 PyUnicode_READY(right) == -1)
10925 return NULL;
10926
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010927 if (left == right) {
10928 switch (op) {
10929 case Py_EQ:
10930 case Py_LE:
10931 case Py_GE:
10932 /* a string is equal to itself */
10933 v = Py_True;
10934 break;
10935 case Py_NE:
10936 case Py_LT:
10937 case Py_GT:
10938 v = Py_False;
10939 break;
10940 default:
10941 PyErr_BadArgument();
10942 return NULL;
10943 }
10944 }
10945 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010946 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010947 result ^= (op == Py_NE);
10948 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010949 }
10950 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010951 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010952
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010953 /* Convert the return value to a Boolean */
10954 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010955 case Py_LE:
10956 v = TEST_COND(result <= 0);
10957 break;
10958 case Py_GE:
10959 v = TEST_COND(result >= 0);
10960 break;
10961 case Py_LT:
10962 v = TEST_COND(result == -1);
10963 break;
10964 case Py_GT:
10965 v = TEST_COND(result == 1);
10966 break;
10967 default:
10968 PyErr_BadArgument();
10969 return NULL;
10970 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010971 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010972 Py_INCREF(v);
10973 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010974}
10975
Alexander Belopolsky40018472011-02-26 01:02:56 +000010976int
10977PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010978{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010979 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010980 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010981 void *buf1, *buf2;
10982 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010983 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010984
10985 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010986 sub = PyUnicode_FromObject(element);
10987 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010988 PyErr_Format(PyExc_TypeError,
10989 "'in <string>' requires string as left operand, not %s",
10990 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010991 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010992 }
10993
Thomas Wouters477c8d52006-05-27 19:21:47 +000010994 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010995 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010996 Py_DECREF(sub);
10997 return -1;
10998 }
10999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 kind1 = PyUnicode_KIND(str);
11001 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011002 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011003 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050011004 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011005 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011006 }
11007 len1 = PyUnicode_GET_LENGTH(str);
11008 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011009 if (len1 < len2) {
11010 Py_DECREF(sub);
11011 Py_DECREF(str);
11012 return 0;
11013 }
11014 buf1 = PyUnicode_DATA(str);
11015 buf2 = PyUnicode_DATA(sub);
11016 if (len2 == 1) {
11017 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11018 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11019 Py_DECREF(sub);
11020 Py_DECREF(str);
11021 return result;
11022 }
11023 if (kind2 != kind1) {
11024 buf2 = _PyUnicode_AsKind(sub, kind1);
11025 if (!buf2) {
11026 Py_DECREF(sub);
11027 Py_DECREF(str);
11028 return -1;
11029 }
11030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011031
Victor Stinner77282cb2013-04-14 19:22:47 +020011032 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033 case PyUnicode_1BYTE_KIND:
11034 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11035 break;
11036 case PyUnicode_2BYTE_KIND:
11037 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11038 break;
11039 case PyUnicode_4BYTE_KIND:
11040 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11041 break;
11042 default:
11043 result = -1;
11044 assert(0);
11045 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011046
11047 Py_DECREF(str);
11048 Py_DECREF(sub);
11049
Victor Stinner77282cb2013-04-14 19:22:47 +020011050 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011051 PyMem_Free(buf2);
11052
Guido van Rossum403d68b2000-03-13 15:55:09 +000011053 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011054}
11055
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056/* Concat to string or Unicode object giving a new Unicode object. */
11057
Alexander Belopolsky40018472011-02-26 01:02:56 +000011058PyObject *
11059PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011062 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011063 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064
11065 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011068 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011071 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072
11073 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011074 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011075 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011076 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011078 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011079 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011080 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081 }
11082
Victor Stinner488fa492011-12-12 00:01:39 +010011083 u_len = PyUnicode_GET_LENGTH(u);
11084 v_len = PyUnicode_GET_LENGTH(v);
11085 if (u_len > PY_SSIZE_T_MAX - v_len) {
11086 PyErr_SetString(PyExc_OverflowError,
11087 "strings are too large to concat");
11088 goto onError;
11089 }
11090 new_len = u_len + v_len;
11091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011092 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011093 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011094 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011095
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011097 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011098 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011099 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011100 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11101 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102 Py_DECREF(u);
11103 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011104 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106
Benjamin Peterson29060642009-01-31 22:14:21 +000011107 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011108 Py_XDECREF(u);
11109 Py_XDECREF(v);
11110 return NULL;
11111}
11112
Walter Dörwald1ab83302007-05-18 17:15:44 +000011113void
Victor Stinner23e56682011-10-03 03:54:37 +020011114PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011115{
Victor Stinner23e56682011-10-03 03:54:37 +020011116 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011117 Py_UCS4 maxchar, maxchar2;
11118 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011119
11120 if (p_left == NULL) {
11121 if (!PyErr_Occurred())
11122 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011123 return;
11124 }
Victor Stinner23e56682011-10-03 03:54:37 +020011125 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011126 if (right == NULL || left == NULL
11127 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011128 if (!PyErr_Occurred())
11129 PyErr_BadInternalCall();
11130 goto error;
11131 }
11132
Benjamin Petersonbac79492012-01-14 13:34:47 -050011133 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011134 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011135 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011136 goto error;
11137
Victor Stinner488fa492011-12-12 00:01:39 +010011138 /* Shortcuts */
11139 if (left == unicode_empty) {
11140 Py_DECREF(left);
11141 Py_INCREF(right);
11142 *p_left = right;
11143 return;
11144 }
11145 if (right == unicode_empty)
11146 return;
11147
11148 left_len = PyUnicode_GET_LENGTH(left);
11149 right_len = PyUnicode_GET_LENGTH(right);
11150 if (left_len > PY_SSIZE_T_MAX - right_len) {
11151 PyErr_SetString(PyExc_OverflowError,
11152 "strings are too large to concat");
11153 goto error;
11154 }
11155 new_len = left_len + right_len;
11156
11157 if (unicode_modifiable(left)
11158 && PyUnicode_CheckExact(right)
11159 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011160 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11161 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011162 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011163 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011164 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11165 {
11166 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011167 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011168 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011169
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011170 /* copy 'right' into the newly allocated area of 'left' */
11171 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011172 }
Victor Stinner488fa492011-12-12 00:01:39 +010011173 else {
11174 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11175 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011176 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011177
Victor Stinner488fa492011-12-12 00:01:39 +010011178 /* Concat the two Unicode strings */
11179 res = PyUnicode_New(new_len, maxchar);
11180 if (res == NULL)
11181 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011182 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11183 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011184 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011185 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011186 }
11187 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011188 return;
11189
11190error:
Victor Stinner488fa492011-12-12 00:01:39 +010011191 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011192}
11193
11194void
11195PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11196{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011197 PyUnicode_Append(pleft, right);
11198 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011199}
11200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011201PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011202 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011204Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011205string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011206interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011209unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011211 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011212 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011213 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011215 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011216 void *buf1, *buf2;
11217 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
Jesus Ceaac451502011-04-20 17:09:23 +020011219 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11220 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 kind1 = PyUnicode_KIND(self);
11224 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011225 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011226 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011227 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229 len1 = PyUnicode_GET_LENGTH(self);
11230 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011232 if (end - start < len2) {
11233 Py_DECREF(substring);
11234 return PyLong_FromLong(0);
11235 }
11236 buf1 = PyUnicode_DATA(self);
11237 buf2 = PyUnicode_DATA(substring);
11238 if (kind2 != kind1) {
11239 buf2 = _PyUnicode_AsKind(substring, kind1);
11240 if (!buf2) {
11241 Py_DECREF(substring);
11242 return NULL;
11243 }
11244 }
11245 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 case PyUnicode_1BYTE_KIND:
11247 iresult = ucs1lib_count(
11248 ((Py_UCS1*)buf1) + start, end - start,
11249 buf2, len2, PY_SSIZE_T_MAX
11250 );
11251 break;
11252 case PyUnicode_2BYTE_KIND:
11253 iresult = ucs2lib_count(
11254 ((Py_UCS2*)buf1) + start, end - start,
11255 buf2, len2, PY_SSIZE_T_MAX
11256 );
11257 break;
11258 case PyUnicode_4BYTE_KIND:
11259 iresult = ucs4lib_count(
11260 ((Py_UCS4*)buf1) + start, end - start,
11261 buf2, len2, PY_SSIZE_T_MAX
11262 );
11263 break;
11264 default:
11265 assert(0); iresult = 0;
11266 }
11267
11268 result = PyLong_FromSsize_t(iresult);
11269
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011270 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011271 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272
11273 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011274
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275 return result;
11276}
11277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011278PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011279 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011281Encode S using the codec registered for encoding. Default encoding\n\
11282is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011283handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011284a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11285'xmlcharrefreplace' as well as any other name registered with\n\
11286codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287
11288static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011289unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011291 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292 char *encoding = NULL;
11293 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011294
Benjamin Peterson308d6372009-09-18 21:42:35 +000011295 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11296 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011298 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011299}
11300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011301PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011302 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303\n\
11304Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011305If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306
11307static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011308unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011310 Py_ssize_t i, j, line_pos, src_len, incr;
11311 Py_UCS4 ch;
11312 PyObject *u;
11313 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011314 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011316 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011317 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318
Ezio Melotti745d54d2013-11-16 19:10:57 +020011319 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11320 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322
Antoine Pitrou22425222011-10-04 19:10:51 +020011323 if (PyUnicode_READY(self) == -1)
11324 return NULL;
11325
Thomas Wouters7e474022000-07-16 12:04:32 +000011326 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011327 src_len = PyUnicode_GET_LENGTH(self);
11328 i = j = line_pos = 0;
11329 kind = PyUnicode_KIND(self);
11330 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011331 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011332 for (; i < src_len; i++) {
11333 ch = PyUnicode_READ(kind, src_data, i);
11334 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011335 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011336 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011337 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011339 goto overflow;
11340 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011341 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011342 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011345 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011346 goto overflow;
11347 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011349 if (ch == '\n' || ch == '\r')
11350 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011352 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011353 if (!found)
11354 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011355
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011357 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358 if (!u)
11359 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011360 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361
Antoine Pitroue71d5742011-10-04 15:55:09 +020011362 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363
Antoine Pitroue71d5742011-10-04 15:55:09 +020011364 for (; i < src_len; i++) {
11365 ch = PyUnicode_READ(kind, src_data, i);
11366 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011368 incr = tabsize - (line_pos % tabsize);
11369 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011370 FILL(kind, dest_data, ' ', j, incr);
11371 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011372 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011373 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011374 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011375 line_pos++;
11376 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011377 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011378 if (ch == '\n' || ch == '\r')
11379 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011381 }
11382 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011383 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011384
Antoine Pitroue71d5742011-10-04 15:55:09 +020011385 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011386 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11387 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388}
11389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011390PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011391 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392\n\
11393Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011394such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395arguments start and end are interpreted as in slice notation.\n\
11396\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011397Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
11399static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011400unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011402 /* initialize variables to prevent gcc warning */
11403 PyObject *substring = NULL;
11404 Py_ssize_t start = 0;
11405 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011406 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
Jesus Ceaac451502011-04-20 17:09:23 +020011408 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11409 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411
Christian Heimesd47802e2013-06-29 21:33:36 +020011412 if (PyUnicode_READY(self) == -1) {
11413 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011414 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011415 }
11416 if (PyUnicode_READY(substring) == -1) {
11417 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011418 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011419 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420
Victor Stinner7931d9a2011-11-04 00:22:48 +010011421 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422
11423 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 if (result == -2)
11426 return NULL;
11427
Christian Heimes217cfd12007-12-02 14:31:20 +000011428 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429}
11430
11431static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011432unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011434 void *data;
11435 enum PyUnicode_Kind kind;
11436 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011437
11438 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11439 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011441 }
11442 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11443 PyErr_SetString(PyExc_IndexError, "string index out of range");
11444 return NULL;
11445 }
11446 kind = PyUnicode_KIND(self);
11447 data = PyUnicode_DATA(self);
11448 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011449 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450}
11451
Guido van Rossumc2504932007-09-18 19:42:40 +000011452/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011453 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011454static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011455unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456{
Guido van Rossumc2504932007-09-18 19:42:40 +000011457 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011458 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011459
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011460#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011461 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011462#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 if (_PyUnicode_HASH(self) != -1)
11464 return _PyUnicode_HASH(self);
11465 if (PyUnicode_READY(self) == -1)
11466 return -1;
11467 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011468 /*
11469 We make the hash of the empty string be 0, rather than using
11470 (prefix ^ suffix), since this slightly obfuscates the hash secret
11471 */
11472 if (len == 0) {
11473 _PyUnicode_HASH(self) = 0;
11474 return 0;
11475 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011476 x = _Py_HashBytes(PyUnicode_DATA(self),
11477 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011479 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480}
11481
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011482PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011485Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486
11487static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011490 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011491 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011492 PyObject *substring = NULL;
11493 Py_ssize_t start = 0;
11494 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495
Jesus Ceaac451502011-04-20 17:09:23 +020011496 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11497 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499
Christian Heimesd47a0452013-06-29 21:21:37 +020011500 if (PyUnicode_READY(self) == -1) {
11501 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011502 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011503 }
11504 if (PyUnicode_READY(substring) == -1) {
11505 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011507 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508
Victor Stinner7931d9a2011-11-04 00:22:48 +010011509 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
11511 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 if (result == -2)
11514 return NULL;
11515
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 if (result < 0) {
11517 PyErr_SetString(PyExc_ValueError, "substring not found");
11518 return NULL;
11519 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011520
Christian Heimes217cfd12007-12-02 14:31:20 +000011521 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522}
11523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011524PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011527Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011528at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529
11530static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011531unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 Py_ssize_t i, length;
11534 int kind;
11535 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536 int cased;
11537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 if (PyUnicode_READY(self) == -1)
11539 return NULL;
11540 length = PyUnicode_GET_LENGTH(self);
11541 kind = PyUnicode_KIND(self);
11542 data = PyUnicode_DATA(self);
11543
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 if (length == 1)
11546 return PyBool_FromLong(
11547 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011549 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011551 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011552
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 for (i = 0; i < length; i++) {
11555 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011556
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11558 return PyBool_FromLong(0);
11559 else if (!cased && Py_UNICODE_ISLOWER(ch))
11560 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011562 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563}
11564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011565PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011568Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011569at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
11571static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011572unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 Py_ssize_t i, length;
11575 int kind;
11576 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577 int cased;
11578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 if (PyUnicode_READY(self) == -1)
11580 return NULL;
11581 length = PyUnicode_GET_LENGTH(self);
11582 kind = PyUnicode_KIND(self);
11583 data = PyUnicode_DATA(self);
11584
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 if (length == 1)
11587 return PyBool_FromLong(
11588 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011590 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011593
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595 for (i = 0; i < length; i++) {
11596 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011597
Benjamin Peterson29060642009-01-31 22:14:21 +000011598 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11599 return PyBool_FromLong(0);
11600 else if (!cased && Py_UNICODE_ISUPPER(ch))
11601 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011603 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011609Return True if S is a titlecased string and there is at least one\n\
11610character in S, i.e. upper- and titlecase characters may only\n\
11611follow uncased characters and lowercase characters only cased ones.\n\
11612Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
11614static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011615unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 Py_ssize_t i, length;
11618 int kind;
11619 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620 int cased, previous_is_cased;
11621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 if (PyUnicode_READY(self) == -1)
11623 return NULL;
11624 length = PyUnicode_GET_LENGTH(self);
11625 kind = PyUnicode_KIND(self);
11626 data = PyUnicode_DATA(self);
11627
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 if (length == 1) {
11630 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11631 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11632 (Py_UNICODE_ISUPPER(ch) != 0));
11633 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011635 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011637 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011638
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639 cased = 0;
11640 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641 for (i = 0; i < length; i++) {
11642 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011643
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11645 if (previous_is_cased)
11646 return PyBool_FromLong(0);
11647 previous_is_cased = 1;
11648 cased = 1;
11649 }
11650 else if (Py_UNICODE_ISLOWER(ch)) {
11651 if (!previous_is_cased)
11652 return PyBool_FromLong(0);
11653 previous_is_cased = 1;
11654 cased = 1;
11655 }
11656 else
11657 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011658 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011659 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660}
11661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011662PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011663 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011664\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011665Return True if all characters in S are whitespace\n\
11666and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667
11668static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011669unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671 Py_ssize_t i, length;
11672 int kind;
11673 void *data;
11674
11675 if (PyUnicode_READY(self) == -1)
11676 return NULL;
11677 length = PyUnicode_GET_LENGTH(self);
11678 kind = PyUnicode_KIND(self);
11679 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682 if (length == 1)
11683 return PyBool_FromLong(
11684 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011686 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 for (i = 0; i < length; i++) {
11691 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011692 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011693 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011695 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696}
11697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011698PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011699 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011700\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011701Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011702and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011703
11704static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011705unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011706{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 Py_ssize_t i, length;
11708 int kind;
11709 void *data;
11710
11711 if (PyUnicode_READY(self) == -1)
11712 return NULL;
11713 length = PyUnicode_GET_LENGTH(self);
11714 kind = PyUnicode_KIND(self);
11715 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011716
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011717 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 if (length == 1)
11719 return PyBool_FromLong(
11720 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011721
11722 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011724 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 for (i = 0; i < length; i++) {
11727 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011729 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011730 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011731}
11732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011733PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011735\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011736Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011737and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011738
11739static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011740unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 int kind;
11743 void *data;
11744 Py_ssize_t len, i;
11745
11746 if (PyUnicode_READY(self) == -1)
11747 return NULL;
11748
11749 kind = PyUnicode_KIND(self);
11750 data = PyUnicode_DATA(self);
11751 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011752
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011753 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 if (len == 1) {
11755 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11756 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11757 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011758
11759 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011761 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 for (i = 0; i < len; i++) {
11764 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011765 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011767 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011768 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011769}
11770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011771PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011772 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011774Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011775False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776
11777static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011778unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 Py_ssize_t i, length;
11781 int kind;
11782 void *data;
11783
11784 if (PyUnicode_READY(self) == -1)
11785 return NULL;
11786 length = PyUnicode_GET_LENGTH(self);
11787 kind = PyUnicode_KIND(self);
11788 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 if (length == 1)
11792 return PyBool_FromLong(
11793 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011795 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011796 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011797 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 for (i = 0; i < length; i++) {
11800 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011803 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804}
11805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011806PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011807 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011809Return True if all characters in S are digits\n\
11810and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811
11812static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011813unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 Py_ssize_t i, length;
11816 int kind;
11817 void *data;
11818
11819 if (PyUnicode_READY(self) == -1)
11820 return NULL;
11821 length = PyUnicode_GET_LENGTH(self);
11822 kind = PyUnicode_KIND(self);
11823 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 if (length == 1) {
11827 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11828 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11829 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011831 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 for (i = 0; i < length; i++) {
11836 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011837 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011839 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840}
11841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011842PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011843 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011845Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011846False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847
11848static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011849unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 Py_ssize_t i, length;
11852 int kind;
11853 void *data;
11854
11855 if (PyUnicode_READY(self) == -1)
11856 return NULL;
11857 length = PyUnicode_GET_LENGTH(self);
11858 kind = PyUnicode_KIND(self);
11859 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 if (length == 1)
11863 return PyBool_FromLong(
11864 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011866 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 for (i = 0; i < length; i++) {
11871 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011872 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011874 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875}
11876
Martin v. Löwis47383402007-08-15 07:32:56 +000011877int
11878PyUnicode_IsIdentifier(PyObject *self)
11879{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 int kind;
11881 void *data;
11882 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011883 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011884
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 if (PyUnicode_READY(self) == -1) {
11886 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011887 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 }
11889
11890 /* Special case for empty strings */
11891 if (PyUnicode_GET_LENGTH(self) == 0)
11892 return 0;
11893 kind = PyUnicode_KIND(self);
11894 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011895
11896 /* PEP 3131 says that the first character must be in
11897 XID_Start and subsequent characters in XID_Continue,
11898 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011899 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011900 letters, digits, underscore). However, given the current
11901 definition of XID_Start and XID_Continue, it is sufficient
11902 to check just for these, except that _ must be allowed
11903 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011905 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011906 return 0;
11907
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011908 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011910 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011911 return 1;
11912}
11913
11914PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011916\n\
11917Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011918to the language definition.\n\
11919\n\
11920Use keyword.iskeyword() to test for reserved identifiers\n\
11921such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011922
11923static PyObject*
11924unicode_isidentifier(PyObject *self)
11925{
11926 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11927}
11928
Georg Brandl559e5d72008-06-11 18:37:52 +000011929PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011931\n\
11932Return True if all characters in S are considered\n\
11933printable in repr() or S is empty, False otherwise.");
11934
11935static PyObject*
11936unicode_isprintable(PyObject *self)
11937{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011938 Py_ssize_t i, length;
11939 int kind;
11940 void *data;
11941
11942 if (PyUnicode_READY(self) == -1)
11943 return NULL;
11944 length = PyUnicode_GET_LENGTH(self);
11945 kind = PyUnicode_KIND(self);
11946 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011947
11948 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 if (length == 1)
11950 return PyBool_FromLong(
11951 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 for (i = 0; i < length; i++) {
11954 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011955 Py_RETURN_FALSE;
11956 }
11957 }
11958 Py_RETURN_TRUE;
11959}
11960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011961PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011962 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963\n\
11964Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011965iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966
11967static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011968unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011970 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971}
11972
Martin v. Löwis18e16552006-02-15 17:27:45 +000011973static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011974unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 if (PyUnicode_READY(self) == -1)
11977 return -1;
11978 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979}
11980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011981PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011982 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011984Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011985done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986
11987static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011988unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011990 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 Py_UCS4 fillchar = ' ';
11992
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011993 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994 return NULL;
11995
Benjamin Petersonbac79492012-01-14 13:34:47 -050011996 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011997 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011998
Victor Stinnerc4b49542011-12-11 22:44:26 +010011999 if (PyUnicode_GET_LENGTH(self) >= width)
12000 return unicode_result_unchanged(self);
12001
12002 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003}
12004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012005PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012006 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012008Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009
12010static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012011unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012012{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012013 if (PyUnicode_READY(self) == -1)
12014 return NULL;
12015 if (PyUnicode_IS_ASCII(self))
12016 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012017 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012018}
12019
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012020#define LEFTSTRIP 0
12021#define RIGHTSTRIP 1
12022#define BOTHSTRIP 2
12023
12024/* Arrays indexed by above */
12025static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
12026
12027#define STRIPNAME(i) (stripformat[i]+3)
12028
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012029/* externally visible for str.strip(unicode) */
12030PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012031_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 void *data;
12034 int kind;
12035 Py_ssize_t i, j, len;
12036 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012037 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012038
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12040 return NULL;
12041
12042 kind = PyUnicode_KIND(self);
12043 data = PyUnicode_DATA(self);
12044 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012045 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12047 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012048 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012049
Benjamin Peterson14339b62009-01-31 16:36:08 +000012050 i = 0;
12051 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012052 while (i < len) {
12053 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12054 if (!BLOOM(sepmask, ch))
12055 break;
12056 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12057 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012058 i++;
12059 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012060 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012061
Benjamin Peterson14339b62009-01-31 16:36:08 +000012062 j = len;
12063 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012064 j--;
12065 while (j >= i) {
12066 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12067 if (!BLOOM(sepmask, ch))
12068 break;
12069 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12070 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012071 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012072 }
12073
Benjamin Peterson29060642009-01-31 22:14:21 +000012074 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012075 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012076
Victor Stinner7931d9a2011-11-04 00:22:48 +010012077 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012078}
12079
12080PyObject*
12081PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12082{
12083 unsigned char *data;
12084 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012085 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086
Victor Stinnerde636f32011-10-01 03:55:54 +020012087 if (PyUnicode_READY(self) == -1)
12088 return NULL;
12089
Victor Stinner684d5fd2012-05-03 02:32:34 +020012090 length = PyUnicode_GET_LENGTH(self);
12091 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012092
Victor Stinner684d5fd2012-05-03 02:32:34 +020012093 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012094 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095
Victor Stinnerde636f32011-10-01 03:55:54 +020012096 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012097 PyErr_SetString(PyExc_IndexError, "string index out of range");
12098 return NULL;
12099 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012100 if (start >= length || end < start)
12101 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012102
Victor Stinner684d5fd2012-05-03 02:32:34 +020012103 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012104 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012105 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012106 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012107 }
12108 else {
12109 kind = PyUnicode_KIND(self);
12110 data = PyUnicode_1BYTE_DATA(self);
12111 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012112 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012113 length);
12114 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116
12117static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012118do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 Py_ssize_t len, i, j;
12121
12122 if (PyUnicode_READY(self) == -1)
12123 return NULL;
12124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012126
Victor Stinnercc7af722013-04-09 22:39:24 +020012127 if (PyUnicode_IS_ASCII(self)) {
12128 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12129
12130 i = 0;
12131 if (striptype != RIGHTSTRIP) {
12132 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012133 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012134 if (!_Py_ascii_whitespace[ch])
12135 break;
12136 i++;
12137 }
12138 }
12139
12140 j = len;
12141 if (striptype != LEFTSTRIP) {
12142 j--;
12143 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012144 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012145 if (!_Py_ascii_whitespace[ch])
12146 break;
12147 j--;
12148 }
12149 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012150 }
12151 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012152 else {
12153 int kind = PyUnicode_KIND(self);
12154 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012155
Victor Stinnercc7af722013-04-09 22:39:24 +020012156 i = 0;
12157 if (striptype != RIGHTSTRIP) {
12158 while (i < len) {
12159 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12160 if (!Py_UNICODE_ISSPACE(ch))
12161 break;
12162 i++;
12163 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012164 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012165
12166 j = len;
12167 if (striptype != LEFTSTRIP) {
12168 j--;
12169 while (j >= i) {
12170 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12171 if (!Py_UNICODE_ISSPACE(ch))
12172 break;
12173 j--;
12174 }
12175 j++;
12176 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012177 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012178
Victor Stinner7931d9a2011-11-04 00:22:48 +010012179 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180}
12181
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012182
12183static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012184do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012185{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012186 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012187
Serhiy Storchakac6792272013-10-19 21:03:34 +030012188 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012189 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012190
Benjamin Peterson14339b62009-01-31 16:36:08 +000012191 if (sep != NULL && sep != Py_None) {
12192 if (PyUnicode_Check(sep))
12193 return _PyUnicode_XStrip(self, striptype, sep);
12194 else {
12195 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012196 "%s arg must be None or str",
12197 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012198 return NULL;
12199 }
12200 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012201
Benjamin Peterson14339b62009-01-31 16:36:08 +000012202 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012203}
12204
12205
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012206PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012207 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012208\n\
12209Return a copy of the string S with leading and trailing\n\
12210whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012211If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012212
12213static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012214unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012215{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012216 if (PyTuple_GET_SIZE(args) == 0)
12217 return do_strip(self, BOTHSTRIP); /* Common case */
12218 else
12219 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012220}
12221
12222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012223PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012224 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012225\n\
12226Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012227If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012228
12229static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012230unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012231{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012232 if (PyTuple_GET_SIZE(args) == 0)
12233 return do_strip(self, LEFTSTRIP); /* Common case */
12234 else
12235 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012236}
12237
12238
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012239PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012240 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012241\n\
12242Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012243If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012244
12245static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012246unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012247{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012248 if (PyTuple_GET_SIZE(args) == 0)
12249 return do_strip(self, RIGHTSTRIP); /* Common case */
12250 else
12251 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012252}
12253
12254
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012256unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012258 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260
Serhiy Storchaka05997252013-01-26 12:14:02 +020012261 if (len < 1)
12262 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263
Victor Stinnerc4b49542011-12-11 22:44:26 +010012264 /* no repeat, return original string */
12265 if (len == 1)
12266 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012267
Benjamin Petersonbac79492012-01-14 13:34:47 -050012268 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012269 return NULL;
12270
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012271 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012272 PyErr_SetString(PyExc_OverflowError,
12273 "repeated string is too long");
12274 return NULL;
12275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012277
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012278 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279 if (!u)
12280 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012281 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 if (PyUnicode_GET_LENGTH(str) == 1) {
12284 const int kind = PyUnicode_KIND(str);
12285 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012286 if (kind == PyUnicode_1BYTE_KIND) {
12287 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012288 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012289 }
12290 else if (kind == PyUnicode_2BYTE_KIND) {
12291 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012292 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012293 ucs2[n] = fill_char;
12294 } else {
12295 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12296 assert(kind == PyUnicode_4BYTE_KIND);
12297 for (n = 0; n < len; ++n)
12298 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 }
12301 else {
12302 /* number of characters copied this far */
12303 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012304 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 char *to = (char *) PyUnicode_DATA(u);
12306 Py_MEMCPY(to, PyUnicode_DATA(str),
12307 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012308 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 n = (done <= nchars-done) ? done : nchars-done;
12310 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012311 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012312 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313 }
12314
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012315 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012316 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317}
12318
Alexander Belopolsky40018472011-02-26 01:02:56 +000012319PyObject *
12320PyUnicode_Replace(PyObject *obj,
12321 PyObject *subobj,
12322 PyObject *replobj,
12323 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324{
12325 PyObject *self;
12326 PyObject *str1;
12327 PyObject *str2;
12328 PyObject *result;
12329
12330 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012331 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012332 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012334 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012335 Py_DECREF(self);
12336 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337 }
12338 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012339 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012340 Py_DECREF(self);
12341 Py_DECREF(str1);
12342 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012344 if (PyUnicode_READY(self) == -1 ||
12345 PyUnicode_READY(str1) == -1 ||
12346 PyUnicode_READY(str2) == -1)
12347 result = NULL;
12348 else
12349 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350 Py_DECREF(self);
12351 Py_DECREF(str1);
12352 Py_DECREF(str2);
12353 return result;
12354}
12355
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012356PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012357 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012358\n\
12359Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012360old replaced by new. If the optional argument count is\n\
12361given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012362
12363static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 PyObject *str1;
12367 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012368 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369 PyObject *result;
12370
Martin v. Löwis18e16552006-02-15 17:27:45 +000012371 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012373 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012374 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012376 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377 return NULL;
12378 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012379 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012380 Py_DECREF(str1);
12381 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012382 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012383 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12384 result = NULL;
12385 else
12386 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387
12388 Py_DECREF(str1);
12389 Py_DECREF(str2);
12390 return result;
12391}
12392
Alexander Belopolsky40018472011-02-26 01:02:56 +000012393static PyObject *
12394unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012396 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 Py_ssize_t isize;
12398 Py_ssize_t osize, squote, dquote, i, o;
12399 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012400 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012402
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012404 return NULL;
12405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012406 isize = PyUnicode_GET_LENGTH(unicode);
12407 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409 /* Compute length of output, quote characters, and
12410 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012411 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412 max = 127;
12413 squote = dquote = 0;
12414 ikind = PyUnicode_KIND(unicode);
12415 for (i = 0; i < isize; i++) {
12416 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012417 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012419 case '\'': squote++; break;
12420 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012421 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012422 incr = 2;
12423 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 default:
12425 /* Fast-path ASCII */
12426 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012427 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012428 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012429 ;
12430 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012433 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012435 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012437 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012438 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012439 if (osize > PY_SSIZE_T_MAX - incr) {
12440 PyErr_SetString(PyExc_OverflowError,
12441 "string is too long to generate repr");
12442 return NULL;
12443 }
12444 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 }
12446
12447 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012448 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012450 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 if (dquote)
12452 /* Both squote and dquote present. Use squote,
12453 and escape them */
12454 osize += squote;
12455 else
12456 quote = '"';
12457 }
Victor Stinner55c08782013-04-14 18:45:39 +020012458 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459
12460 repr = PyUnicode_New(osize, max);
12461 if (repr == NULL)
12462 return NULL;
12463 okind = PyUnicode_KIND(repr);
12464 odata = PyUnicode_DATA(repr);
12465
12466 PyUnicode_WRITE(okind, odata, 0, quote);
12467 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012468 if (unchanged) {
12469 _PyUnicode_FastCopyCharacters(repr, 1,
12470 unicode, 0,
12471 isize);
12472 }
12473 else {
12474 for (i = 0, o = 1; i < isize; i++) {
12475 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476
Victor Stinner55c08782013-04-14 18:45:39 +020012477 /* Escape quotes and backslashes */
12478 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012479 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012481 continue;
12482 }
12483
12484 /* Map special whitespace to '\t', \n', '\r' */
12485 if (ch == '\t') {
12486 PyUnicode_WRITE(okind, odata, o++, '\\');
12487 PyUnicode_WRITE(okind, odata, o++, 't');
12488 }
12489 else if (ch == '\n') {
12490 PyUnicode_WRITE(okind, odata, o++, '\\');
12491 PyUnicode_WRITE(okind, odata, o++, 'n');
12492 }
12493 else if (ch == '\r') {
12494 PyUnicode_WRITE(okind, odata, o++, '\\');
12495 PyUnicode_WRITE(okind, odata, o++, 'r');
12496 }
12497
12498 /* Map non-printable US ASCII to '\xhh' */
12499 else if (ch < ' ' || ch == 0x7F) {
12500 PyUnicode_WRITE(okind, odata, o++, '\\');
12501 PyUnicode_WRITE(okind, odata, o++, 'x');
12502 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12503 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12504 }
12505
12506 /* Copy ASCII characters as-is */
12507 else if (ch < 0x7F) {
12508 PyUnicode_WRITE(okind, odata, o++, ch);
12509 }
12510
12511 /* Non-ASCII characters */
12512 else {
12513 /* Map Unicode whitespace and control characters
12514 (categories Z* and C* except ASCII space)
12515 */
12516 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12517 PyUnicode_WRITE(okind, odata, o++, '\\');
12518 /* Map 8-bit characters to '\xhh' */
12519 if (ch <= 0xff) {
12520 PyUnicode_WRITE(okind, odata, o++, 'x');
12521 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12522 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12523 }
12524 /* Map 16-bit characters to '\uxxxx' */
12525 else if (ch <= 0xffff) {
12526 PyUnicode_WRITE(okind, odata, o++, 'u');
12527 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12528 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12529 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12530 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12531 }
12532 /* Map 21-bit characters to '\U00xxxxxx' */
12533 else {
12534 PyUnicode_WRITE(okind, odata, o++, 'U');
12535 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12536 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12537 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12538 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12539 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12540 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12541 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12542 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12543 }
12544 }
12545 /* Copy characters as-is */
12546 else {
12547 PyUnicode_WRITE(okind, odata, o++, ch);
12548 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012549 }
12550 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012553 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012554 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555}
12556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012557PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012558 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559\n\
12560Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012561such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562arguments start and end are interpreted as in slice notation.\n\
12563\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012564Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565
12566static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012569 /* initialize variables to prevent gcc warning */
12570 PyObject *substring = NULL;
12571 Py_ssize_t start = 0;
12572 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012573 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574
Jesus Ceaac451502011-04-20 17:09:23 +020012575 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12576 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012577 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578
Christian Heimesea71a522013-06-29 21:17:34 +020012579 if (PyUnicode_READY(self) == -1) {
12580 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012582 }
12583 if (PyUnicode_READY(substring) == -1) {
12584 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587
Victor Stinner7931d9a2011-11-04 00:22:48 +010012588 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589
12590 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 if (result == -2)
12593 return NULL;
12594
Christian Heimes217cfd12007-12-02 14:31:20 +000012595 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596}
12597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012598PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012601Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602
12603static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012606 /* initialize variables to prevent gcc warning */
12607 PyObject *substring = NULL;
12608 Py_ssize_t start = 0;
12609 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012610 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611
Jesus Ceaac451502011-04-20 17:09:23 +020012612 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12613 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012614 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615
Christian Heimesea71a522013-06-29 21:17:34 +020012616 if (PyUnicode_READY(self) == -1) {
12617 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012619 }
12620 if (PyUnicode_READY(substring) == -1) {
12621 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624
Victor Stinner7931d9a2011-11-04 00:22:48 +010012625 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626
12627 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629 if (result == -2)
12630 return NULL;
12631
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632 if (result < 0) {
12633 PyErr_SetString(PyExc_ValueError, "substring not found");
12634 return NULL;
12635 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636
Christian Heimes217cfd12007-12-02 14:31:20 +000012637 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638}
12639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012640PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012641 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012643Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012644done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645
12646static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012647unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012649 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 Py_UCS4 fillchar = ' ';
12651
Victor Stinnere9a29352011-10-01 02:14:59 +020012652 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012654
Benjamin Petersonbac79492012-01-14 13:34:47 -050012655 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656 return NULL;
12657
Victor Stinnerc4b49542011-12-11 22:44:26 +010012658 if (PyUnicode_GET_LENGTH(self) >= width)
12659 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660
Victor Stinnerc4b49542011-12-11 22:44:26 +010012661 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662}
12663
Alexander Belopolsky40018472011-02-26 01:02:56 +000012664PyObject *
12665PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666{
12667 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012668
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669 s = PyUnicode_FromObject(s);
12670 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012671 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012672 if (sep != NULL) {
12673 sep = PyUnicode_FromObject(sep);
12674 if (sep == NULL) {
12675 Py_DECREF(s);
12676 return NULL;
12677 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678 }
12679
Victor Stinner9310abb2011-10-05 00:59:23 +020012680 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681
12682 Py_DECREF(s);
12683 Py_XDECREF(sep);
12684 return result;
12685}
12686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012687PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012688 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689\n\
12690Return a list of the words in S, using sep as the\n\
12691delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012692splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012693whitespace string is a separator and empty strings are\n\
12694removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695
12696static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012697unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012699 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012701 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012703 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12704 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705 return NULL;
12706
12707 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012708 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012710 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012712 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713}
12714
Thomas Wouters477c8d52006-05-27 19:21:47 +000012715PyObject *
12716PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12717{
12718 PyObject* str_obj;
12719 PyObject* sep_obj;
12720 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012721 int kind1, kind2;
12722 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012724
12725 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012726 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012727 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012728 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012729 if (!sep_obj) {
12730 Py_DECREF(str_obj);
12731 return NULL;
12732 }
12733 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12734 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012735 Py_DECREF(str_obj);
12736 return NULL;
12737 }
12738
Victor Stinner14f8f022011-10-05 20:58:25 +020012739 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012741 len1 = PyUnicode_GET_LENGTH(str_obj);
12742 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012743 if (kind1 < kind2 || len1 < len2) {
12744 _Py_INCREF_UNICODE_EMPTY();
12745 if (!unicode_empty)
12746 out = NULL;
12747 else {
12748 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12749 Py_DECREF(unicode_empty);
12750 }
12751 Py_DECREF(sep_obj);
12752 Py_DECREF(str_obj);
12753 return out;
12754 }
12755 buf1 = PyUnicode_DATA(str_obj);
12756 buf2 = PyUnicode_DATA(sep_obj);
12757 if (kind2 != kind1) {
12758 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12759 if (!buf2)
12760 goto onError;
12761 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012763 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012765 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12766 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12767 else
12768 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012769 break;
12770 case PyUnicode_2BYTE_KIND:
12771 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12772 break;
12773 case PyUnicode_4BYTE_KIND:
12774 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12775 break;
12776 default:
12777 assert(0);
12778 out = 0;
12779 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012780
12781 Py_DECREF(sep_obj);
12782 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012783 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012785
12786 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012787 onError:
12788 Py_DECREF(sep_obj);
12789 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012790 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791 PyMem_Free(buf2);
12792 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012793}
12794
12795
12796PyObject *
12797PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12798{
12799 PyObject* str_obj;
12800 PyObject* sep_obj;
12801 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012802 int kind1, kind2;
12803 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012804 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012805
12806 str_obj = PyUnicode_FromObject(str_in);
12807 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012809 sep_obj = PyUnicode_FromObject(sep_in);
12810 if (!sep_obj) {
12811 Py_DECREF(str_obj);
12812 return NULL;
12813 }
12814
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012815 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012816 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012817 len1 = PyUnicode_GET_LENGTH(str_obj);
12818 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012819 if (kind1 < kind2 || len1 < len2) {
12820 _Py_INCREF_UNICODE_EMPTY();
12821 if (!unicode_empty)
12822 out = NULL;
12823 else {
12824 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12825 Py_DECREF(unicode_empty);
12826 }
12827 Py_DECREF(sep_obj);
12828 Py_DECREF(str_obj);
12829 return out;
12830 }
12831 buf1 = PyUnicode_DATA(str_obj);
12832 buf2 = PyUnicode_DATA(sep_obj);
12833 if (kind2 != kind1) {
12834 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12835 if (!buf2)
12836 goto onError;
12837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012839 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012840 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012841 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12842 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12843 else
12844 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 break;
12846 case PyUnicode_2BYTE_KIND:
12847 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12848 break;
12849 case PyUnicode_4BYTE_KIND:
12850 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12851 break;
12852 default:
12853 assert(0);
12854 out = 0;
12855 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856
12857 Py_DECREF(sep_obj);
12858 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012859 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012860 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012861
12862 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012863 onError:
12864 Py_DECREF(sep_obj);
12865 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012866 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 PyMem_Free(buf2);
12868 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012869}
12870
12871PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012872 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012873\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012874Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012875the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012876found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012877
12878static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012879unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012880{
Victor Stinner9310abb2011-10-05 00:59:23 +020012881 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012882}
12883
12884PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012885 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012886\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012887Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012888the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012889separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012890
12891static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012892unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012893{
Victor Stinner9310abb2011-10-05 00:59:23 +020012894 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012895}
12896
Alexander Belopolsky40018472011-02-26 01:02:56 +000012897PyObject *
12898PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012899{
12900 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012901
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012902 s = PyUnicode_FromObject(s);
12903 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012904 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012905 if (sep != NULL) {
12906 sep = PyUnicode_FromObject(sep);
12907 if (sep == NULL) {
12908 Py_DECREF(s);
12909 return NULL;
12910 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012911 }
12912
Victor Stinner9310abb2011-10-05 00:59:23 +020012913 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012914
12915 Py_DECREF(s);
12916 Py_XDECREF(sep);
12917 return result;
12918}
12919
12920PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012921 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012922\n\
12923Return a list of the words in S, using sep as the\n\
12924delimiter string, starting at the end of the string and\n\
12925working to the front. If maxsplit is given, at most maxsplit\n\
12926splits are done. If sep is not specified, any whitespace string\n\
12927is a separator.");
12928
12929static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012930unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012931{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012932 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012933 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012934 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012935
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012936 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12937 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012938 return NULL;
12939
12940 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012941 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012942 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012943 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012944 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012945 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012946}
12947
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012948PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012949 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950\n\
12951Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012952Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012953is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954
12955static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012956unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012957{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012958 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012959 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012960
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012961 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12962 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012963 return NULL;
12964
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012965 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012966}
12967
12968static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012969PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012970{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012971 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012972}
12973
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012974PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012975 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012976\n\
12977Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012978and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979
12980static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012981unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012982{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012983 if (PyUnicode_READY(self) == -1)
12984 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012985 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012986}
12987
Larry Hastings61272b72014-01-07 12:41:53 -080012988/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012989
Larry Hastings31826802013-10-19 00:09:25 -070012990@staticmethod
12991str.maketrans as unicode_maketrans
12992
12993 x: object
12994
12995 y: unicode=NULL
12996
12997 z: unicode=NULL
12998
12999 /
13000
13001Return a translation table usable for str.translate().
13002
13003If there is only one argument, it must be a dictionary mapping Unicode
13004ordinals (integers) or characters to Unicode ordinals, strings or None.
13005Character keys will be then converted to ordinals.
13006If there are two arguments, they must be strings of equal length, and
13007in the resulting dictionary, each character in x will be mapped to the
13008character at the same position in y. If there is a third argument, it
13009must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013010[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013011
Larry Hastings31826802013-10-19 00:09:25 -070013012static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013013unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013014/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013015{
Georg Brandlceee0772007-11-27 23:48:05 +000013016 PyObject *new = NULL, *key, *value;
13017 Py_ssize_t i = 0;
13018 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013019
Georg Brandlceee0772007-11-27 23:48:05 +000013020 new = PyDict_New();
13021 if (!new)
13022 return NULL;
13023 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013024 int x_kind, y_kind, z_kind;
13025 void *x_data, *y_data, *z_data;
13026
Georg Brandlceee0772007-11-27 23:48:05 +000013027 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013028 if (!PyUnicode_Check(x)) {
13029 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13030 "be a string if there is a second argument");
13031 goto err;
13032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013033 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013034 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13035 "arguments must have equal length");
13036 goto err;
13037 }
13038 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 x_kind = PyUnicode_KIND(x);
13040 y_kind = PyUnicode_KIND(y);
13041 x_data = PyUnicode_DATA(x);
13042 y_data = PyUnicode_DATA(y);
13043 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13044 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013045 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013046 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013047 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013048 if (!value) {
13049 Py_DECREF(key);
13050 goto err;
13051 }
Georg Brandlceee0772007-11-27 23:48:05 +000013052 res = PyDict_SetItem(new, key, value);
13053 Py_DECREF(key);
13054 Py_DECREF(value);
13055 if (res < 0)
13056 goto err;
13057 }
13058 /* create entries for deleting chars in z */
13059 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013060 z_kind = PyUnicode_KIND(z);
13061 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013062 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013063 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013064 if (!key)
13065 goto err;
13066 res = PyDict_SetItem(new, key, Py_None);
13067 Py_DECREF(key);
13068 if (res < 0)
13069 goto err;
13070 }
13071 }
13072 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013073 int kind;
13074 void *data;
13075
Georg Brandlceee0772007-11-27 23:48:05 +000013076 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013077 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013078 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13079 "to maketrans it must be a dict");
13080 goto err;
13081 }
13082 /* copy entries into the new dict, converting string keys to int keys */
13083 while (PyDict_Next(x, &i, &key, &value)) {
13084 if (PyUnicode_Check(key)) {
13085 /* convert string keys to integer keys */
13086 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013087 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013088 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13089 "table must be of length 1");
13090 goto err;
13091 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 kind = PyUnicode_KIND(key);
13093 data = PyUnicode_DATA(key);
13094 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013095 if (!newkey)
13096 goto err;
13097 res = PyDict_SetItem(new, newkey, value);
13098 Py_DECREF(newkey);
13099 if (res < 0)
13100 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013101 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013102 /* just keep integer keys */
13103 if (PyDict_SetItem(new, key, value) < 0)
13104 goto err;
13105 } else {
13106 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13107 "be strings or integers");
13108 goto err;
13109 }
13110 }
13111 }
13112 return new;
13113 err:
13114 Py_DECREF(new);
13115 return NULL;
13116}
13117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013118PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013121Return a copy of the string S in which each character has been mapped\n\
13122through the given translation table. The table must implement\n\
13123lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13124mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13125this operation raises LookupError, the character is left untouched.\n\
13126Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127
13128static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013129unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013131 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132}
13133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013134PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013135 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013137Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138
13139static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013140unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013142 if (PyUnicode_READY(self) == -1)
13143 return NULL;
13144 if (PyUnicode_IS_ASCII(self))
13145 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013146 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147}
13148
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013149PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013150 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013152Pad a numeric string S with zeros on the left, to fill a field\n\
13153of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154
13155static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013156unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013158 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013159 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013160 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013161 int kind;
13162 void *data;
13163 Py_UCS4 chr;
13164
Martin v. Löwis18e16552006-02-15 17:27:45 +000013165 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166 return NULL;
13167
Benjamin Petersonbac79492012-01-14 13:34:47 -050013168 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013169 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170
Victor Stinnerc4b49542011-12-11 22:44:26 +010013171 if (PyUnicode_GET_LENGTH(self) >= width)
13172 return unicode_result_unchanged(self);
13173
13174 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175
13176 u = pad(self, fill, 0, '0');
13177
Walter Dörwald068325e2002-04-15 13:36:47 +000013178 if (u == NULL)
13179 return NULL;
13180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013181 kind = PyUnicode_KIND(u);
13182 data = PyUnicode_DATA(u);
13183 chr = PyUnicode_READ(kind, data, fill);
13184
13185 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013187 PyUnicode_WRITE(kind, data, 0, chr);
13188 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189 }
13190
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013191 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013192 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194
13195#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013196static PyObject *
13197unicode__decimal2ascii(PyObject *self)
13198{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013199 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013200}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201#endif
13202
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013203PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013204 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013206Return True if S starts with the specified prefix, False otherwise.\n\
13207With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013208With optional end, stop comparing S at that position.\n\
13209prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210
13211static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013212unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013215 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013216 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013217 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013218 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013219 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220
Jesus Ceaac451502011-04-20 17:09:23 +020013221 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013222 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223 if (PyTuple_Check(subobj)) {
13224 Py_ssize_t i;
13225 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013226 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013227 if (substring == NULL)
13228 return NULL;
13229 result = tailmatch(self, substring, start, end, -1);
13230 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013231 if (result == -1)
13232 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013233 if (result) {
13234 Py_RETURN_TRUE;
13235 }
13236 }
13237 /* nothing matched */
13238 Py_RETURN_FALSE;
13239 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013240 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013241 if (substring == NULL) {
13242 if (PyErr_ExceptionMatches(PyExc_TypeError))
13243 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13244 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013246 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013247 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013248 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013249 if (result == -1)
13250 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013251 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252}
13253
13254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013255PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013257\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013258Return True if S ends with the specified suffix, False otherwise.\n\
13259With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013260With optional end, stop comparing S at that position.\n\
13261suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262
13263static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013264unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013265 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013267 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013268 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013269 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013270 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013271 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272
Jesus Ceaac451502011-04-20 17:09:23 +020013273 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013275 if (PyTuple_Check(subobj)) {
13276 Py_ssize_t i;
13277 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013278 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013280 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013281 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013282 result = tailmatch(self, substring, start, end, +1);
13283 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013284 if (result == -1)
13285 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013286 if (result) {
13287 Py_RETURN_TRUE;
13288 }
13289 }
13290 Py_RETURN_FALSE;
13291 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013292 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013293 if (substring == NULL) {
13294 if (PyErr_ExceptionMatches(PyExc_TypeError))
13295 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13296 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013297 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013298 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013299 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013300 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013301 if (result == -1)
13302 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013303 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304}
13305
Victor Stinner202fdca2012-05-07 12:47:02 +020013306Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013307_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013308{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013309 if (!writer->readonly)
13310 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13311 else {
13312 /* Copy-on-write mode: set buffer size to 0 so
13313 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13314 * next write. */
13315 writer->size = 0;
13316 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013317 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13318 writer->data = PyUnicode_DATA(writer->buffer);
13319 writer->kind = PyUnicode_KIND(writer->buffer);
13320}
13321
Victor Stinnerd3f08822012-05-29 12:57:52 +020013322void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013323_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013324{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013325 memset(writer, 0, sizeof(*writer));
13326#ifdef Py_DEBUG
13327 writer->kind = 5; /* invalid kind */
13328#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013329 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013330}
13331
Victor Stinnerd3f08822012-05-29 12:57:52 +020013332int
13333_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13334 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013335{
Victor Stinner6989ba02013-11-18 21:08:39 +010013336#ifdef MS_WINDOWS
13337 /* On Windows, overallocate by 50% is the best factor */
13338# define OVERALLOCATE_FACTOR 2
13339#else
13340 /* On Linux, overallocate by 25% is the best factor */
13341# define OVERALLOCATE_FACTOR 4
13342#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013343 Py_ssize_t newlen;
13344 PyObject *newbuffer;
13345
Victor Stinnerd3f08822012-05-29 12:57:52 +020013346 assert(length > 0);
13347
Victor Stinner202fdca2012-05-07 12:47:02 +020013348 if (length > PY_SSIZE_T_MAX - writer->pos) {
13349 PyErr_NoMemory();
13350 return -1;
13351 }
13352 newlen = writer->pos + length;
13353
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013354 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013355
Victor Stinnerd3f08822012-05-29 12:57:52 +020013356 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013357 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013358 if (writer->overallocate
13359 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13360 /* overallocate to limit the number of realloc() */
13361 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013362 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013363 if (newlen < writer->min_length)
13364 newlen = writer->min_length;
13365
Victor Stinnerd3f08822012-05-29 12:57:52 +020013366 writer->buffer = PyUnicode_New(newlen, maxchar);
13367 if (writer->buffer == NULL)
13368 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013369 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013370 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013371 if (writer->overallocate
13372 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13373 /* overallocate to limit the number of realloc() */
13374 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013375 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013376 if (newlen < writer->min_length)
13377 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013378
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013379 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013380 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013381 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013382 newbuffer = PyUnicode_New(newlen, maxchar);
13383 if (newbuffer == NULL)
13384 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013385 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13386 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013387 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013388 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013389 }
13390 else {
13391 newbuffer = resize_compact(writer->buffer, newlen);
13392 if (newbuffer == NULL)
13393 return -1;
13394 }
13395 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013396 }
13397 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013398 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013399 newbuffer = PyUnicode_New(writer->size, maxchar);
13400 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013401 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013402 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13403 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013404 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013405 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013406 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013407 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013408
13409#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013410}
13411
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013412Py_LOCAL_INLINE(int)
13413_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013414{
13415 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13416 return -1;
13417 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13418 writer->pos++;
13419 return 0;
13420}
13421
13422int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013423_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13424{
13425 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13426}
13427
13428int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013429_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13430{
13431 Py_UCS4 maxchar;
13432 Py_ssize_t len;
13433
13434 if (PyUnicode_READY(str) == -1)
13435 return -1;
13436 len = PyUnicode_GET_LENGTH(str);
13437 if (len == 0)
13438 return 0;
13439 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13440 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013441 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013442 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013443 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013444 Py_INCREF(str);
13445 writer->buffer = str;
13446 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013447 writer->pos += len;
13448 return 0;
13449 }
13450 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13451 return -1;
13452 }
13453 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13454 str, 0, len);
13455 writer->pos += len;
13456 return 0;
13457}
13458
Victor Stinnere215d962012-10-06 23:03:36 +020013459int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013460_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13461 Py_ssize_t start, Py_ssize_t end)
13462{
13463 Py_UCS4 maxchar;
13464 Py_ssize_t len;
13465
13466 if (PyUnicode_READY(str) == -1)
13467 return -1;
13468
13469 assert(0 <= start);
13470 assert(end <= PyUnicode_GET_LENGTH(str));
13471 assert(start <= end);
13472
13473 if (end == 0)
13474 return 0;
13475
13476 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13477 return _PyUnicodeWriter_WriteStr(writer, str);
13478
13479 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13480 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13481 else
13482 maxchar = writer->maxchar;
13483 len = end - start;
13484
13485 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13486 return -1;
13487
13488 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13489 str, start, len);
13490 writer->pos += len;
13491 return 0;
13492}
13493
13494int
Victor Stinner4a587072013-11-19 12:54:53 +010013495_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13496 const char *ascii, Py_ssize_t len)
13497{
13498 if (len == -1)
13499 len = strlen(ascii);
13500
13501 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13502
13503 if (writer->buffer == NULL && !writer->overallocate) {
13504 PyObject *str;
13505
13506 str = _PyUnicode_FromASCII(ascii, len);
13507 if (str == NULL)
13508 return -1;
13509
13510 writer->readonly = 1;
13511 writer->buffer = str;
13512 _PyUnicodeWriter_Update(writer);
13513 writer->pos += len;
13514 return 0;
13515 }
13516
13517 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13518 return -1;
13519
13520 switch (writer->kind)
13521 {
13522 case PyUnicode_1BYTE_KIND:
13523 {
13524 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13525 Py_UCS1 *data = writer->data;
13526
13527 Py_MEMCPY(data + writer->pos, str, len);
13528 break;
13529 }
13530 case PyUnicode_2BYTE_KIND:
13531 {
13532 _PyUnicode_CONVERT_BYTES(
13533 Py_UCS1, Py_UCS2,
13534 ascii, ascii + len,
13535 (Py_UCS2 *)writer->data + writer->pos);
13536 break;
13537 }
13538 case PyUnicode_4BYTE_KIND:
13539 {
13540 _PyUnicode_CONVERT_BYTES(
13541 Py_UCS1, Py_UCS4,
13542 ascii, ascii + len,
13543 (Py_UCS4 *)writer->data + writer->pos);
13544 break;
13545 }
13546 default:
13547 assert(0);
13548 }
13549
13550 writer->pos += len;
13551 return 0;
13552}
13553
13554int
13555_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13556 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013557{
13558 Py_UCS4 maxchar;
13559
13560 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13561 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13562 return -1;
13563 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13564 writer->pos += len;
13565 return 0;
13566}
13567
Victor Stinnerd3f08822012-05-29 12:57:52 +020013568PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013569_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013570{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013571 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013572 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013573 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013574 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013575 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013576 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013577 str = writer->buffer;
13578 writer->buffer = NULL;
13579 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13580 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013581 }
13582 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13583 PyObject *newbuffer;
13584 newbuffer = resize_compact(writer->buffer, writer->pos);
13585 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013586 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013587 return NULL;
13588 }
13589 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013590 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013591 str = writer->buffer;
13592 writer->buffer = NULL;
13593 assert(_PyUnicode_CheckConsistency(str, 1));
13594 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013595}
13596
Victor Stinnerd3f08822012-05-29 12:57:52 +020013597void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013598_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013599{
13600 Py_CLEAR(writer->buffer);
13601}
13602
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013603#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013604
13605PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013606 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013607\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013608Return a formatted version of S, using substitutions from args and kwargs.\n\
13609The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013610
Eric Smith27bbca62010-11-04 17:06:58 +000013611PyDoc_STRVAR(format_map__doc__,
13612 "S.format_map(mapping) -> str\n\
13613\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013614Return a formatted version of S, using substitutions from mapping.\n\
13615The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013616
Eric Smith4a7d76d2008-05-30 18:10:19 +000013617static PyObject *
13618unicode__format__(PyObject* self, PyObject* args)
13619{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013620 PyObject *format_spec;
13621 _PyUnicodeWriter writer;
13622 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013623
13624 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13625 return NULL;
13626
Victor Stinnerd3f08822012-05-29 12:57:52 +020013627 if (PyUnicode_READY(self) == -1)
13628 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013629 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013630 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13631 self, format_spec, 0,
13632 PyUnicode_GET_LENGTH(format_spec));
13633 if (ret == -1) {
13634 _PyUnicodeWriter_Dealloc(&writer);
13635 return NULL;
13636 }
13637 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013638}
13639
Eric Smith8c663262007-08-25 02:26:07 +000013640PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013642\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013643Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013644
13645static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013646unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013647{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013648 Py_ssize_t size;
13649
13650 /* If it's a compact object, account for base structure +
13651 character data. */
13652 if (PyUnicode_IS_COMPACT_ASCII(v))
13653 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13654 else if (PyUnicode_IS_COMPACT(v))
13655 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013656 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013657 else {
13658 /* If it is a two-block object, account for base object, and
13659 for character block if present. */
13660 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013661 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013662 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013663 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013664 }
13665 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013666 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013667 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013668 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013669 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013670 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013671
13672 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013673}
13674
13675PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013677
13678static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013679unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013680{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013681 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013682 if (!copy)
13683 return NULL;
13684 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013685}
13686
Guido van Rossumd57fd912000-03-10 22:53:23 +000013687static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013688 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013689 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013690 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13691 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013692 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13693 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013694 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013695 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13696 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13697 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013698 {"expandtabs", (PyCFunction) unicode_expandtabs,
13699 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013700 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013701 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013702 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13703 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13704 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013705 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013706 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13707 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13708 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013709 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013710 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013711 {"splitlines", (PyCFunction) unicode_splitlines,
13712 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013713 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013714 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13715 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13716 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13717 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13718 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13719 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13720 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13721 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13722 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13723 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13724 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13725 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13726 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13727 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013728 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013729 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013730 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013731 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013732 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013733 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013734 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013735 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013736#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013737 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013738 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013739#endif
13740
Benjamin Peterson14339b62009-01-31 16:36:08 +000013741 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013742 {NULL, NULL}
13743};
13744
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013745static PyObject *
13746unicode_mod(PyObject *v, PyObject *w)
13747{
Brian Curtindfc80e32011-08-10 20:28:54 -050013748 if (!PyUnicode_Check(v))
13749 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013750 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013751}
13752
13753static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013754 0, /*nb_add*/
13755 0, /*nb_subtract*/
13756 0, /*nb_multiply*/
13757 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013758};
13759
Guido van Rossumd57fd912000-03-10 22:53:23 +000013760static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013761 (lenfunc) unicode_length, /* sq_length */
13762 PyUnicode_Concat, /* sq_concat */
13763 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13764 (ssizeargfunc) unicode_getitem, /* sq_item */
13765 0, /* sq_slice */
13766 0, /* sq_ass_item */
13767 0, /* sq_ass_slice */
13768 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013769};
13770
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013771static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013772unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 if (PyUnicode_READY(self) == -1)
13775 return NULL;
13776
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013777 if (PyIndex_Check(item)) {
13778 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013779 if (i == -1 && PyErr_Occurred())
13780 return NULL;
13781 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013782 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013783 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013784 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013785 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013786 PyObject *result;
13787 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013788 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013789 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013791 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013793 return NULL;
13794 }
13795
13796 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013797 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013798 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013799 slicelength == PyUnicode_GET_LENGTH(self)) {
13800 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013801 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013802 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013803 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013804 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013805 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013806 src_kind = PyUnicode_KIND(self);
13807 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013808 if (!PyUnicode_IS_ASCII(self)) {
13809 kind_limit = kind_maxchar_limit(src_kind);
13810 max_char = 0;
13811 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13812 ch = PyUnicode_READ(src_kind, src_data, cur);
13813 if (ch > max_char) {
13814 max_char = ch;
13815 if (max_char >= kind_limit)
13816 break;
13817 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013818 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013819 }
Victor Stinner55c99112011-10-13 01:17:06 +020013820 else
13821 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013822 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013823 if (result == NULL)
13824 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013825 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013826 dest_data = PyUnicode_DATA(result);
13827
13828 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013829 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13830 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013831 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013832 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013833 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013834 } else {
13835 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13836 return NULL;
13837 }
13838}
13839
13840static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013841 (lenfunc)unicode_length, /* mp_length */
13842 (binaryfunc)unicode_subscript, /* mp_subscript */
13843 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013844};
13845
Guido van Rossumd57fd912000-03-10 22:53:23 +000013846
Guido van Rossumd57fd912000-03-10 22:53:23 +000013847/* Helpers for PyUnicode_Format() */
13848
Victor Stinnera47082312012-10-04 02:19:54 +020013849struct unicode_formatter_t {
13850 PyObject *args;
13851 int args_owned;
13852 Py_ssize_t arglen, argidx;
13853 PyObject *dict;
13854
13855 enum PyUnicode_Kind fmtkind;
13856 Py_ssize_t fmtcnt, fmtpos;
13857 void *fmtdata;
13858 PyObject *fmtstr;
13859
13860 _PyUnicodeWriter writer;
13861};
13862
13863struct unicode_format_arg_t {
13864 Py_UCS4 ch;
13865 int flags;
13866 Py_ssize_t width;
13867 int prec;
13868 int sign;
13869};
13870
Guido van Rossumd57fd912000-03-10 22:53:23 +000013871static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013872unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013873{
Victor Stinnera47082312012-10-04 02:19:54 +020013874 Py_ssize_t argidx = ctx->argidx;
13875
13876 if (argidx < ctx->arglen) {
13877 ctx->argidx++;
13878 if (ctx->arglen < 0)
13879 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013880 else
Victor Stinnera47082312012-10-04 02:19:54 +020013881 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013882 }
13883 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013884 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013885 return NULL;
13886}
13887
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013888/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013889
Victor Stinnera47082312012-10-04 02:19:54 +020013890/* Format a float into the writer if the writer is not NULL, or into *p_output
13891 otherwise.
13892
13893 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013894static int
Victor Stinnera47082312012-10-04 02:19:54 +020013895formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13896 PyObject **p_output,
13897 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013898{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013899 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013900 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013901 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013902 int prec;
13903 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013904
Guido van Rossumd57fd912000-03-10 22:53:23 +000013905 x = PyFloat_AsDouble(v);
13906 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013907 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013908
Victor Stinnera47082312012-10-04 02:19:54 +020013909 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013910 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013911 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013912
Victor Stinnera47082312012-10-04 02:19:54 +020013913 if (arg->flags & F_ALT)
13914 dtoa_flags = Py_DTSF_ALT;
13915 else
13916 dtoa_flags = 0;
13917 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013918 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013919 return -1;
13920 len = strlen(p);
13921 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013922 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013923 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013924 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013925 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013926 }
13927 else
13928 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013929 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013930 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931}
13932
Victor Stinnerd0880d52012-04-27 23:40:13 +020013933/* formatlong() emulates the format codes d, u, o, x and X, and
13934 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13935 * Python's regular ints.
13936 * Return value: a new PyUnicodeObject*, or NULL if error.
13937 * The output string is of the form
13938 * "-"? ("0x" | "0X")? digit+
13939 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13940 * set in flags. The case of hex digits will be correct,
13941 * There will be at least prec digits, zero-filled on the left if
13942 * necessary to get that many.
13943 * val object to be converted
13944 * flags bitmask of format flags; only F_ALT is looked at
13945 * prec minimum number of digits; 0-fill on left if needed
13946 * type a character in [duoxX]; u acts the same as d
13947 *
13948 * CAUTION: o, x and X conversions on regular ints can never
13949 * produce a '-' sign, but can for Python's unbounded ints.
13950 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013951PyObject *
13952_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013953{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013954 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013955 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013956 Py_ssize_t i;
13957 int sign; /* 1 if '-', else 0 */
13958 int len; /* number of characters */
13959 Py_ssize_t llen;
13960 int numdigits; /* len == numnondigits + numdigits */
13961 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013962
Victor Stinnerd0880d52012-04-27 23:40:13 +020013963 /* Avoid exceeding SSIZE_T_MAX */
13964 if (prec > INT_MAX-3) {
13965 PyErr_SetString(PyExc_OverflowError,
13966 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013968 }
13969
13970 assert(PyLong_Check(val));
13971
13972 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013973 default:
13974 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013975 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013976 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013977 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013978 /* int and int subclasses should print numerically when a numeric */
13979 /* format code is used (see issue18780) */
13980 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013981 break;
13982 case 'o':
13983 numnondigits = 2;
13984 result = PyNumber_ToBase(val, 8);
13985 break;
13986 case 'x':
13987 case 'X':
13988 numnondigits = 2;
13989 result = PyNumber_ToBase(val, 16);
13990 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013991 }
13992 if (!result)
13993 return NULL;
13994
13995 assert(unicode_modifiable(result));
13996 assert(PyUnicode_IS_READY(result));
13997 assert(PyUnicode_IS_ASCII(result));
13998
13999 /* To modify the string in-place, there can only be one reference. */
14000 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014001 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014002 PyErr_BadInternalCall();
14003 return NULL;
14004 }
14005 buf = PyUnicode_DATA(result);
14006 llen = PyUnicode_GET_LENGTH(result);
14007 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014008 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014009 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014010 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014011 return NULL;
14012 }
14013 len = (int)llen;
14014 sign = buf[0] == '-';
14015 numnondigits += sign;
14016 numdigits = len - numnondigits;
14017 assert(numdigits > 0);
14018
14019 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014020 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014021 (type == 'o' || type == 'x' || type == 'X'))) {
14022 assert(buf[sign] == '0');
14023 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14024 buf[sign+1] == 'o');
14025 numnondigits -= 2;
14026 buf += 2;
14027 len -= 2;
14028 if (sign)
14029 buf[0] = '-';
14030 assert(len == numnondigits + numdigits);
14031 assert(numdigits > 0);
14032 }
14033
14034 /* Fill with leading zeroes to meet minimum width. */
14035 if (prec > numdigits) {
14036 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14037 numnondigits + prec);
14038 char *b1;
14039 if (!r1) {
14040 Py_DECREF(result);
14041 return NULL;
14042 }
14043 b1 = PyBytes_AS_STRING(r1);
14044 for (i = 0; i < numnondigits; ++i)
14045 *b1++ = *buf++;
14046 for (i = 0; i < prec - numdigits; i++)
14047 *b1++ = '0';
14048 for (i = 0; i < numdigits; i++)
14049 *b1++ = *buf++;
14050 *b1 = '\0';
14051 Py_DECREF(result);
14052 result = r1;
14053 buf = PyBytes_AS_STRING(result);
14054 len = numnondigits + prec;
14055 }
14056
14057 /* Fix up case for hex conversions. */
14058 if (type == 'X') {
14059 /* Need to convert all lower case letters to upper case.
14060 and need to convert 0x to 0X (and -0x to -0X). */
14061 for (i = 0; i < len; i++)
14062 if (buf[i] >= 'a' && buf[i] <= 'x')
14063 buf[i] -= 'a'-'A';
14064 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014065 if (!PyUnicode_Check(result)
14066 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014067 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014068 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014069 Py_DECREF(result);
14070 result = unicode;
14071 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014072 else if (len != PyUnicode_GET_LENGTH(result)) {
14073 if (PyUnicode_Resize(&result, len) < 0)
14074 Py_CLEAR(result);
14075 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014076 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014077}
14078
Ethan Furmandf3ed242014-01-05 06:50:30 -080014079/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014080 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014081 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014082 * -1 and raise an exception on error */
14083static int
Victor Stinnera47082312012-10-04 02:19:54 +020014084mainformatlong(PyObject *v,
14085 struct unicode_format_arg_t *arg,
14086 PyObject **p_output,
14087 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014088{
14089 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014090 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014091
14092 if (!PyNumber_Check(v))
14093 goto wrongtype;
14094
Ethan Furman9ab74802014-03-21 06:38:46 -070014095 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014096 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014097 if (type == 'o' || type == 'x' || type == 'X') {
14098 iobj = PyNumber_Index(v);
14099 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014100 if (PyErr_ExceptionMatches(PyExc_TypeError))
14101 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014102 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014103 }
14104 }
14105 else {
14106 iobj = PyNumber_Long(v);
14107 if (iobj == NULL ) {
14108 if (PyErr_ExceptionMatches(PyExc_TypeError))
14109 goto wrongtype;
14110 return -1;
14111 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014112 }
14113 assert(PyLong_Check(iobj));
14114 }
14115 else {
14116 iobj = v;
14117 Py_INCREF(iobj);
14118 }
14119
14120 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014121 && arg->width == -1 && arg->prec == -1
14122 && !(arg->flags & (F_SIGN | F_BLANK))
14123 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014124 {
14125 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014126 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014127 int base;
14128
Victor Stinnera47082312012-10-04 02:19:54 +020014129 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014130 {
14131 default:
14132 assert(0 && "'type' not in [diuoxX]");
14133 case 'd':
14134 case 'i':
14135 case 'u':
14136 base = 10;
14137 break;
14138 case 'o':
14139 base = 8;
14140 break;
14141 case 'x':
14142 case 'X':
14143 base = 16;
14144 break;
14145 }
14146
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014147 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14148 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014149 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014150 }
14151 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014152 return 1;
14153 }
14154
Ethan Furmanb95b5612015-01-23 20:05:18 -080014155 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014156 Py_DECREF(iobj);
14157 if (res == NULL)
14158 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014159 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014160 return 0;
14161
14162wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014163 switch(type)
14164 {
14165 case 'o':
14166 case 'x':
14167 case 'X':
14168 PyErr_Format(PyExc_TypeError,
14169 "%%%c format: an integer is required, "
14170 "not %.200s",
14171 type, Py_TYPE(v)->tp_name);
14172 break;
14173 default:
14174 PyErr_Format(PyExc_TypeError,
14175 "%%%c format: a number is required, "
14176 "not %.200s",
14177 type, Py_TYPE(v)->tp_name);
14178 break;
14179 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014180 return -1;
14181}
14182
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014183static Py_UCS4
14184formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014185{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014186 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014187 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014188 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014189 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014190 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014191 goto onError;
14192 }
14193 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014194 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014195 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014196 /* make sure number is a type of integer */
14197 if (!PyLong_Check(v)) {
14198 iobj = PyNumber_Index(v);
14199 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014200 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014201 }
14202 v = iobj;
14203 Py_DECREF(iobj);
14204 }
14205 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014206 x = PyLong_AsLong(v);
14207 if (x == -1 && PyErr_Occurred())
14208 goto onError;
14209
Victor Stinner8faf8212011-12-08 22:14:11 +010014210 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014211 PyErr_SetString(PyExc_OverflowError,
14212 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014213 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014214 }
14215
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014216 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014217 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014218
Benjamin Peterson29060642009-01-31 22:14:21 +000014219 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014220 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014221 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014222 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014223}
14224
Victor Stinnera47082312012-10-04 02:19:54 +020014225/* Parse options of an argument: flags, width, precision.
14226 Handle also "%(name)" syntax.
14227
14228 Return 0 if the argument has been formatted into arg->str.
14229 Return 1 if the argument has been written into ctx->writer,
14230 Raise an exception and return -1 on error. */
14231static int
14232unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14233 struct unicode_format_arg_t *arg)
14234{
14235#define FORMAT_READ(ctx) \
14236 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14237
14238 PyObject *v;
14239
Victor Stinnera47082312012-10-04 02:19:54 +020014240 if (arg->ch == '(') {
14241 /* Get argument value from a dictionary. Example: "%(name)s". */
14242 Py_ssize_t keystart;
14243 Py_ssize_t keylen;
14244 PyObject *key;
14245 int pcount = 1;
14246
14247 if (ctx->dict == NULL) {
14248 PyErr_SetString(PyExc_TypeError,
14249 "format requires a mapping");
14250 return -1;
14251 }
14252 ++ctx->fmtpos;
14253 --ctx->fmtcnt;
14254 keystart = ctx->fmtpos;
14255 /* Skip over balanced parentheses */
14256 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14257 arg->ch = FORMAT_READ(ctx);
14258 if (arg->ch == ')')
14259 --pcount;
14260 else if (arg->ch == '(')
14261 ++pcount;
14262 ctx->fmtpos++;
14263 }
14264 keylen = ctx->fmtpos - keystart - 1;
14265 if (ctx->fmtcnt < 0 || pcount > 0) {
14266 PyErr_SetString(PyExc_ValueError,
14267 "incomplete format key");
14268 return -1;
14269 }
14270 key = PyUnicode_Substring(ctx->fmtstr,
14271 keystart, keystart + keylen);
14272 if (key == NULL)
14273 return -1;
14274 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014275 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014276 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014277 }
14278 ctx->args = PyObject_GetItem(ctx->dict, key);
14279 Py_DECREF(key);
14280 if (ctx->args == NULL)
14281 return -1;
14282 ctx->args_owned = 1;
14283 ctx->arglen = -1;
14284 ctx->argidx = -2;
14285 }
14286
14287 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014288 while (--ctx->fmtcnt >= 0) {
14289 arg->ch = FORMAT_READ(ctx);
14290 ctx->fmtpos++;
14291 switch (arg->ch) {
14292 case '-': arg->flags |= F_LJUST; continue;
14293 case '+': arg->flags |= F_SIGN; continue;
14294 case ' ': arg->flags |= F_BLANK; continue;
14295 case '#': arg->flags |= F_ALT; continue;
14296 case '0': arg->flags |= F_ZERO; continue;
14297 }
14298 break;
14299 }
14300
14301 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014302 if (arg->ch == '*') {
14303 v = unicode_format_getnextarg(ctx);
14304 if (v == NULL)
14305 return -1;
14306 if (!PyLong_Check(v)) {
14307 PyErr_SetString(PyExc_TypeError,
14308 "* wants int");
14309 return -1;
14310 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014311 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014312 if (arg->width == -1 && PyErr_Occurred())
14313 return -1;
14314 if (arg->width < 0) {
14315 arg->flags |= F_LJUST;
14316 arg->width = -arg->width;
14317 }
14318 if (--ctx->fmtcnt >= 0) {
14319 arg->ch = FORMAT_READ(ctx);
14320 ctx->fmtpos++;
14321 }
14322 }
14323 else if (arg->ch >= '0' && arg->ch <= '9') {
14324 arg->width = arg->ch - '0';
14325 while (--ctx->fmtcnt >= 0) {
14326 arg->ch = FORMAT_READ(ctx);
14327 ctx->fmtpos++;
14328 if (arg->ch < '0' || arg->ch > '9')
14329 break;
14330 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14331 mixing signed and unsigned comparison. Since arg->ch is between
14332 '0' and '9', casting to int is safe. */
14333 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14334 PyErr_SetString(PyExc_ValueError,
14335 "width too big");
14336 return -1;
14337 }
14338 arg->width = arg->width*10 + (arg->ch - '0');
14339 }
14340 }
14341
14342 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014343 if (arg->ch == '.') {
14344 arg->prec = 0;
14345 if (--ctx->fmtcnt >= 0) {
14346 arg->ch = FORMAT_READ(ctx);
14347 ctx->fmtpos++;
14348 }
14349 if (arg->ch == '*') {
14350 v = unicode_format_getnextarg(ctx);
14351 if (v == NULL)
14352 return -1;
14353 if (!PyLong_Check(v)) {
14354 PyErr_SetString(PyExc_TypeError,
14355 "* wants int");
14356 return -1;
14357 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014358 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014359 if (arg->prec == -1 && PyErr_Occurred())
14360 return -1;
14361 if (arg->prec < 0)
14362 arg->prec = 0;
14363 if (--ctx->fmtcnt >= 0) {
14364 arg->ch = FORMAT_READ(ctx);
14365 ctx->fmtpos++;
14366 }
14367 }
14368 else if (arg->ch >= '0' && arg->ch <= '9') {
14369 arg->prec = arg->ch - '0';
14370 while (--ctx->fmtcnt >= 0) {
14371 arg->ch = FORMAT_READ(ctx);
14372 ctx->fmtpos++;
14373 if (arg->ch < '0' || arg->ch > '9')
14374 break;
14375 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14376 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014377 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014378 return -1;
14379 }
14380 arg->prec = arg->prec*10 + (arg->ch - '0');
14381 }
14382 }
14383 }
14384
14385 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14386 if (ctx->fmtcnt >= 0) {
14387 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14388 if (--ctx->fmtcnt >= 0) {
14389 arg->ch = FORMAT_READ(ctx);
14390 ctx->fmtpos++;
14391 }
14392 }
14393 }
14394 if (ctx->fmtcnt < 0) {
14395 PyErr_SetString(PyExc_ValueError,
14396 "incomplete format");
14397 return -1;
14398 }
14399 return 0;
14400
14401#undef FORMAT_READ
14402}
14403
14404/* Format one argument. Supported conversion specifiers:
14405
14406 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014407 - "i", "d", "u": int or float
14408 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014409 - "e", "E", "f", "F", "g", "G": float
14410 - "c": int or str (1 character)
14411
Victor Stinner8dbd4212012-12-04 09:30:24 +010014412 When possible, the output is written directly into the Unicode writer
14413 (ctx->writer). A string is created when padding is required.
14414
Victor Stinnera47082312012-10-04 02:19:54 +020014415 Return 0 if the argument has been formatted into *p_str,
14416 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014417 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014418static int
14419unicode_format_arg_format(struct unicode_formatter_t *ctx,
14420 struct unicode_format_arg_t *arg,
14421 PyObject **p_str)
14422{
14423 PyObject *v;
14424 _PyUnicodeWriter *writer = &ctx->writer;
14425
14426 if (ctx->fmtcnt == 0)
14427 ctx->writer.overallocate = 0;
14428
14429 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014430 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014431 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014432 return 1;
14433 }
14434
14435 v = unicode_format_getnextarg(ctx);
14436 if (v == NULL)
14437 return -1;
14438
Victor Stinnera47082312012-10-04 02:19:54 +020014439
14440 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014441 case 's':
14442 case 'r':
14443 case 'a':
14444 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14445 /* Fast path */
14446 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14447 return -1;
14448 return 1;
14449 }
14450
14451 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14452 *p_str = v;
14453 Py_INCREF(*p_str);
14454 }
14455 else {
14456 if (arg->ch == 's')
14457 *p_str = PyObject_Str(v);
14458 else if (arg->ch == 'r')
14459 *p_str = PyObject_Repr(v);
14460 else
14461 *p_str = PyObject_ASCII(v);
14462 }
14463 break;
14464
14465 case 'i':
14466 case 'd':
14467 case 'u':
14468 case 'o':
14469 case 'x':
14470 case 'X':
14471 {
14472 int ret = mainformatlong(v, arg, p_str, writer);
14473 if (ret != 0)
14474 return ret;
14475 arg->sign = 1;
14476 break;
14477 }
14478
14479 case 'e':
14480 case 'E':
14481 case 'f':
14482 case 'F':
14483 case 'g':
14484 case 'G':
14485 if (arg->width == -1 && arg->prec == -1
14486 && !(arg->flags & (F_SIGN | F_BLANK)))
14487 {
14488 /* Fast path */
14489 if (formatfloat(v, arg, NULL, writer) == -1)
14490 return -1;
14491 return 1;
14492 }
14493
14494 arg->sign = 1;
14495 if (formatfloat(v, arg, p_str, NULL) == -1)
14496 return -1;
14497 break;
14498
14499 case 'c':
14500 {
14501 Py_UCS4 ch = formatchar(v);
14502 if (ch == (Py_UCS4) -1)
14503 return -1;
14504 if (arg->width == -1 && arg->prec == -1) {
14505 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014506 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014507 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014508 return 1;
14509 }
14510 *p_str = PyUnicode_FromOrdinal(ch);
14511 break;
14512 }
14513
14514 default:
14515 PyErr_Format(PyExc_ValueError,
14516 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014517 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014518 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14519 (int)arg->ch,
14520 ctx->fmtpos - 1);
14521 return -1;
14522 }
14523 if (*p_str == NULL)
14524 return -1;
14525 assert (PyUnicode_Check(*p_str));
14526 return 0;
14527}
14528
14529static int
14530unicode_format_arg_output(struct unicode_formatter_t *ctx,
14531 struct unicode_format_arg_t *arg,
14532 PyObject *str)
14533{
14534 Py_ssize_t len;
14535 enum PyUnicode_Kind kind;
14536 void *pbuf;
14537 Py_ssize_t pindex;
14538 Py_UCS4 signchar;
14539 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014540 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014541 Py_ssize_t sublen;
14542 _PyUnicodeWriter *writer = &ctx->writer;
14543 Py_UCS4 fill;
14544
14545 fill = ' ';
14546 if (arg->sign && arg->flags & F_ZERO)
14547 fill = '0';
14548
14549 if (PyUnicode_READY(str) == -1)
14550 return -1;
14551
14552 len = PyUnicode_GET_LENGTH(str);
14553 if ((arg->width == -1 || arg->width <= len)
14554 && (arg->prec == -1 || arg->prec >= len)
14555 && !(arg->flags & (F_SIGN | F_BLANK)))
14556 {
14557 /* Fast path */
14558 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14559 return -1;
14560 return 0;
14561 }
14562
14563 /* Truncate the string for "s", "r" and "a" formats
14564 if the precision is set */
14565 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14566 if (arg->prec >= 0 && len > arg->prec)
14567 len = arg->prec;
14568 }
14569
14570 /* Adjust sign and width */
14571 kind = PyUnicode_KIND(str);
14572 pbuf = PyUnicode_DATA(str);
14573 pindex = 0;
14574 signchar = '\0';
14575 if (arg->sign) {
14576 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14577 if (ch == '-' || ch == '+') {
14578 signchar = ch;
14579 len--;
14580 pindex++;
14581 }
14582 else if (arg->flags & F_SIGN)
14583 signchar = '+';
14584 else if (arg->flags & F_BLANK)
14585 signchar = ' ';
14586 else
14587 arg->sign = 0;
14588 }
14589 if (arg->width < len)
14590 arg->width = len;
14591
14592 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014593 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014594 if (!(arg->flags & F_LJUST)) {
14595 if (arg->sign) {
14596 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014597 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014598 }
14599 else {
14600 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014601 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014602 }
14603 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014604 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14605 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014606 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014607 }
14608
Victor Stinnera47082312012-10-04 02:19:54 +020014609 buflen = arg->width;
14610 if (arg->sign && len == arg->width)
14611 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014612 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014613 return -1;
14614
14615 /* Write the sign if needed */
14616 if (arg->sign) {
14617 if (fill != ' ') {
14618 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14619 writer->pos += 1;
14620 }
14621 if (arg->width > len)
14622 arg->width--;
14623 }
14624
14625 /* Write the numeric prefix for "x", "X" and "o" formats
14626 if the alternate form is used.
14627 For example, write "0x" for the "%#x" format. */
14628 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14629 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14630 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14631 if (fill != ' ') {
14632 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14633 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14634 writer->pos += 2;
14635 pindex += 2;
14636 }
14637 arg->width -= 2;
14638 if (arg->width < 0)
14639 arg->width = 0;
14640 len -= 2;
14641 }
14642
14643 /* Pad left with the fill character if needed */
14644 if (arg->width > len && !(arg->flags & F_LJUST)) {
14645 sublen = arg->width - len;
14646 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14647 writer->pos += sublen;
14648 arg->width = len;
14649 }
14650
14651 /* If padding with spaces: write sign if needed and/or numeric prefix if
14652 the alternate form is used */
14653 if (fill == ' ') {
14654 if (arg->sign) {
14655 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14656 writer->pos += 1;
14657 }
14658 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14659 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14660 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14661 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14662 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14663 writer->pos += 2;
14664 pindex += 2;
14665 }
14666 }
14667
14668 /* Write characters */
14669 if (len) {
14670 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14671 str, pindex, len);
14672 writer->pos += len;
14673 }
14674
14675 /* Pad right with the fill character if needed */
14676 if (arg->width > len) {
14677 sublen = arg->width - len;
14678 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14679 writer->pos += sublen;
14680 }
14681 return 0;
14682}
14683
14684/* Helper of PyUnicode_Format(): format one arg.
14685 Return 0 on success, raise an exception and return -1 on error. */
14686static int
14687unicode_format_arg(struct unicode_formatter_t *ctx)
14688{
14689 struct unicode_format_arg_t arg;
14690 PyObject *str;
14691 int ret;
14692
Victor Stinner8dbd4212012-12-04 09:30:24 +010014693 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14694 arg.flags = 0;
14695 arg.width = -1;
14696 arg.prec = -1;
14697 arg.sign = 0;
14698 str = NULL;
14699
Victor Stinnera47082312012-10-04 02:19:54 +020014700 ret = unicode_format_arg_parse(ctx, &arg);
14701 if (ret == -1)
14702 return -1;
14703
14704 ret = unicode_format_arg_format(ctx, &arg, &str);
14705 if (ret == -1)
14706 return -1;
14707
14708 if (ret != 1) {
14709 ret = unicode_format_arg_output(ctx, &arg, str);
14710 Py_DECREF(str);
14711 if (ret == -1)
14712 return -1;
14713 }
14714
14715 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14716 PyErr_SetString(PyExc_TypeError,
14717 "not all arguments converted during string formatting");
14718 return -1;
14719 }
14720 return 0;
14721}
14722
Alexander Belopolsky40018472011-02-26 01:02:56 +000014723PyObject *
14724PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014725{
Victor Stinnera47082312012-10-04 02:19:54 +020014726 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014727
Guido van Rossumd57fd912000-03-10 22:53:23 +000014728 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014729 PyErr_BadInternalCall();
14730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014731 }
Victor Stinnera47082312012-10-04 02:19:54 +020014732
14733 ctx.fmtstr = PyUnicode_FromObject(format);
14734 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014735 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014736 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14737 Py_DECREF(ctx.fmtstr);
14738 return NULL;
14739 }
14740 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14741 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14742 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14743 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014744
Victor Stinner8f674cc2013-04-17 23:02:17 +020014745 _PyUnicodeWriter_Init(&ctx.writer);
14746 ctx.writer.min_length = ctx.fmtcnt + 100;
14747 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014748
Guido van Rossumd57fd912000-03-10 22:53:23 +000014749 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014750 ctx.arglen = PyTuple_Size(args);
14751 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014752 }
14753 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014754 ctx.arglen = -1;
14755 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014756 }
Victor Stinnera47082312012-10-04 02:19:54 +020014757 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014758 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014759 ctx.dict = args;
14760 else
14761 ctx.dict = NULL;
14762 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014763
Victor Stinnera47082312012-10-04 02:19:54 +020014764 while (--ctx.fmtcnt >= 0) {
14765 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014766 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014767
14768 nonfmtpos = ctx.fmtpos++;
14769 while (ctx.fmtcnt >= 0 &&
14770 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14771 ctx.fmtpos++;
14772 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014773 }
Victor Stinnera47082312012-10-04 02:19:54 +020014774 if (ctx.fmtcnt < 0) {
14775 ctx.fmtpos--;
14776 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014777 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014778
Victor Stinnercfc4c132013-04-03 01:48:39 +020014779 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14780 nonfmtpos, ctx.fmtpos) < 0)
14781 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014782 }
14783 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014784 ctx.fmtpos++;
14785 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014786 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014787 }
14788 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014789
Victor Stinnera47082312012-10-04 02:19:54 +020014790 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014791 PyErr_SetString(PyExc_TypeError,
14792 "not all arguments converted during string formatting");
14793 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014794 }
14795
Victor Stinnera47082312012-10-04 02:19:54 +020014796 if (ctx.args_owned) {
14797 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014798 }
Victor Stinnera47082312012-10-04 02:19:54 +020014799 Py_DECREF(ctx.fmtstr);
14800 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014801
Benjamin Peterson29060642009-01-31 22:14:21 +000014802 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014803 Py_DECREF(ctx.fmtstr);
14804 _PyUnicodeWriter_Dealloc(&ctx.writer);
14805 if (ctx.args_owned) {
14806 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014807 }
14808 return NULL;
14809}
14810
Jeremy Hylton938ace62002-07-17 16:30:39 +000014811static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014812unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14813
Tim Peters6d6c1a32001-08-02 04:15:00 +000014814static PyObject *
14815unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14816{
Benjamin Peterson29060642009-01-31 22:14:21 +000014817 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014818 static char *kwlist[] = {"object", "encoding", "errors", 0};
14819 char *encoding = NULL;
14820 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014821
Benjamin Peterson14339b62009-01-31 16:36:08 +000014822 if (type != &PyUnicode_Type)
14823 return unicode_subtype_new(type, args, kwds);
14824 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014825 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014826 return NULL;
14827 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014828 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014829 if (encoding == NULL && errors == NULL)
14830 return PyObject_Str(x);
14831 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014832 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014833}
14834
Guido van Rossume023fe02001-08-30 03:12:59 +000014835static PyObject *
14836unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14837{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014838 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014839 Py_ssize_t length, char_size;
14840 int share_wstr, share_utf8;
14841 unsigned int kind;
14842 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014843
Benjamin Peterson14339b62009-01-31 16:36:08 +000014844 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014845
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014846 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014847 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014848 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014849 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014850 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014851 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014852 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014853 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014854
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014855 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014856 if (self == NULL) {
14857 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014858 return NULL;
14859 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014860 kind = PyUnicode_KIND(unicode);
14861 length = PyUnicode_GET_LENGTH(unicode);
14862
14863 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014864#ifdef Py_DEBUG
14865 _PyUnicode_HASH(self) = -1;
14866#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014867 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014868#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014869 _PyUnicode_STATE(self).interned = 0;
14870 _PyUnicode_STATE(self).kind = kind;
14871 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014872 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014873 _PyUnicode_STATE(self).ready = 1;
14874 _PyUnicode_WSTR(self) = NULL;
14875 _PyUnicode_UTF8_LENGTH(self) = 0;
14876 _PyUnicode_UTF8(self) = NULL;
14877 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014878 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014879
14880 share_utf8 = 0;
14881 share_wstr = 0;
14882 if (kind == PyUnicode_1BYTE_KIND) {
14883 char_size = 1;
14884 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14885 share_utf8 = 1;
14886 }
14887 else if (kind == PyUnicode_2BYTE_KIND) {
14888 char_size = 2;
14889 if (sizeof(wchar_t) == 2)
14890 share_wstr = 1;
14891 }
14892 else {
14893 assert(kind == PyUnicode_4BYTE_KIND);
14894 char_size = 4;
14895 if (sizeof(wchar_t) == 4)
14896 share_wstr = 1;
14897 }
14898
14899 /* Ensure we won't overflow the length. */
14900 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14901 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014902 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014903 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014904 data = PyObject_MALLOC((length + 1) * char_size);
14905 if (data == NULL) {
14906 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014907 goto onError;
14908 }
14909
Victor Stinnerc3c74152011-10-02 20:39:55 +020014910 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014911 if (share_utf8) {
14912 _PyUnicode_UTF8_LENGTH(self) = length;
14913 _PyUnicode_UTF8(self) = data;
14914 }
14915 if (share_wstr) {
14916 _PyUnicode_WSTR_LENGTH(self) = length;
14917 _PyUnicode_WSTR(self) = (wchar_t *)data;
14918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014919
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014920 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014921 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014922 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014923#ifdef Py_DEBUG
14924 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14925#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014926 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014927 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014928
14929onError:
14930 Py_DECREF(unicode);
14931 Py_DECREF(self);
14932 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014933}
14934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014935PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014936"str(object='') -> str\n\
14937str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014938\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014939Create a new string object from the given object. If encoding or\n\
14940errors is specified, then the object must expose a data buffer\n\
14941that will be decoded using the given encoding and error handler.\n\
14942Otherwise, returns the result of object.__str__() (if defined)\n\
14943or repr(object).\n\
14944encoding defaults to sys.getdefaultencoding().\n\
14945errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014946
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014947static PyObject *unicode_iter(PyObject *seq);
14948
Guido van Rossumd57fd912000-03-10 22:53:23 +000014949PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014950 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014951 "str", /* tp_name */
14952 sizeof(PyUnicodeObject), /* tp_size */
14953 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014954 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014955 (destructor)unicode_dealloc, /* tp_dealloc */
14956 0, /* tp_print */
14957 0, /* tp_getattr */
14958 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014959 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014960 unicode_repr, /* tp_repr */
14961 &unicode_as_number, /* tp_as_number */
14962 &unicode_as_sequence, /* tp_as_sequence */
14963 &unicode_as_mapping, /* tp_as_mapping */
14964 (hashfunc) unicode_hash, /* tp_hash*/
14965 0, /* tp_call*/
14966 (reprfunc) unicode_str, /* tp_str */
14967 PyObject_GenericGetAttr, /* tp_getattro */
14968 0, /* tp_setattro */
14969 0, /* tp_as_buffer */
14970 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014971 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014972 unicode_doc, /* tp_doc */
14973 0, /* tp_traverse */
14974 0, /* tp_clear */
14975 PyUnicode_RichCompare, /* tp_richcompare */
14976 0, /* tp_weaklistoffset */
14977 unicode_iter, /* tp_iter */
14978 0, /* tp_iternext */
14979 unicode_methods, /* tp_methods */
14980 0, /* tp_members */
14981 0, /* tp_getset */
14982 &PyBaseObject_Type, /* tp_base */
14983 0, /* tp_dict */
14984 0, /* tp_descr_get */
14985 0, /* tp_descr_set */
14986 0, /* tp_dictoffset */
14987 0, /* tp_init */
14988 0, /* tp_alloc */
14989 unicode_new, /* tp_new */
14990 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014991};
14992
14993/* Initialize the Unicode implementation */
14994
Victor Stinner3a50e702011-10-18 21:21:00 +020014995int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014996{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014997 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014998 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014999 0x000A, /* LINE FEED */
15000 0x000D, /* CARRIAGE RETURN */
15001 0x001C, /* FILE SEPARATOR */
15002 0x001D, /* GROUP SEPARATOR */
15003 0x001E, /* RECORD SEPARATOR */
15004 0x0085, /* NEXT LINE */
15005 0x2028, /* LINE SEPARATOR */
15006 0x2029, /* PARAGRAPH SEPARATOR */
15007 };
15008
Fred Drakee4315f52000-05-09 19:53:39 +000015009 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015010 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015011 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015012 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015013 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015014
Guido van Rossumcacfc072002-05-24 19:01:59 +000015015 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015016 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015017
15018 /* initialize the linebreak bloom filter */
15019 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015020 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015021 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015022
Christian Heimes26532f72013-07-20 14:57:16 +020015023 if (PyType_Ready(&EncodingMapType) < 0)
15024 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015025
Benjamin Petersonc4311282012-10-30 23:21:10 -040015026 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15027 Py_FatalError("Can't initialize field name iterator type");
15028
15029 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15030 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015031
Victor Stinner3a50e702011-10-18 21:21:00 +020015032 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015033}
15034
15035/* Finalize the Unicode implementation */
15036
Christian Heimesa156e092008-02-16 07:38:31 +000015037int
15038PyUnicode_ClearFreeList(void)
15039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015040 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015041}
15042
Guido van Rossumd57fd912000-03-10 22:53:23 +000015043void
Thomas Wouters78890102000-07-22 19:25:51 +000015044_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015045{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015046 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015047
Serhiy Storchaka05997252013-01-26 12:14:02 +020015048 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015049
Serhiy Storchaka05997252013-01-26 12:14:02 +020015050 for (i = 0; i < 256; i++)
15051 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015052 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015053 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015054}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015055
Walter Dörwald16807132007-05-25 13:52:07 +000015056void
15057PyUnicode_InternInPlace(PyObject **p)
15058{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015059 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015060 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015061#ifdef Py_DEBUG
15062 assert(s != NULL);
15063 assert(_PyUnicode_CHECK(s));
15064#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015065 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015066 return;
15067#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015068 /* If it's a subclass, we don't really know what putting
15069 it in the interned dict might do. */
15070 if (!PyUnicode_CheckExact(s))
15071 return;
15072 if (PyUnicode_CHECK_INTERNED(s))
15073 return;
15074 if (interned == NULL) {
15075 interned = PyDict_New();
15076 if (interned == NULL) {
15077 PyErr_Clear(); /* Don't leave an exception */
15078 return;
15079 }
15080 }
15081 /* It might be that the GetItem call fails even
15082 though the key is present in the dictionary,
15083 namely when this happens during a stack overflow. */
15084 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015085 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015086 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015087
Victor Stinnerf0335102013-04-14 19:13:03 +020015088 if (t) {
15089 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015090 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015091 return;
15092 }
Walter Dörwald16807132007-05-25 13:52:07 +000015093
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015095 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015096 PyErr_Clear();
15097 PyThreadState_GET()->recursion_critical = 0;
15098 return;
15099 }
15100 PyThreadState_GET()->recursion_critical = 0;
15101 /* The two references in interned are not counted by refcnt.
15102 The deallocator will take care of this */
15103 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015104 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015105}
15106
15107void
15108PyUnicode_InternImmortal(PyObject **p)
15109{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015110 PyUnicode_InternInPlace(p);
15111 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015112 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015113 Py_INCREF(*p);
15114 }
Walter Dörwald16807132007-05-25 13:52:07 +000015115}
15116
15117PyObject *
15118PyUnicode_InternFromString(const char *cp)
15119{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015120 PyObject *s = PyUnicode_FromString(cp);
15121 if (s == NULL)
15122 return NULL;
15123 PyUnicode_InternInPlace(&s);
15124 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015125}
15126
Alexander Belopolsky40018472011-02-26 01:02:56 +000015127void
15128_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015129{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015130 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015131 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 Py_ssize_t i, n;
15133 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015134
Benjamin Peterson14339b62009-01-31 16:36:08 +000015135 if (interned == NULL || !PyDict_Check(interned))
15136 return;
15137 keys = PyDict_Keys(interned);
15138 if (keys == NULL || !PyList_Check(keys)) {
15139 PyErr_Clear();
15140 return;
15141 }
Walter Dörwald16807132007-05-25 13:52:07 +000015142
Benjamin Peterson14339b62009-01-31 16:36:08 +000015143 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15144 detector, interned unicode strings are not forcibly deallocated;
15145 rather, we give them their stolen references back, and then clear
15146 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015147
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 n = PyList_GET_SIZE(keys);
15149 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015150 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015152 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015153 if (PyUnicode_READY(s) == -1) {
15154 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015155 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015157 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015158 case SSTATE_NOT_INTERNED:
15159 /* XXX Shouldn't happen */
15160 break;
15161 case SSTATE_INTERNED_IMMORTAL:
15162 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015163 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015164 break;
15165 case SSTATE_INTERNED_MORTAL:
15166 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015167 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015168 break;
15169 default:
15170 Py_FatalError("Inconsistent interned string state.");
15171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015172 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015173 }
15174 fprintf(stderr, "total size of all interned strings: "
15175 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15176 "mortal/immortal\n", mortal_size, immortal_size);
15177 Py_DECREF(keys);
15178 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015179 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015180}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015181
15182
15183/********************* Unicode Iterator **************************/
15184
15185typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015186 PyObject_HEAD
15187 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015188 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015189} unicodeiterobject;
15190
15191static void
15192unicodeiter_dealloc(unicodeiterobject *it)
15193{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015194 _PyObject_GC_UNTRACK(it);
15195 Py_XDECREF(it->it_seq);
15196 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015197}
15198
15199static int
15200unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15201{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 Py_VISIT(it->it_seq);
15203 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015204}
15205
15206static PyObject *
15207unicodeiter_next(unicodeiterobject *it)
15208{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015209 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015210
Benjamin Peterson14339b62009-01-31 16:36:08 +000015211 assert(it != NULL);
15212 seq = it->it_seq;
15213 if (seq == NULL)
15214 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015215 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015217 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15218 int kind = PyUnicode_KIND(seq);
15219 void *data = PyUnicode_DATA(seq);
15220 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15221 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015222 if (item != NULL)
15223 ++it->it_index;
15224 return item;
15225 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015226
Benjamin Peterson14339b62009-01-31 16:36:08 +000015227 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015228 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015229 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015230}
15231
15232static PyObject *
15233unicodeiter_len(unicodeiterobject *it)
15234{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015235 Py_ssize_t len = 0;
15236 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015237 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015239}
15240
15241PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15242
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015243static PyObject *
15244unicodeiter_reduce(unicodeiterobject *it)
15245{
15246 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015247 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015248 it->it_seq, it->it_index);
15249 } else {
15250 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15251 if (u == NULL)
15252 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015253 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015254 }
15255}
15256
15257PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15258
15259static PyObject *
15260unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15261{
15262 Py_ssize_t index = PyLong_AsSsize_t(state);
15263 if (index == -1 && PyErr_Occurred())
15264 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015265 if (it->it_seq != NULL) {
15266 if (index < 0)
15267 index = 0;
15268 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15269 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15270 it->it_index = index;
15271 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015272 Py_RETURN_NONE;
15273}
15274
15275PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15276
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015277static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015278 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015279 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015280 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15281 reduce_doc},
15282 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15283 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015284 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015285};
15286
15287PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015288 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15289 "str_iterator", /* tp_name */
15290 sizeof(unicodeiterobject), /* tp_basicsize */
15291 0, /* tp_itemsize */
15292 /* methods */
15293 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15294 0, /* tp_print */
15295 0, /* tp_getattr */
15296 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015297 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015298 0, /* tp_repr */
15299 0, /* tp_as_number */
15300 0, /* tp_as_sequence */
15301 0, /* tp_as_mapping */
15302 0, /* tp_hash */
15303 0, /* tp_call */
15304 0, /* tp_str */
15305 PyObject_GenericGetAttr, /* tp_getattro */
15306 0, /* tp_setattro */
15307 0, /* tp_as_buffer */
15308 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15309 0, /* tp_doc */
15310 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15311 0, /* tp_clear */
15312 0, /* tp_richcompare */
15313 0, /* tp_weaklistoffset */
15314 PyObject_SelfIter, /* tp_iter */
15315 (iternextfunc)unicodeiter_next, /* tp_iternext */
15316 unicodeiter_methods, /* tp_methods */
15317 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015318};
15319
15320static PyObject *
15321unicode_iter(PyObject *seq)
15322{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015323 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015324
Benjamin Peterson14339b62009-01-31 16:36:08 +000015325 if (!PyUnicode_Check(seq)) {
15326 PyErr_BadInternalCall();
15327 return NULL;
15328 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015329 if (PyUnicode_READY(seq) == -1)
15330 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15332 if (it == NULL)
15333 return NULL;
15334 it->it_index = 0;
15335 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015336 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015337 _PyObject_GC_TRACK(it);
15338 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015339}
15340
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015341
15342size_t
15343Py_UNICODE_strlen(const Py_UNICODE *u)
15344{
15345 int res = 0;
15346 while(*u++)
15347 res++;
15348 return res;
15349}
15350
15351Py_UNICODE*
15352Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15353{
15354 Py_UNICODE *u = s1;
15355 while ((*u++ = *s2++));
15356 return s1;
15357}
15358
15359Py_UNICODE*
15360Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15361{
15362 Py_UNICODE *u = s1;
15363 while ((*u++ = *s2++))
15364 if (n-- == 0)
15365 break;
15366 return s1;
15367}
15368
15369Py_UNICODE*
15370Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15371{
15372 Py_UNICODE *u1 = s1;
15373 u1 += Py_UNICODE_strlen(u1);
15374 Py_UNICODE_strcpy(u1, s2);
15375 return s1;
15376}
15377
15378int
15379Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15380{
15381 while (*s1 && *s2 && *s1 == *s2)
15382 s1++, s2++;
15383 if (*s1 && *s2)
15384 return (*s1 < *s2) ? -1 : +1;
15385 if (*s1)
15386 return 1;
15387 if (*s2)
15388 return -1;
15389 return 0;
15390}
15391
15392int
15393Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15394{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015395 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015396 for (; n != 0; n--) {
15397 u1 = *s1;
15398 u2 = *s2;
15399 if (u1 != u2)
15400 return (u1 < u2) ? -1 : +1;
15401 if (u1 == '\0')
15402 return 0;
15403 s1++;
15404 s2++;
15405 }
15406 return 0;
15407}
15408
15409Py_UNICODE*
15410Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15411{
15412 const Py_UNICODE *p;
15413 for (p = s; *p; p++)
15414 if (*p == c)
15415 return (Py_UNICODE*)p;
15416 return NULL;
15417}
15418
15419Py_UNICODE*
15420Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15421{
15422 const Py_UNICODE *p;
15423 p = s + Py_UNICODE_strlen(s);
15424 while (p != s) {
15425 p--;
15426 if (*p == c)
15427 return (Py_UNICODE*)p;
15428 }
15429 return NULL;
15430}
Victor Stinner331ea922010-08-10 16:37:20 +000015431
Victor Stinner71133ff2010-09-01 23:43:53 +000015432Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015433PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015434{
Victor Stinner577db2c2011-10-11 22:12:48 +020015435 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015436 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015438 if (!PyUnicode_Check(unicode)) {
15439 PyErr_BadArgument();
15440 return NULL;
15441 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015442 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015443 if (u == NULL)
15444 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015445 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015446 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015447 PyErr_NoMemory();
15448 return NULL;
15449 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015450 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015451 size *= sizeof(Py_UNICODE);
15452 copy = PyMem_Malloc(size);
15453 if (copy == NULL) {
15454 PyErr_NoMemory();
15455 return NULL;
15456 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015457 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015458 return copy;
15459}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015460
Georg Brandl66c221e2010-10-14 07:04:07 +000015461/* A _string module, to export formatter_parser and formatter_field_name_split
15462 to the string.Formatter class implemented in Python. */
15463
15464static PyMethodDef _string_methods[] = {
15465 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15466 METH_O, PyDoc_STR("split the argument as a field name")},
15467 {"formatter_parser", (PyCFunction) formatter_parser,
15468 METH_O, PyDoc_STR("parse the argument as a format string")},
15469 {NULL, NULL}
15470};
15471
15472static struct PyModuleDef _string_module = {
15473 PyModuleDef_HEAD_INIT,
15474 "_string",
15475 PyDoc_STR("string helper module"),
15476 0,
15477 _string_methods,
15478 NULL,
15479 NULL,
15480 NULL,
15481 NULL
15482};
15483
15484PyMODINIT_FUNC
15485PyInit__string(void)
15486{
15487 return PyModule_Create(&_string_module);
15488}
15489
15490
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015491#ifdef __cplusplus
15492}
15493#endif