blob: 0b78301f23625d3477d86d0603b58f3522cda836 [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
678/* Fill the data of an Unicode string with invalid characters to detect bugs
679 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;
751 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200752#ifdef Py_DEBUG
753 unicode_fill_invalid(unicode, old_length);
754#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200755 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
756 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200757 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200758 return unicode;
759}
760
Alexander Belopolsky40018472011-02-26 01:02:56 +0000761static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200762resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000763{
Victor Stinner95663112011-10-04 01:03:50 +0200764 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100765 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200766 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200767 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000768
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 if (PyUnicode_IS_READY(unicode)) {
770 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200771 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200772 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200773#ifdef Py_DEBUG
774 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
775#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200776
777 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200778 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200779 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
780 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200781
782 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
783 PyErr_NoMemory();
784 return -1;
785 }
786 new_size = (length + 1) * char_size;
787
Victor Stinner7a9105a2011-12-12 00:13:42 +0100788 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
789 {
790 PyObject_DEL(_PyUnicode_UTF8(unicode));
791 _PyUnicode_UTF8(unicode) = NULL;
792 _PyUnicode_UTF8_LENGTH(unicode) = 0;
793 }
794
Victor Stinnerfe226c02011-10-03 03:52:20 +0200795 data = (PyObject *)PyObject_REALLOC(data, new_size);
796 if (data == NULL) {
797 PyErr_NoMemory();
798 return -1;
799 }
800 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200801 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200802 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200803 _PyUnicode_WSTR_LENGTH(unicode) = length;
804 }
805 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200806 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200807 _PyUnicode_UTF8_LENGTH(unicode) = length;
808 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200809 _PyUnicode_LENGTH(unicode) = length;
810 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200811#ifdef Py_DEBUG
812 unicode_fill_invalid(unicode, old_length);
813#endif
Victor Stinner95663112011-10-04 01:03:50 +0200814 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200815 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200816 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200817 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200818 }
Victor Stinner95663112011-10-04 01:03:50 +0200819 assert(_PyUnicode_WSTR(unicode) != NULL);
820
821 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700822 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200823 PyErr_NoMemory();
824 return -1;
825 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100826 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200827 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100828 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200829 if (!wstr) {
830 PyErr_NoMemory();
831 return -1;
832 }
833 _PyUnicode_WSTR(unicode) = wstr;
834 _PyUnicode_WSTR(unicode)[length] = 0;
835 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200836 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000837 return 0;
838}
839
Victor Stinnerfe226c02011-10-03 03:52:20 +0200840static PyObject*
841resize_copy(PyObject *unicode, Py_ssize_t length)
842{
843 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100844 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200845 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100846
Benjamin Petersonbac79492012-01-14 13:34:47 -0500847 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100848 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200849
850 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
851 if (copy == NULL)
852 return NULL;
853
854 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200855 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200856 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200857 }
858 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200859 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100860
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200861 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200862 if (w == NULL)
863 return NULL;
864 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
865 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200866 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
867 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200868 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200869 }
870}
871
Guido van Rossumd57fd912000-03-10 22:53:23 +0000872/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000873 Ux0000 terminated; some code (e.g. new_identifier)
874 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875
876 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000877 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000878
879*/
880
Alexander Belopolsky40018472011-02-26 01:02:56 +0000881static PyUnicodeObject *
882_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200884 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200885 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000886
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888 if (length == 0 && unicode_empty != NULL) {
889 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200890 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000891 }
892
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000893 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700894 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000895 return (PyUnicodeObject *)PyErr_NoMemory();
896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200897 if (length < 0) {
898 PyErr_SetString(PyExc_SystemError,
899 "Negative size passed to _PyUnicode_New");
900 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000901 }
902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200903 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
904 if (unicode == NULL)
905 return NULL;
906 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100907
908 _PyUnicode_WSTR_LENGTH(unicode) = length;
909 _PyUnicode_HASH(unicode) = -1;
910 _PyUnicode_STATE(unicode).interned = 0;
911 _PyUnicode_STATE(unicode).kind = 0;
912 _PyUnicode_STATE(unicode).compact = 0;
913 _PyUnicode_STATE(unicode).ready = 0;
914 _PyUnicode_STATE(unicode).ascii = 0;
915 _PyUnicode_DATA_ANY(unicode) = NULL;
916 _PyUnicode_LENGTH(unicode) = 0;
917 _PyUnicode_UTF8(unicode) = NULL;
918 _PyUnicode_UTF8_LENGTH(unicode) = 0;
919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200920 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
921 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100922 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000923 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100924 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000925 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200926
Jeremy Hyltond8082792003-09-16 19:41:39 +0000927 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000928 * the caller fails before initializing str -- unicode_resize()
929 * reads str[0], and the Keep-Alive optimization can keep memory
930 * allocated for str alive across a call to unicode_dealloc(unicode).
931 * We don't want unicode_resize to read uninitialized memory in
932 * that case.
933 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200934 _PyUnicode_WSTR(unicode)[0] = 0;
935 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100936
Victor Stinner7931d9a2011-11-04 00:22:48 +0100937 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000938 return unicode;
939}
940
Victor Stinnerf42dc442011-10-02 23:33:16 +0200941static const char*
942unicode_kind_name(PyObject *unicode)
943{
Victor Stinner42dfd712011-10-03 14:41:45 +0200944 /* don't check consistency: unicode_kind_name() is called from
945 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200946 if (!PyUnicode_IS_COMPACT(unicode))
947 {
948 if (!PyUnicode_IS_READY(unicode))
949 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600950 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200951 {
952 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200953 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200954 return "legacy ascii";
955 else
956 return "legacy latin1";
957 case PyUnicode_2BYTE_KIND:
958 return "legacy UCS2";
959 case PyUnicode_4BYTE_KIND:
960 return "legacy UCS4";
961 default:
962 return "<legacy invalid kind>";
963 }
964 }
965 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600966 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200967 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 return "ascii";
970 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200971 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200972 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200973 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200974 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200975 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200976 default:
977 return "<invalid compact kind>";
978 }
979}
980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200981#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982/* Functions wrapping macros for use in debugger */
983char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200984 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200985}
986
987void *_PyUnicode_compact_data(void *unicode) {
988 return _PyUnicode_COMPACT_DATA(unicode);
989}
990void *_PyUnicode_data(void *unicode){
991 printf("obj %p\n", unicode);
992 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
993 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
994 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
995 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
996 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
997 return PyUnicode_DATA(unicode);
998}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200999
1000void
1001_PyUnicode_Dump(PyObject *op)
1002{
1003 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001004 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1005 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1006 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001007
Victor Stinnera849a4b2011-10-03 12:12:11 +02001008 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001009 {
1010 if (ascii->state.ascii)
1011 data = (ascii + 1);
1012 else
1013 data = (compact + 1);
1014 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001015 else
1016 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001017 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1018 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001019
Victor Stinnera849a4b2011-10-03 12:12:11 +02001020 if (ascii->wstr == data)
1021 printf("shared ");
1022 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001023
Victor Stinnera3b334d2011-10-03 13:53:37 +02001024 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001025 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001026 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1027 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001028 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1029 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001030 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001031 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001032}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033#endif
1034
1035PyObject *
1036PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1037{
1038 PyObject *obj;
1039 PyCompactUnicodeObject *unicode;
1040 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001041 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001042 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 Py_ssize_t char_size;
1044 Py_ssize_t struct_size;
1045
1046 /* Optimization for empty strings */
1047 if (size == 0 && unicode_empty != NULL) {
1048 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001049 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 }
1051
Victor Stinner9e9d6892011-10-04 01:02:02 +02001052 is_ascii = 0;
1053 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 struct_size = sizeof(PyCompactUnicodeObject);
1055 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001056 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057 char_size = 1;
1058 is_ascii = 1;
1059 struct_size = sizeof(PyASCIIObject);
1060 }
1061 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001062 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001063 char_size = 1;
1064 }
1065 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001066 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001067 char_size = 2;
1068 if (sizeof(wchar_t) == 2)
1069 is_sharing = 1;
1070 }
1071 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001072 if (maxchar > MAX_UNICODE) {
1073 PyErr_SetString(PyExc_SystemError,
1074 "invalid maximum character passed to PyUnicode_New");
1075 return NULL;
1076 }
Victor Stinner8f825062012-04-27 13:55:39 +02001077 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078 char_size = 4;
1079 if (sizeof(wchar_t) == 4)
1080 is_sharing = 1;
1081 }
1082
1083 /* Ensure we won't overflow the size. */
1084 if (size < 0) {
1085 PyErr_SetString(PyExc_SystemError,
1086 "Negative size passed to PyUnicode_New");
1087 return NULL;
1088 }
1089 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1090 return PyErr_NoMemory();
1091
1092 /* Duplicated allocation code from _PyObject_New() instead of a call to
1093 * PyObject_New() so we are able to allocate space for the object and
1094 * it's data buffer.
1095 */
1096 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1097 if (obj == NULL)
1098 return PyErr_NoMemory();
1099 obj = PyObject_INIT(obj, &PyUnicode_Type);
1100 if (obj == NULL)
1101 return NULL;
1102
1103 unicode = (PyCompactUnicodeObject *)obj;
1104 if (is_ascii)
1105 data = ((PyASCIIObject*)obj) + 1;
1106 else
1107 data = unicode + 1;
1108 _PyUnicode_LENGTH(unicode) = size;
1109 _PyUnicode_HASH(unicode) = -1;
1110 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001111 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001112 _PyUnicode_STATE(unicode).compact = 1;
1113 _PyUnicode_STATE(unicode).ready = 1;
1114 _PyUnicode_STATE(unicode).ascii = is_ascii;
1115 if (is_ascii) {
1116 ((char*)data)[size] = 0;
1117 _PyUnicode_WSTR(unicode) = NULL;
1118 }
Victor Stinner8f825062012-04-27 13:55:39 +02001119 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 ((char*)data)[size] = 0;
1121 _PyUnicode_WSTR(unicode) = NULL;
1122 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001124 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001125 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126 else {
1127 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001128 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001129 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001131 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001132 ((Py_UCS4*)data)[size] = 0;
1133 if (is_sharing) {
1134 _PyUnicode_WSTR_LENGTH(unicode) = size;
1135 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1136 }
1137 else {
1138 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1139 _PyUnicode_WSTR(unicode) = NULL;
1140 }
1141 }
Victor Stinner8f825062012-04-27 13:55:39 +02001142#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001143 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001144#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001145 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146 return obj;
1147}
1148
1149#if SIZEOF_WCHAR_T == 2
1150/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1151 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001152 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153
1154 This function assumes that unicode can hold one more code point than wstr
1155 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001156static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001157unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001158 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159{
1160 const wchar_t *iter;
1161 Py_UCS4 *ucs4_out;
1162
Victor Stinner910337b2011-10-03 03:20:16 +02001163 assert(unicode != NULL);
1164 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1166 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1167
1168 for (iter = begin; iter < end; ) {
1169 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1170 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001171 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1172 && (iter+1) < end
1173 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001174 {
Victor Stinner551ac952011-11-29 22:58:13 +01001175 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001176 iter += 2;
1177 }
1178 else {
1179 *ucs4_out++ = *iter;
1180 iter++;
1181 }
1182 }
1183 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1184 _PyUnicode_GET_LENGTH(unicode)));
1185
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001186}
1187#endif
1188
Victor Stinnercd9950f2011-10-02 00:34:53 +02001189static int
Victor Stinner488fa492011-12-12 00:01:39 +01001190unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001191{
Victor Stinner488fa492011-12-12 00:01:39 +01001192 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001193 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001194 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001195 return -1;
1196 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001197 return 0;
1198}
1199
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001200static int
1201_copy_characters(PyObject *to, Py_ssize_t to_start,
1202 PyObject *from, Py_ssize_t from_start,
1203 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 unsigned int from_kind, to_kind;
1206 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207
Victor Stinneree4544c2012-05-09 22:24:08 +02001208 assert(0 <= how_many);
1209 assert(0 <= from_start);
1210 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001211 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001212 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001213 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001214
Victor Stinnerd3f08822012-05-29 12:57:52 +02001215 assert(PyUnicode_Check(to));
1216 assert(PyUnicode_IS_READY(to));
1217 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1218
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001219 if (how_many == 0)
1220 return 0;
1221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001222 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001223 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001225 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001226
Victor Stinnerf1852262012-06-16 16:38:26 +02001227#ifdef Py_DEBUG
1228 if (!check_maxchar
1229 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1230 {
1231 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1232 Py_UCS4 ch;
1233 Py_ssize_t i;
1234 for (i=0; i < how_many; i++) {
1235 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1236 assert(ch <= to_maxchar);
1237 }
1238 }
1239#endif
1240
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001241 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001242 if (check_maxchar
1243 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1244 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001245 /* Writing Latin-1 characters into an ASCII string requires to
1246 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001247 Py_UCS4 max_char;
1248 max_char = ucs1lib_find_max_char(from_data,
1249 (Py_UCS1*)from_data + how_many);
1250 if (max_char >= 128)
1251 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001252 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001253 Py_MEMCPY((char*)to_data + to_kind * to_start,
1254 (char*)from_data + from_kind * from_start,
1255 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001256 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001257 else if (from_kind == PyUnicode_1BYTE_KIND
1258 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001259 {
1260 _PyUnicode_CONVERT_BYTES(
1261 Py_UCS1, Py_UCS2,
1262 PyUnicode_1BYTE_DATA(from) + from_start,
1263 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1264 PyUnicode_2BYTE_DATA(to) + to_start
1265 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001266 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001267 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001268 && to_kind == PyUnicode_4BYTE_KIND)
1269 {
1270 _PyUnicode_CONVERT_BYTES(
1271 Py_UCS1, Py_UCS4,
1272 PyUnicode_1BYTE_DATA(from) + from_start,
1273 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1274 PyUnicode_4BYTE_DATA(to) + to_start
1275 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001276 }
1277 else if (from_kind == PyUnicode_2BYTE_KIND
1278 && to_kind == PyUnicode_4BYTE_KIND)
1279 {
1280 _PyUnicode_CONVERT_BYTES(
1281 Py_UCS2, Py_UCS4,
1282 PyUnicode_2BYTE_DATA(from) + from_start,
1283 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1284 PyUnicode_4BYTE_DATA(to) + to_start
1285 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001286 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001287 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001288 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1289
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001290 if (!check_maxchar) {
1291 if (from_kind == PyUnicode_2BYTE_KIND
1292 && to_kind == PyUnicode_1BYTE_KIND)
1293 {
1294 _PyUnicode_CONVERT_BYTES(
1295 Py_UCS2, Py_UCS1,
1296 PyUnicode_2BYTE_DATA(from) + from_start,
1297 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1298 PyUnicode_1BYTE_DATA(to) + to_start
1299 );
1300 }
1301 else if (from_kind == PyUnicode_4BYTE_KIND
1302 && to_kind == PyUnicode_1BYTE_KIND)
1303 {
1304 _PyUnicode_CONVERT_BYTES(
1305 Py_UCS4, Py_UCS1,
1306 PyUnicode_4BYTE_DATA(from) + from_start,
1307 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1308 PyUnicode_1BYTE_DATA(to) + to_start
1309 );
1310 }
1311 else if (from_kind == PyUnicode_4BYTE_KIND
1312 && to_kind == PyUnicode_2BYTE_KIND)
1313 {
1314 _PyUnicode_CONVERT_BYTES(
1315 Py_UCS4, Py_UCS2,
1316 PyUnicode_4BYTE_DATA(from) + from_start,
1317 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1318 PyUnicode_2BYTE_DATA(to) + to_start
1319 );
1320 }
1321 else {
1322 assert(0);
1323 return -1;
1324 }
1325 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001326 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001327 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001328 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001329 Py_ssize_t i;
1330
Victor Stinnera0702ab2011-09-29 14:14:38 +02001331 for (i=0; i < how_many; i++) {
1332 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001333 if (ch > to_maxchar)
1334 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001335 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1336 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001337 }
1338 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001339 return 0;
1340}
1341
Victor Stinnerd3f08822012-05-29 12:57:52 +02001342void
1343_PyUnicode_FastCopyCharacters(
1344 PyObject *to, Py_ssize_t to_start,
1345 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001346{
1347 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1348}
1349
1350Py_ssize_t
1351PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1352 PyObject *from, Py_ssize_t from_start,
1353 Py_ssize_t how_many)
1354{
1355 int err;
1356
1357 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1358 PyErr_BadInternalCall();
1359 return -1;
1360 }
1361
Benjamin Petersonbac79492012-01-14 13:34:47 -05001362 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001363 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001364 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001365 return -1;
1366
Victor Stinnerd3f08822012-05-29 12:57:52 +02001367 if (from_start < 0) {
1368 PyErr_SetString(PyExc_IndexError, "string index out of range");
1369 return -1;
1370 }
1371 if (to_start < 0) {
1372 PyErr_SetString(PyExc_IndexError, "string index out of range");
1373 return -1;
1374 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001375 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1376 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1377 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001378 "Cannot write %zi characters at %zi "
1379 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001380 how_many, to_start, PyUnicode_GET_LENGTH(to));
1381 return -1;
1382 }
1383
1384 if (how_many == 0)
1385 return 0;
1386
Victor Stinner488fa492011-12-12 00:01:39 +01001387 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001388 return -1;
1389
1390 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1391 if (err) {
1392 PyErr_Format(PyExc_SystemError,
1393 "Cannot copy %s characters "
1394 "into a string of %s characters",
1395 unicode_kind_name(from),
1396 unicode_kind_name(to));
1397 return -1;
1398 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001399 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400}
1401
Victor Stinner17222162011-09-28 22:15:37 +02001402/* Find the maximum code point and count the number of surrogate pairs so a
1403 correct string length can be computed before converting a string to UCS4.
1404 This function counts single surrogates as a character and not as a pair.
1405
1406 Return 0 on success, or -1 on error. */
1407static int
1408find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1409 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410{
1411 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001412 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001413
Victor Stinnerc53be962011-10-02 21:33:54 +02001414 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 *num_surrogates = 0;
1416 *maxchar = 0;
1417
1418 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001420 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1421 && (iter+1) < end
1422 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1423 {
1424 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1425 ++(*num_surrogates);
1426 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001427 }
1428 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001430 {
1431 ch = *iter;
1432 iter++;
1433 }
1434 if (ch > *maxchar) {
1435 *maxchar = ch;
1436 if (*maxchar > MAX_UNICODE) {
1437 PyErr_Format(PyExc_ValueError,
1438 "character U+%x is not in range [U+0000; U+10ffff]",
1439 ch);
1440 return -1;
1441 }
1442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443 }
1444 return 0;
1445}
1446
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001447int
1448_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001449{
1450 wchar_t *end;
1451 Py_UCS4 maxchar = 0;
1452 Py_ssize_t num_surrogates;
1453#if SIZEOF_WCHAR_T == 2
1454 Py_ssize_t length_wo_surrogates;
1455#endif
1456
Georg Brandl7597add2011-10-05 16:36:47 +02001457 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001458 strings were created using _PyObject_New() and where no canonical
1459 representation (the str field) has been set yet aka strings
1460 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001461 assert(_PyUnicode_CHECK(unicode));
1462 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001463 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001464 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001465 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001466 /* Actually, it should neither be interned nor be anything else: */
1467 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001470 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001471 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473
1474 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001475 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1476 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 PyErr_NoMemory();
1478 return -1;
1479 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001480 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001481 _PyUnicode_WSTR(unicode), end,
1482 PyUnicode_1BYTE_DATA(unicode));
1483 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1484 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1485 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1486 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001487 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001488 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001489 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 }
1491 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001492 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001493 _PyUnicode_UTF8(unicode) = NULL;
1494 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495 }
1496 PyObject_FREE(_PyUnicode_WSTR(unicode));
1497 _PyUnicode_WSTR(unicode) = NULL;
1498 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1499 }
1500 /* In this case we might have to convert down from 4-byte native
1501 wchar_t to 2-byte unicode. */
1502 else if (maxchar < 65536) {
1503 assert(num_surrogates == 0 &&
1504 "FindMaxCharAndNumSurrogatePairs() messed up");
1505
Victor Stinner506f5922011-09-28 22:34:18 +02001506#if SIZEOF_WCHAR_T == 2
1507 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001508 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001509 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1510 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1511 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001512 _PyUnicode_UTF8(unicode) = NULL;
1513 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001514#else
1515 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001516 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001517 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001518 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001519 PyErr_NoMemory();
1520 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 }
Victor Stinner506f5922011-09-28 22:34:18 +02001522 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1523 _PyUnicode_WSTR(unicode), end,
1524 PyUnicode_2BYTE_DATA(unicode));
1525 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1526 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1527 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001528 _PyUnicode_UTF8(unicode) = NULL;
1529 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001530 PyObject_FREE(_PyUnicode_WSTR(unicode));
1531 _PyUnicode_WSTR(unicode) = NULL;
1532 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1533#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001534 }
1535 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1536 else {
1537#if SIZEOF_WCHAR_T == 2
1538 /* in case the native representation is 2-bytes, we need to allocate a
1539 new normalized 4-byte version. */
1540 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001541 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1542 PyErr_NoMemory();
1543 return -1;
1544 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001545 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1546 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001547 PyErr_NoMemory();
1548 return -1;
1549 }
1550 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1551 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001552 _PyUnicode_UTF8(unicode) = NULL;
1553 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001554 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1555 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001556 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 PyObject_FREE(_PyUnicode_WSTR(unicode));
1558 _PyUnicode_WSTR(unicode) = NULL;
1559 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1560#else
1561 assert(num_surrogates == 0);
1562
Victor Stinnerc3c74152011-10-02 20:39:55 +02001563 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001565 _PyUnicode_UTF8(unicode) = NULL;
1566 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001567 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1568#endif
1569 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1570 }
1571 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001572 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001573 return 0;
1574}
1575
Alexander Belopolsky40018472011-02-26 01:02:56 +00001576static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001577unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001578{
Walter Dörwald16807132007-05-25 13:52:07 +00001579 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 case SSTATE_NOT_INTERNED:
1581 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001582
Benjamin Peterson29060642009-01-31 22:14:21 +00001583 case SSTATE_INTERNED_MORTAL:
1584 /* revive dead object temporarily for DelItem */
1585 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001586 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 Py_FatalError(
1588 "deletion of interned string failed");
1589 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001590
Benjamin Peterson29060642009-01-31 22:14:21 +00001591 case SSTATE_INTERNED_IMMORTAL:
1592 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001593
Benjamin Peterson29060642009-01-31 22:14:21 +00001594 default:
1595 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001596 }
1597
Victor Stinner03490912011-10-03 23:45:12 +02001598 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001600 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001601 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001602 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1603 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001605 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606}
1607
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001608#ifdef Py_DEBUG
1609static int
1610unicode_is_singleton(PyObject *unicode)
1611{
1612 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1613 if (unicode == unicode_empty)
1614 return 1;
1615 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1616 {
1617 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1618 if (ch < 256 && unicode_latin1[ch] == unicode)
1619 return 1;
1620 }
1621 return 0;
1622}
1623#endif
1624
Alexander Belopolsky40018472011-02-26 01:02:56 +00001625static int
Victor Stinner488fa492011-12-12 00:01:39 +01001626unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001627{
Victor Stinner488fa492011-12-12 00:01:39 +01001628 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001629 if (Py_REFCNT(unicode) != 1)
1630 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001631 if (_PyUnicode_HASH(unicode) != -1)
1632 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001633 if (PyUnicode_CHECK_INTERNED(unicode))
1634 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001635 if (!PyUnicode_CheckExact(unicode))
1636 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001637#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001638 /* singleton refcount is greater than 1 */
1639 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001640#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641 return 1;
1642}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001643
Victor Stinnerfe226c02011-10-03 03:52:20 +02001644static int
1645unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1646{
1647 PyObject *unicode;
1648 Py_ssize_t old_length;
1649
1650 assert(p_unicode != NULL);
1651 unicode = *p_unicode;
1652
1653 assert(unicode != NULL);
1654 assert(PyUnicode_Check(unicode));
1655 assert(0 <= length);
1656
Victor Stinner910337b2011-10-03 03:20:16 +02001657 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001658 old_length = PyUnicode_WSTR_LENGTH(unicode);
1659 else
1660 old_length = PyUnicode_GET_LENGTH(unicode);
1661 if (old_length == length)
1662 return 0;
1663
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001664 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001665 _Py_INCREF_UNICODE_EMPTY();
1666 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001667 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001668 Py_DECREF(*p_unicode);
1669 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001670 return 0;
1671 }
1672
Victor Stinner488fa492011-12-12 00:01:39 +01001673 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001674 PyObject *copy = resize_copy(unicode, length);
1675 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001676 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001677 Py_DECREF(*p_unicode);
1678 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001679 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001680 }
1681
Victor Stinnerfe226c02011-10-03 03:52:20 +02001682 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001683 PyObject *new_unicode = resize_compact(unicode, length);
1684 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001685 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001686 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001687 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001688 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001689 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001690}
1691
Alexander Belopolsky40018472011-02-26 01:02:56 +00001692int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001693PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001694{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695 PyObject *unicode;
1696 if (p_unicode == NULL) {
1697 PyErr_BadInternalCall();
1698 return -1;
1699 }
1700 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001701 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001702 {
1703 PyErr_BadInternalCall();
1704 return -1;
1705 }
1706 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001707}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001708
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001709/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001710
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001711 WARNING: The function doesn't copy the terminating null character and
1712 doesn't check the maximum character (may write a latin1 character in an
1713 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001714static void
1715unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1716 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001717{
1718 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1719 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001720 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001721
1722 switch (kind) {
1723 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001724 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001725#ifdef Py_DEBUG
1726 if (PyUnicode_IS_ASCII(unicode)) {
1727 Py_UCS4 maxchar = ucs1lib_find_max_char(
1728 (const Py_UCS1*)str,
1729 (const Py_UCS1*)str + len);
1730 assert(maxchar < 128);
1731 }
1732#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001733 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001734 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 }
1736 case PyUnicode_2BYTE_KIND: {
1737 Py_UCS2 *start = (Py_UCS2 *)data + index;
1738 Py_UCS2 *ucs2 = start;
1739 assert(index <= PyUnicode_GET_LENGTH(unicode));
1740
Victor Stinner184252a2012-06-16 02:57:41 +02001741 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001742 *ucs2 = (Py_UCS2)*str;
1743
1744 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001745 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001746 }
1747 default: {
1748 Py_UCS4 *start = (Py_UCS4 *)data + index;
1749 Py_UCS4 *ucs4 = start;
1750 assert(kind == PyUnicode_4BYTE_KIND);
1751 assert(index <= PyUnicode_GET_LENGTH(unicode));
1752
Victor Stinner184252a2012-06-16 02:57:41 +02001753 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001754 *ucs4 = (Py_UCS4)*str;
1755
1756 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001757 }
1758 }
1759}
1760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761static PyObject*
1762get_latin1_char(unsigned char ch)
1763{
Victor Stinnera464fc12011-10-02 20:39:30 +02001764 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001766 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 if (!unicode)
1768 return NULL;
1769 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001770 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001771 unicode_latin1[ch] = unicode;
1772 }
1773 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001774 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775}
1776
Victor Stinner985a82a2014-01-03 12:53:47 +01001777static PyObject*
1778unicode_char(Py_UCS4 ch)
1779{
1780 PyObject *unicode;
1781
1782 assert(ch <= MAX_UNICODE);
1783
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001784 if (ch < 256)
1785 return get_latin1_char(ch);
1786
Victor Stinner985a82a2014-01-03 12:53:47 +01001787 unicode = PyUnicode_New(1, ch);
1788 if (unicode == NULL)
1789 return NULL;
1790 switch (PyUnicode_KIND(unicode)) {
1791 case PyUnicode_1BYTE_KIND:
1792 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1793 break;
1794 case PyUnicode_2BYTE_KIND:
1795 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1796 break;
1797 default:
1798 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1799 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1800 }
1801 assert(_PyUnicode_CheckConsistency(unicode, 1));
1802 return unicode;
1803}
1804
Alexander Belopolsky40018472011-02-26 01:02:56 +00001805PyObject *
1806PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001808 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 Py_UCS4 maxchar = 0;
1810 Py_ssize_t num_surrogates;
1811
1812 if (u == NULL)
1813 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001814
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001815 /* If the Unicode data is known at construction time, we can apply
1816 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001819 if (size == 0)
1820 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001821
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001822 /* Single character Unicode objects in the Latin-1 range are
1823 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001824 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825 return get_latin1_char((unsigned char)*u);
1826
1827 /* If not empty and not single character, copy the Unicode data
1828 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001829 if (find_maxchar_surrogates(u, u + size,
1830 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001831 return NULL;
1832
Victor Stinner8faf8212011-12-08 22:14:11 +01001833 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001834 if (!unicode)
1835 return NULL;
1836
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837 switch (PyUnicode_KIND(unicode)) {
1838 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001839 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1841 break;
1842 case PyUnicode_2BYTE_KIND:
1843#if Py_UNICODE_SIZE == 2
1844 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1845#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001846 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001847 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1848#endif
1849 break;
1850 case PyUnicode_4BYTE_KIND:
1851#if SIZEOF_WCHAR_T == 2
1852 /* This is the only case which has to process surrogates, thus
1853 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001854 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001855#else
1856 assert(num_surrogates == 0);
1857 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1858#endif
1859 break;
1860 default:
1861 assert(0 && "Impossible state");
1862 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001863
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001864 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001865}
1866
Alexander Belopolsky40018472011-02-26 01:02:56 +00001867PyObject *
1868PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001869{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001870 if (size < 0) {
1871 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001872 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001873 return NULL;
1874 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001875 if (u != NULL)
1876 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1877 else
1878 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001879}
1880
Alexander Belopolsky40018472011-02-26 01:02:56 +00001881PyObject *
1882PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883{
1884 size_t size = strlen(u);
1885 if (size > PY_SSIZE_T_MAX) {
1886 PyErr_SetString(PyExc_OverflowError, "input too long");
1887 return NULL;
1888 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001889 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001890}
1891
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001892PyObject *
1893_PyUnicode_FromId(_Py_Identifier *id)
1894{
1895 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001896 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1897 strlen(id->string),
1898 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001899 if (!id->object)
1900 return NULL;
1901 PyUnicode_InternInPlace(&id->object);
1902 assert(!id->next);
1903 id->next = static_strings;
1904 static_strings = id;
1905 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001906 return id->object;
1907}
1908
1909void
1910_PyUnicode_ClearStaticStrings()
1911{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 _Py_Identifier *tmp, *s = static_strings;
1913 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001914 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001915 tmp = s->next;
1916 s->next = NULL;
1917 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001918 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001919 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001920}
1921
Benjamin Peterson0df54292012-03-26 14:50:32 -04001922/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001923
Victor Stinnerd3f08822012-05-29 12:57:52 +02001924PyObject*
1925_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001926{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001927 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001928 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001929 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001930#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001931 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001932#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001933 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001934 }
Victor Stinner785938e2011-12-11 20:09:03 +01001935 unicode = PyUnicode_New(size, 127);
1936 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001937 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001938 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1939 assert(_PyUnicode_CheckConsistency(unicode, 1));
1940 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001941}
1942
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001943static Py_UCS4
1944kind_maxchar_limit(unsigned int kind)
1945{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001946 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001947 case PyUnicode_1BYTE_KIND:
1948 return 0x80;
1949 case PyUnicode_2BYTE_KIND:
1950 return 0x100;
1951 case PyUnicode_4BYTE_KIND:
1952 return 0x10000;
1953 default:
1954 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001955 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001956 }
1957}
1958
Victor Stinnere6abb482012-05-02 01:15:40 +02001959Py_LOCAL_INLINE(Py_UCS4)
1960align_maxchar(Py_UCS4 maxchar)
1961{
1962 if (maxchar <= 127)
1963 return 127;
1964 else if (maxchar <= 255)
1965 return 255;
1966 else if (maxchar <= 65535)
1967 return 65535;
1968 else
1969 return MAX_UNICODE;
1970}
1971
Victor Stinner702c7342011-10-05 13:50:52 +02001972static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001973_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001974{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001975 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001977
Serhiy Storchaka678db842013-01-26 12:16:36 +02001978 if (size == 0)
1979 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001980 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001981 if (size == 1)
1982 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001983
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001984 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001985 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 if (!res)
1987 return NULL;
1988 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001989 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001991}
1992
Victor Stinnere57b1c02011-09-28 22:20:48 +02001993static PyObject*
1994_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995{
1996 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001998
Serhiy Storchaka678db842013-01-26 12:16:36 +02001999 if (size == 0)
2000 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002001 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002002 if (size == 1)
2003 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002004
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002005 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002006 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 if (!res)
2008 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002009 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002011 else {
2012 _PyUnicode_CONVERT_BYTES(
2013 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2014 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002015 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016 return res;
2017}
2018
Victor Stinnere57b1c02011-09-28 22:20:48 +02002019static PyObject*
2020_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021{
2022 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002024
Serhiy Storchaka678db842013-01-26 12:16:36 +02002025 if (size == 0)
2026 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002027 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002028 if (size == 1)
2029 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002030
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002031 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002032 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002033 if (!res)
2034 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002035 if (max_char < 256)
2036 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2037 PyUnicode_1BYTE_DATA(res));
2038 else if (max_char < 0x10000)
2039 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2040 PyUnicode_2BYTE_DATA(res));
2041 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002042 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002043 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 return res;
2045}
2046
2047PyObject*
2048PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2049{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002050 if (size < 0) {
2051 PyErr_SetString(PyExc_ValueError, "size must be positive");
2052 return NULL;
2053 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002054 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002055 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002056 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002058 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002060 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002061 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002062 PyErr_SetString(PyExc_SystemError, "invalid kind");
2063 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002064 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002065}
2066
Victor Stinnerece58de2012-04-23 23:36:38 +02002067Py_UCS4
2068_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2069{
2070 enum PyUnicode_Kind kind;
2071 void *startptr, *endptr;
2072
2073 assert(PyUnicode_IS_READY(unicode));
2074 assert(0 <= start);
2075 assert(end <= PyUnicode_GET_LENGTH(unicode));
2076 assert(start <= end);
2077
2078 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2079 return PyUnicode_MAX_CHAR_VALUE(unicode);
2080
2081 if (start == end)
2082 return 127;
2083
Victor Stinner94d558b2012-04-27 22:26:58 +02002084 if (PyUnicode_IS_ASCII(unicode))
2085 return 127;
2086
Victor Stinnerece58de2012-04-23 23:36:38 +02002087 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002088 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002089 endptr = (char *)startptr + end * kind;
2090 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002091 switch(kind) {
2092 case PyUnicode_1BYTE_KIND:
2093 return ucs1lib_find_max_char(startptr, endptr);
2094 case PyUnicode_2BYTE_KIND:
2095 return ucs2lib_find_max_char(startptr, endptr);
2096 case PyUnicode_4BYTE_KIND:
2097 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002098 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002099 assert(0);
2100 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002101 }
2102}
2103
Victor Stinner25a4b292011-10-06 12:31:55 +02002104/* Ensure that a string uses the most efficient storage, if it is not the
2105 case: create a new string with of the right kind. Write NULL into *p_unicode
2106 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002107static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002108unicode_adjust_maxchar(PyObject **p_unicode)
2109{
2110 PyObject *unicode, *copy;
2111 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002112 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002113 unsigned int kind;
2114
2115 assert(p_unicode != NULL);
2116 unicode = *p_unicode;
2117 assert(PyUnicode_IS_READY(unicode));
2118 if (PyUnicode_IS_ASCII(unicode))
2119 return;
2120
2121 len = PyUnicode_GET_LENGTH(unicode);
2122 kind = PyUnicode_KIND(unicode);
2123 if (kind == PyUnicode_1BYTE_KIND) {
2124 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002125 max_char = ucs1lib_find_max_char(u, u + len);
2126 if (max_char >= 128)
2127 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002128 }
2129 else if (kind == PyUnicode_2BYTE_KIND) {
2130 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002131 max_char = ucs2lib_find_max_char(u, u + len);
2132 if (max_char >= 256)
2133 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 }
2135 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002136 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002137 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002138 max_char = ucs4lib_find_max_char(u, u + len);
2139 if (max_char >= 0x10000)
2140 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002141 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002142 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002143 if (copy != NULL)
2144 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002145 Py_DECREF(unicode);
2146 *p_unicode = copy;
2147}
2148
Victor Stinner034f6cf2011-09-30 02:26:44 +02002149PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002150_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002151{
Victor Stinner87af4f22011-11-21 23:03:47 +01002152 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002153 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002154
Victor Stinner034f6cf2011-09-30 02:26:44 +02002155 if (!PyUnicode_Check(unicode)) {
2156 PyErr_BadInternalCall();
2157 return NULL;
2158 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002159 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002160 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002161
Victor Stinner87af4f22011-11-21 23:03:47 +01002162 length = PyUnicode_GET_LENGTH(unicode);
2163 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002164 if (!copy)
2165 return NULL;
2166 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2167
Victor Stinner87af4f22011-11-21 23:03:47 +01002168 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2169 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002170 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002171 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002172}
2173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174
Victor Stinnerbc603d12011-10-02 01:00:40 +02002175/* Widen Unicode objects to larger buffers. Don't write terminating null
2176 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177
2178void*
2179_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2180{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002181 Py_ssize_t len;
2182 void *result;
2183 unsigned int skind;
2184
Benjamin Petersonbac79492012-01-14 13:34:47 -05002185 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002186 return NULL;
2187
2188 len = PyUnicode_GET_LENGTH(s);
2189 skind = PyUnicode_KIND(s);
2190 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002191 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 return NULL;
2193 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002194 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002195 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002196 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002197 if (!result)
2198 return PyErr_NoMemory();
2199 assert(skind == PyUnicode_1BYTE_KIND);
2200 _PyUnicode_CONVERT_BYTES(
2201 Py_UCS1, Py_UCS2,
2202 PyUnicode_1BYTE_DATA(s),
2203 PyUnicode_1BYTE_DATA(s) + len,
2204 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002206 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002207 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002208 if (!result)
2209 return PyErr_NoMemory();
2210 if (skind == PyUnicode_2BYTE_KIND) {
2211 _PyUnicode_CONVERT_BYTES(
2212 Py_UCS2, Py_UCS4,
2213 PyUnicode_2BYTE_DATA(s),
2214 PyUnicode_2BYTE_DATA(s) + len,
2215 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002217 else {
2218 assert(skind == PyUnicode_1BYTE_KIND);
2219 _PyUnicode_CONVERT_BYTES(
2220 Py_UCS1, Py_UCS4,
2221 PyUnicode_1BYTE_DATA(s),
2222 PyUnicode_1BYTE_DATA(s) + len,
2223 result);
2224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002226 default:
2227 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002228 }
Victor Stinner01698042011-10-04 00:04:26 +02002229 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002230 return NULL;
2231}
2232
2233static Py_UCS4*
2234as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2235 int copy_null)
2236{
2237 int kind;
2238 void *data;
2239 Py_ssize_t len, targetlen;
2240 if (PyUnicode_READY(string) == -1)
2241 return NULL;
2242 kind = PyUnicode_KIND(string);
2243 data = PyUnicode_DATA(string);
2244 len = PyUnicode_GET_LENGTH(string);
2245 targetlen = len;
2246 if (copy_null)
2247 targetlen++;
2248 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002249 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002250 if (!target) {
2251 PyErr_NoMemory();
2252 return NULL;
2253 }
2254 }
2255 else {
2256 if (targetsize < targetlen) {
2257 PyErr_Format(PyExc_SystemError,
2258 "string is longer than the buffer");
2259 if (copy_null && 0 < targetsize)
2260 target[0] = 0;
2261 return NULL;
2262 }
2263 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002264 if (kind == PyUnicode_1BYTE_KIND) {
2265 Py_UCS1 *start = (Py_UCS1 *) data;
2266 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002268 else if (kind == PyUnicode_2BYTE_KIND) {
2269 Py_UCS2 *start = (Py_UCS2 *) data;
2270 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2271 }
2272 else {
2273 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 if (copy_null)
2277 target[len] = 0;
2278 return target;
2279}
2280
2281Py_UCS4*
2282PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2283 int copy_null)
2284{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002285 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002286 PyErr_BadInternalCall();
2287 return NULL;
2288 }
2289 return as_ucs4(string, target, targetsize, copy_null);
2290}
2291
2292Py_UCS4*
2293PyUnicode_AsUCS4Copy(PyObject *string)
2294{
2295 return as_ucs4(string, NULL, 0, 1);
2296}
2297
2298#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002299
Alexander Belopolsky40018472011-02-26 01:02:56 +00002300PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002301PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002302{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002303 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002305 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002306 PyErr_BadInternalCall();
2307 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002308 }
2309
Martin v. Löwis790465f2008-04-05 20:41:37 +00002310 if (size == -1) {
2311 size = wcslen(w);
2312 }
2313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002314 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002315}
2316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002317#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002318
Victor Stinner15a11362012-10-06 23:48:20 +02002319/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002320 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2321 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2322#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002323
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002324static int
2325unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2326 Py_ssize_t width, Py_ssize_t precision)
2327{
2328 Py_ssize_t length, fill, arglen;
2329 Py_UCS4 maxchar;
2330
2331 if (PyUnicode_READY(str) == -1)
2332 return -1;
2333
2334 length = PyUnicode_GET_LENGTH(str);
2335 if ((precision == -1 || precision >= length)
2336 && width <= length)
2337 return _PyUnicodeWriter_WriteStr(writer, str);
2338
2339 if (precision != -1)
2340 length = Py_MIN(precision, length);
2341
2342 arglen = Py_MAX(length, width);
2343 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2344 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2345 else
2346 maxchar = writer->maxchar;
2347
2348 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2349 return -1;
2350
2351 if (width > length) {
2352 fill = width - length;
2353 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2354 return -1;
2355 writer->pos += fill;
2356 }
2357
2358 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2359 str, 0, length);
2360 writer->pos += length;
2361 return 0;
2362}
2363
2364static int
2365unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2366 Py_ssize_t width, Py_ssize_t precision)
2367{
2368 /* UTF-8 */
2369 Py_ssize_t length;
2370 PyObject *unicode;
2371 int res;
2372
2373 length = strlen(str);
2374 if (precision != -1)
2375 length = Py_MIN(length, precision);
2376 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2377 if (unicode == NULL)
2378 return -1;
2379
2380 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2381 Py_DECREF(unicode);
2382 return res;
2383}
2384
Victor Stinner96865452011-03-01 23:44:09 +00002385static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002386unicode_fromformat_arg(_PyUnicodeWriter *writer,
2387 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002388{
Victor Stinnere215d962012-10-06 23:03:36 +02002389 const char *p;
2390 Py_ssize_t len;
2391 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002392 Py_ssize_t width;
2393 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002394 int longflag;
2395 int longlongflag;
2396 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002397 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002398
2399 p = f;
2400 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002401 zeropad = 0;
2402 if (*f == '0') {
2403 zeropad = 1;
2404 f++;
2405 }
Victor Stinner96865452011-03-01 23:44:09 +00002406
2407 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002408 width = -1;
2409 if (Py_ISDIGIT((unsigned)*f)) {
2410 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002411 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002412 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002413 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002414 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002415 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002416 return NULL;
2417 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002418 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002419 f++;
2420 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002421 }
2422 precision = -1;
2423 if (*f == '.') {
2424 f++;
2425 if (Py_ISDIGIT((unsigned)*f)) {
2426 precision = (*f - '0');
2427 f++;
2428 while (Py_ISDIGIT((unsigned)*f)) {
2429 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2430 PyErr_SetString(PyExc_ValueError,
2431 "precision too big");
2432 return NULL;
2433 }
2434 precision = (precision * 10) + (*f - '0');
2435 f++;
2436 }
2437 }
Victor Stinner96865452011-03-01 23:44:09 +00002438 if (*f == '%') {
2439 /* "%.3%s" => f points to "3" */
2440 f--;
2441 }
2442 }
2443 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002444 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002445 f--;
2446 }
Victor Stinner96865452011-03-01 23:44:09 +00002447
2448 /* Handle %ld, %lu, %lld and %llu. */
2449 longflag = 0;
2450 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002451 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002452 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002453 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002454 longflag = 1;
2455 ++f;
2456 }
2457#ifdef HAVE_LONG_LONG
2458 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002459 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002460 longlongflag = 1;
2461 f += 2;
2462 }
2463#endif
2464 }
2465 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002466 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002467 size_tflag = 1;
2468 ++f;
2469 }
Victor Stinnere215d962012-10-06 23:03:36 +02002470
2471 if (f[1] == '\0')
2472 writer->overallocate = 0;
2473
2474 switch (*f) {
2475 case 'c':
2476 {
2477 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002478 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002479 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002480 "character argument not in range(0x110000)");
2481 return NULL;
2482 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002483 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002484 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002485 break;
2486 }
2487
2488 case 'i':
2489 case 'd':
2490 case 'u':
2491 case 'x':
2492 {
2493 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002494 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002495 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002496
2497 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002498 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002499 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002500 va_arg(*vargs, unsigned long));
2501#ifdef HAVE_LONG_LONG
2502 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002503 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002504 va_arg(*vargs, unsigned PY_LONG_LONG));
2505#endif
2506 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002507 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002508 va_arg(*vargs, size_t));
2509 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002510 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002511 va_arg(*vargs, unsigned int));
2512 }
2513 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002514 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002515 }
2516 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002517 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002518 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002519 va_arg(*vargs, long));
2520#ifdef HAVE_LONG_LONG
2521 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002522 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002523 va_arg(*vargs, PY_LONG_LONG));
2524#endif
2525 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002526 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002527 va_arg(*vargs, Py_ssize_t));
2528 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002529 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002530 va_arg(*vargs, int));
2531 }
2532 assert(len >= 0);
2533
Victor Stinnere215d962012-10-06 23:03:36 +02002534 if (precision < len)
2535 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002536
2537 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002538 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2539 return NULL;
2540
Victor Stinnere215d962012-10-06 23:03:36 +02002541 if (width > precision) {
2542 Py_UCS4 fillchar;
2543 fill = width - precision;
2544 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002545 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2546 return NULL;
2547 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002548 }
Victor Stinner15a11362012-10-06 23:48:20 +02002549 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002550 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002551 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2552 return NULL;
2553 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002554 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002555
Victor Stinner4a587072013-11-19 12:54:53 +01002556 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2557 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002558 break;
2559 }
2560
2561 case 'p':
2562 {
2563 char number[MAX_LONG_LONG_CHARS];
2564
2565 len = sprintf(number, "%p", va_arg(*vargs, void*));
2566 assert(len >= 0);
2567
2568 /* %p is ill-defined: ensure leading 0x. */
2569 if (number[1] == 'X')
2570 number[1] = 'x';
2571 else if (number[1] != 'x') {
2572 memmove(number + 2, number,
2573 strlen(number) + 1);
2574 number[0] = '0';
2575 number[1] = 'x';
2576 len += 2;
2577 }
2578
Victor Stinner4a587072013-11-19 12:54:53 +01002579 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002580 return NULL;
2581 break;
2582 }
2583
2584 case 's':
2585 {
2586 /* UTF-8 */
2587 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002589 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002590 break;
2591 }
2592
2593 case 'U':
2594 {
2595 PyObject *obj = va_arg(*vargs, PyObject *);
2596 assert(obj && _PyUnicode_CHECK(obj));
2597
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002599 return NULL;
2600 break;
2601 }
2602
2603 case 'V':
2604 {
2605 PyObject *obj = va_arg(*vargs, PyObject *);
2606 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002607 if (obj) {
2608 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002609 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002610 return NULL;
2611 }
2612 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002613 assert(str != NULL);
2614 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002615 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002616 }
2617 break;
2618 }
2619
2620 case 'S':
2621 {
2622 PyObject *obj = va_arg(*vargs, PyObject *);
2623 PyObject *str;
2624 assert(obj);
2625 str = PyObject_Str(obj);
2626 if (!str)
2627 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002628 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002629 Py_DECREF(str);
2630 return NULL;
2631 }
2632 Py_DECREF(str);
2633 break;
2634 }
2635
2636 case 'R':
2637 {
2638 PyObject *obj = va_arg(*vargs, PyObject *);
2639 PyObject *repr;
2640 assert(obj);
2641 repr = PyObject_Repr(obj);
2642 if (!repr)
2643 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002644 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002645 Py_DECREF(repr);
2646 return NULL;
2647 }
2648 Py_DECREF(repr);
2649 break;
2650 }
2651
2652 case 'A':
2653 {
2654 PyObject *obj = va_arg(*vargs, PyObject *);
2655 PyObject *ascii;
2656 assert(obj);
2657 ascii = PyObject_ASCII(obj);
2658 if (!ascii)
2659 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002660 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002661 Py_DECREF(ascii);
2662 return NULL;
2663 }
2664 Py_DECREF(ascii);
2665 break;
2666 }
2667
2668 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002669 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002670 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002671 break;
2672
2673 default:
2674 /* if we stumble upon an unknown formatting code, copy the rest
2675 of the format string to the output string. (we cannot just
2676 skip the code, since there's no way to know what's in the
2677 argument list) */
2678 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002679 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002680 return NULL;
2681 f = p+len;
2682 return f;
2683 }
2684
2685 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002686 return f;
2687}
2688
Walter Dörwaldd2034312007-05-18 16:29:38 +00002689PyObject *
2690PyUnicode_FromFormatV(const char *format, va_list vargs)
2691{
Victor Stinnere215d962012-10-06 23:03:36 +02002692 va_list vargs2;
2693 const char *f;
2694 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002695
Victor Stinner8f674cc2013-04-17 23:02:17 +02002696 _PyUnicodeWriter_Init(&writer);
2697 writer.min_length = strlen(format) + 100;
2698 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002699
2700 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2701 Copy it to be able to pass a reference to a subfunction. */
2702 Py_VA_COPY(vargs2, vargs);
2703
2704 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002705 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002706 f = unicode_fromformat_arg(&writer, f, &vargs2);
2707 if (f == NULL)
2708 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002709 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002710 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002711 const char *p;
2712 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002713
Victor Stinnere215d962012-10-06 23:03:36 +02002714 p = f;
2715 do
2716 {
2717 if ((unsigned char)*p > 127) {
2718 PyErr_Format(PyExc_ValueError,
2719 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2720 "string, got a non-ASCII byte: 0x%02x",
2721 (unsigned char)*p);
2722 return NULL;
2723 }
2724 p++;
2725 }
2726 while (*p != '\0' && *p != '%');
2727 len = p - f;
2728
2729 if (*p == '\0')
2730 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002731
2732 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002733 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002734
2735 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002736 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002737 }
Victor Stinnere215d962012-10-06 23:03:36 +02002738 return _PyUnicodeWriter_Finish(&writer);
2739
2740 fail:
2741 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002742 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002743}
2744
Walter Dörwaldd2034312007-05-18 16:29:38 +00002745PyObject *
2746PyUnicode_FromFormat(const char *format, ...)
2747{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002748 PyObject* ret;
2749 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002750
2751#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002752 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002753#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002754 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002755#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002756 ret = PyUnicode_FromFormatV(format, vargs);
2757 va_end(vargs);
2758 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002759}
2760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002761#ifdef HAVE_WCHAR_H
2762
Victor Stinner5593d8a2010-10-02 11:11:27 +00002763/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2764 convert a Unicode object to a wide character string.
2765
Victor Stinnerd88d9832011-09-06 02:00:05 +02002766 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002767 character) required to convert the unicode object. Ignore size argument.
2768
Victor Stinnerd88d9832011-09-06 02:00:05 +02002769 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002770 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002771 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002772static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002773unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002774 wchar_t *w,
2775 Py_ssize_t size)
2776{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002777 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002778 const wchar_t *wstr;
2779
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002780 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 if (wstr == NULL)
2782 return -1;
2783
Victor Stinner5593d8a2010-10-02 11:11:27 +00002784 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002785 if (size > res)
2786 size = res + 1;
2787 else
2788 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002790 return res;
2791 }
2792 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002794}
2795
2796Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002797PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002798 wchar_t *w,
2799 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002800{
2801 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002802 PyErr_BadInternalCall();
2803 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002804 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002805 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002806}
2807
Victor Stinner137c34c2010-09-29 10:25:54 +00002808wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002809PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002810 Py_ssize_t *size)
2811{
2812 wchar_t* buffer;
2813 Py_ssize_t buflen;
2814
2815 if (unicode == NULL) {
2816 PyErr_BadInternalCall();
2817 return NULL;
2818 }
2819
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002820 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 if (buflen == -1)
2822 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002823 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002824 if (buffer == NULL) {
2825 PyErr_NoMemory();
2826 return NULL;
2827 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002828 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002829 if (buflen == -1) {
2830 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002831 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002832 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002833 if (size != NULL)
2834 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002835 return buffer;
2836}
2837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002838#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002839
Alexander Belopolsky40018472011-02-26 01:02:56 +00002840PyObject *
2841PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002842{
Victor Stinner8faf8212011-12-08 22:14:11 +01002843 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002844 PyErr_SetString(PyExc_ValueError,
2845 "chr() arg not in range(0x110000)");
2846 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002847 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002848
Victor Stinner985a82a2014-01-03 12:53:47 +01002849 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002850}
2851
Alexander Belopolsky40018472011-02-26 01:02:56 +00002852PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002853PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002854{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002855 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002856 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002857 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002858 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002859 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 Py_INCREF(obj);
2861 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002862 }
2863 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002864 /* For a Unicode subtype that's not a Unicode object,
2865 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002866 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002867 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002868 PyErr_Format(PyExc_TypeError,
2869 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002870 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002871 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002872}
2873
Alexander Belopolsky40018472011-02-26 01:02:56 +00002874PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002875PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002876 const char *encoding,
2877 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002878{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002879 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002880 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002881
Guido van Rossumd57fd912000-03-10 22:53:23 +00002882 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002883 PyErr_BadInternalCall();
2884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002885 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002886
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002887 /* Decoding bytes objects is the most common case and should be fast */
2888 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002889 if (PyBytes_GET_SIZE(obj) == 0)
2890 _Py_RETURN_UNICODE_EMPTY();
2891 v = PyUnicode_Decode(
2892 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2893 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002894 return v;
2895 }
2896
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002897 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002898 PyErr_SetString(PyExc_TypeError,
2899 "decoding str is not supported");
2900 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002901 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002902
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002903 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2904 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2905 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002906 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002907 Py_TYPE(obj)->tp_name);
2908 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002909 }
Tim Petersced69f82003-09-16 20:30:58 +00002910
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002911 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002912 PyBuffer_Release(&buffer);
2913 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002914 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002915
Serhiy Storchaka05997252013-01-26 12:14:02 +02002916 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002917 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002918 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002919}
2920
Victor Stinner600d3be2010-06-10 12:00:55 +00002921/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002922 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2923 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002924int
2925_Py_normalize_encoding(const char *encoding,
2926 char *lower,
2927 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002928{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002929 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002930 char *l;
2931 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002932
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002933 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002934 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002935 if (lower_len < 6)
2936 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002937 strcpy(lower, "utf-8");
2938 return 1;
2939 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002940 e = encoding;
2941 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002942 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002943 while (*e) {
2944 if (l == l_end)
2945 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002946 if (Py_ISUPPER(*e)) {
2947 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002948 }
2949 else if (*e == '_') {
2950 *l++ = '-';
2951 e++;
2952 }
2953 else {
2954 *l++ = *e++;
2955 }
2956 }
2957 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002958 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002959}
2960
Alexander Belopolsky40018472011-02-26 01:02:56 +00002961PyObject *
2962PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002963 Py_ssize_t size,
2964 const char *encoding,
2965 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002966{
2967 PyObject *buffer = NULL, *unicode;
2968 Py_buffer info;
2969 char lower[11]; /* Enough for any encoding shortcut */
2970
Fred Drakee4315f52000-05-09 19:53:39 +00002971 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002972 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002973 if ((strcmp(lower, "utf-8") == 0) ||
2974 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002975 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002976 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002977 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01002978 (strcmp(lower, "iso-8859-1") == 0) ||
2979 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002980 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002981#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002982 else if (strcmp(lower, "mbcs") == 0)
2983 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002984#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002985 else if (strcmp(lower, "ascii") == 0)
2986 return PyUnicode_DecodeASCII(s, size, errors);
2987 else if (strcmp(lower, "utf-16") == 0)
2988 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2989 else if (strcmp(lower, "utf-32") == 0)
2990 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2991 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002992
2993 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002994 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002995 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002996 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002997 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002998 if (buffer == NULL)
2999 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003000 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003001 if (unicode == NULL)
3002 goto onError;
3003 if (!PyUnicode_Check(unicode)) {
3004 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003005 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3006 "use codecs.decode() to decode to arbitrary types",
3007 encoding,
3008 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009 Py_DECREF(unicode);
3010 goto onError;
3011 }
3012 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003013 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003014
Benjamin Peterson29060642009-01-31 22:14:21 +00003015 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003016 Py_XDECREF(buffer);
3017 return NULL;
3018}
3019
Alexander Belopolsky40018472011-02-26 01:02:56 +00003020PyObject *
3021PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003022 const char *encoding,
3023 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003024{
3025 PyObject *v;
3026
3027 if (!PyUnicode_Check(unicode)) {
3028 PyErr_BadArgument();
3029 goto onError;
3030 }
3031
3032 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003033 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003034
3035 /* Decode via the codec registry */
3036 v = PyCodec_Decode(unicode, encoding, errors);
3037 if (v == NULL)
3038 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003039 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003040
Benjamin Peterson29060642009-01-31 22:14:21 +00003041 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003042 return NULL;
3043}
3044
Alexander Belopolsky40018472011-02-26 01:02:56 +00003045PyObject *
3046PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003047 const char *encoding,
3048 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003049{
3050 PyObject *v;
3051
3052 if (!PyUnicode_Check(unicode)) {
3053 PyErr_BadArgument();
3054 goto onError;
3055 }
3056
3057 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003058 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003059
3060 /* Decode via the codec registry */
3061 v = PyCodec_Decode(unicode, encoding, errors);
3062 if (v == NULL)
3063 goto onError;
3064 if (!PyUnicode_Check(v)) {
3065 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003066 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3067 "use codecs.decode() to decode to arbitrary types",
3068 encoding,
3069 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003070 Py_DECREF(v);
3071 goto onError;
3072 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003073 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003074
Benjamin Peterson29060642009-01-31 22:14:21 +00003075 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003076 return NULL;
3077}
3078
Alexander Belopolsky40018472011-02-26 01:02:56 +00003079PyObject *
3080PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003081 Py_ssize_t size,
3082 const char *encoding,
3083 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084{
3085 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003086
Guido van Rossumd57fd912000-03-10 22:53:23 +00003087 unicode = PyUnicode_FromUnicode(s, size);
3088 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3091 Py_DECREF(unicode);
3092 return v;
3093}
3094
Alexander Belopolsky40018472011-02-26 01:02:56 +00003095PyObject *
3096PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003097 const char *encoding,
3098 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003099{
3100 PyObject *v;
3101
3102 if (!PyUnicode_Check(unicode)) {
3103 PyErr_BadArgument();
3104 goto onError;
3105 }
3106
3107 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003108 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003109
3110 /* Encode via the codec registry */
3111 v = PyCodec_Encode(unicode, encoding, errors);
3112 if (v == NULL)
3113 goto onError;
3114 return v;
3115
Benjamin Peterson29060642009-01-31 22:14:21 +00003116 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003117 return NULL;
3118}
3119
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003120static size_t
3121wcstombs_errorpos(const wchar_t *wstr)
3122{
3123 size_t len;
3124#if SIZEOF_WCHAR_T == 2
3125 wchar_t buf[3];
3126#else
3127 wchar_t buf[2];
3128#endif
3129 char outbuf[MB_LEN_MAX];
3130 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003131
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003132#if SIZEOF_WCHAR_T == 2
3133 buf[2] = 0;
3134#else
3135 buf[1] = 0;
3136#endif
3137 start = wstr;
3138 while (*wstr != L'\0')
3139 {
3140 previous = wstr;
3141#if SIZEOF_WCHAR_T == 2
3142 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3143 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3144 {
3145 buf[0] = wstr[0];
3146 buf[1] = wstr[1];
3147 wstr += 2;
3148 }
3149 else {
3150 buf[0] = *wstr;
3151 buf[1] = 0;
3152 wstr++;
3153 }
3154#else
3155 buf[0] = *wstr;
3156 wstr++;
3157#endif
3158 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003159 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003160 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003161 }
3162
3163 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003164 return 0;
3165}
3166
Victor Stinner1b579672011-12-17 05:47:23 +01003167static int
3168locale_error_handler(const char *errors, int *surrogateescape)
3169{
3170 if (errors == NULL) {
3171 *surrogateescape = 0;
3172 return 0;
3173 }
3174
3175 if (strcmp(errors, "strict") == 0) {
3176 *surrogateescape = 0;
3177 return 0;
3178 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003179 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003180 *surrogateescape = 1;
3181 return 0;
3182 }
3183 PyErr_Format(PyExc_ValueError,
3184 "only 'strict' and 'surrogateescape' error handlers "
3185 "are supported, not '%s'",
3186 errors);
3187 return -1;
3188}
3189
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003190PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003191PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003192{
3193 Py_ssize_t wlen, wlen2;
3194 wchar_t *wstr;
3195 PyObject *bytes = NULL;
3196 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003197 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 PyObject *exc;
3199 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003200 int surrogateescape;
3201
3202 if (locale_error_handler(errors, &surrogateescape) < 0)
3203 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003204
3205 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3206 if (wstr == NULL)
3207 return NULL;
3208
3209 wlen2 = wcslen(wstr);
3210 if (wlen2 != wlen) {
3211 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003212 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003213 return NULL;
3214 }
3215
3216 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003217 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003218 char *str;
3219
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003220 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003221 if (str == NULL) {
3222 if (error_pos == (size_t)-1) {
3223 PyErr_NoMemory();
3224 PyMem_Free(wstr);
3225 return NULL;
3226 }
3227 else {
3228 goto encode_error;
3229 }
3230 }
3231 PyMem_Free(wstr);
3232
3233 bytes = PyBytes_FromString(str);
3234 PyMem_Free(str);
3235 }
3236 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003237 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003238 size_t len, len2;
3239
3240 len = wcstombs(NULL, wstr, 0);
3241 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003242 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003243 goto encode_error;
3244 }
3245
3246 bytes = PyBytes_FromStringAndSize(NULL, len);
3247 if (bytes == NULL) {
3248 PyMem_Free(wstr);
3249 return NULL;
3250 }
3251
3252 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3253 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003254 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003255 goto encode_error;
3256 }
3257 PyMem_Free(wstr);
3258 }
3259 return bytes;
3260
3261encode_error:
3262 errmsg = strerror(errno);
3263 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003264
3265 if (error_pos == (size_t)-1)
3266 error_pos = wcstombs_errorpos(wstr);
3267
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003268 PyMem_Free(wstr);
3269 Py_XDECREF(bytes);
3270
Victor Stinner2f197072011-12-17 07:08:30 +01003271 if (errmsg != NULL) {
3272 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003273 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003274 if (wstr != NULL) {
3275 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003276 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003277 } else
3278 errmsg = NULL;
3279 }
3280 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003281 reason = PyUnicode_FromString(
3282 "wcstombs() encountered an unencodable "
3283 "wide character");
3284 if (reason == NULL)
3285 return NULL;
3286
3287 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3288 "locale", unicode,
3289 (Py_ssize_t)error_pos,
3290 (Py_ssize_t)(error_pos+1),
3291 reason);
3292 Py_DECREF(reason);
3293 if (exc != NULL) {
3294 PyCodec_StrictErrors(exc);
3295 Py_XDECREF(exc);
3296 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003297 return NULL;
3298}
3299
Victor Stinnerad158722010-10-27 00:25:46 +00003300PyObject *
3301PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003302{
Victor Stinner99b95382011-07-04 14:23:54 +02003303#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003304 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003305#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003306 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003307#else
Victor Stinner793b5312011-04-27 00:24:21 +02003308 PyInterpreterState *interp = PyThreadState_GET()->interp;
3309 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3310 cannot use it to encode and decode filenames before it is loaded. Load
3311 the Python codec requires to encode at least its own filename. Use the C
3312 version of the locale codec until the codec registry is initialized and
3313 the Python codec is loaded.
3314
3315 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3316 cannot only rely on it: check also interp->fscodec_initialized for
3317 subinterpreters. */
3318 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003319 return PyUnicode_AsEncodedString(unicode,
3320 Py_FileSystemDefaultEncoding,
3321 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003322 }
3323 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003324 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003325 }
Victor Stinnerad158722010-10-27 00:25:46 +00003326#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003327}
3328
Alexander Belopolsky40018472011-02-26 01:02:56 +00003329PyObject *
3330PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003331 const char *encoding,
3332 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333{
3334 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003335 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003336
Guido van Rossumd57fd912000-03-10 22:53:23 +00003337 if (!PyUnicode_Check(unicode)) {
3338 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003339 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003340 }
Fred Drakee4315f52000-05-09 19:53:39 +00003341
Fred Drakee4315f52000-05-09 19:53:39 +00003342 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003343 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003344 if ((strcmp(lower, "utf-8") == 0) ||
3345 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003346 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003347 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003348 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003349 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003350 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003351 }
Victor Stinner37296e82010-06-10 13:36:23 +00003352 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003353 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003354 (strcmp(lower, "iso-8859-1") == 0) ||
3355 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003357#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003358 else if (strcmp(lower, "mbcs") == 0)
3359 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003360#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003361 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003363 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003364
3365 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003366 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003367 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003368 return NULL;
3369
3370 /* The normal path */
3371 if (PyBytes_Check(v))
3372 return v;
3373
3374 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003375 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003376 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003378
3379 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003380 "encoder %s returned bytearray instead of bytes; "
3381 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003382 encoding);
3383 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003384 Py_DECREF(v);
3385 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003386 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003387
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003388 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3389 Py_DECREF(v);
3390 return b;
3391 }
3392
3393 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003394 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3395 "use codecs.encode() to encode to arbitrary types",
3396 encoding,
3397 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003398 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003399 return NULL;
3400}
3401
Alexander Belopolsky40018472011-02-26 01:02:56 +00003402PyObject *
3403PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003404 const char *encoding,
3405 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003406{
3407 PyObject *v;
3408
3409 if (!PyUnicode_Check(unicode)) {
3410 PyErr_BadArgument();
3411 goto onError;
3412 }
3413
3414 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003415 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003416
3417 /* Encode via the codec registry */
3418 v = PyCodec_Encode(unicode, encoding, errors);
3419 if (v == NULL)
3420 goto onError;
3421 if (!PyUnicode_Check(v)) {
3422 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003423 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3424 "use codecs.encode() to encode to arbitrary types",
3425 encoding,
3426 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003427 Py_DECREF(v);
3428 goto onError;
3429 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003430 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003431
Benjamin Peterson29060642009-01-31 22:14:21 +00003432 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003433 return NULL;
3434}
3435
Victor Stinner2f197072011-12-17 07:08:30 +01003436static size_t
3437mbstowcs_errorpos(const char *str, size_t len)
3438{
3439#ifdef HAVE_MBRTOWC
3440 const char *start = str;
3441 mbstate_t mbs;
3442 size_t converted;
3443 wchar_t ch;
3444
3445 memset(&mbs, 0, sizeof mbs);
3446 while (len)
3447 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003448 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003449 if (converted == 0)
3450 /* Reached end of string */
3451 break;
3452 if (converted == (size_t)-1 || converted == (size_t)-2) {
3453 /* Conversion error or incomplete character */
3454 return str - start;
3455 }
3456 else {
3457 str += converted;
3458 len -= converted;
3459 }
3460 }
3461 /* failed to find the undecodable byte sequence */
3462 return 0;
3463#endif
3464 return 0;
3465}
3466
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003467PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003468PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003469 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003470{
3471 wchar_t smallbuf[256];
3472 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3473 wchar_t *wstr;
3474 size_t wlen, wlen2;
3475 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003476 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003477 size_t error_pos;
3478 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003479 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3480 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003481
3482 if (locale_error_handler(errors, &surrogateescape) < 0)
3483 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003484
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003485 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3486 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003487 return NULL;
3488 }
3489
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003490 if (surrogateescape) {
3491 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003492 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003493 if (wstr == NULL) {
3494 if (wlen == (size_t)-1)
3495 PyErr_NoMemory();
3496 else
3497 PyErr_SetFromErrno(PyExc_OSError);
3498 return NULL;
3499 }
3500
3501 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003502 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003503 }
3504 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003505 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506#ifndef HAVE_BROKEN_MBSTOWCS
3507 wlen = mbstowcs(NULL, str, 0);
3508#else
3509 wlen = len;
3510#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003511 if (wlen == (size_t)-1)
3512 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003513 if (wlen+1 <= smallbuf_len) {
3514 wstr = smallbuf;
3515 }
3516 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003517 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003518 if (!wstr)
3519 return PyErr_NoMemory();
3520 }
3521
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003522 wlen2 = mbstowcs(wstr, str, wlen+1);
3523 if (wlen2 == (size_t)-1) {
3524 if (wstr != smallbuf)
3525 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003526 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003527 }
3528#ifdef HAVE_BROKEN_MBSTOWCS
3529 assert(wlen2 == wlen);
3530#endif
3531 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3532 if (wstr != smallbuf)
3533 PyMem_Free(wstr);
3534 }
3535 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003536
3537decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003538 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003539 errmsg = strerror(errno);
3540 assert(errmsg != NULL);
3541
3542 error_pos = mbstowcs_errorpos(str, len);
3543 if (errmsg != NULL) {
3544 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003545 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003546 if (wstr != NULL) {
3547 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003548 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003549 }
Victor Stinner2f197072011-12-17 07:08:30 +01003550 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003551 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003552 reason = PyUnicode_FromString(
3553 "mbstowcs() encountered an invalid multibyte sequence");
3554 if (reason == NULL)
3555 return NULL;
3556
3557 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3558 "locale", str, len,
3559 (Py_ssize_t)error_pos,
3560 (Py_ssize_t)(error_pos+1),
3561 reason);
3562 Py_DECREF(reason);
3563 if (exc != NULL) {
3564 PyCodec_StrictErrors(exc);
3565 Py_XDECREF(exc);
3566 }
3567 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003568}
3569
3570PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003571PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003572{
3573 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003574 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003575}
3576
3577
3578PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003579PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003580 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003581 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3582}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003583
Christian Heimes5894ba72007-11-04 11:43:14 +00003584PyObject*
3585PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3586{
Victor Stinner99b95382011-07-04 14:23:54 +02003587#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003588 return PyUnicode_DecodeMBCS(s, size, NULL);
3589#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003590 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003591#else
Victor Stinner793b5312011-04-27 00:24:21 +02003592 PyInterpreterState *interp = PyThreadState_GET()->interp;
3593 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3594 cannot use it to encode and decode filenames before it is loaded. Load
3595 the Python codec requires to encode at least its own filename. Use the C
3596 version of the locale codec until the codec registry is initialized and
3597 the Python codec is loaded.
3598
3599 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3600 cannot only rely on it: check also interp->fscodec_initialized for
3601 subinterpreters. */
3602 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003603 return PyUnicode_Decode(s, size,
3604 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003605 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003606 }
3607 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003608 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003609 }
Victor Stinnerad158722010-10-27 00:25:46 +00003610#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003611}
3612
Martin v. Löwis011e8422009-05-05 04:43:17 +00003613
3614int
3615PyUnicode_FSConverter(PyObject* arg, void* addr)
3616{
3617 PyObject *output = NULL;
3618 Py_ssize_t size;
3619 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003620 if (arg == NULL) {
3621 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003622 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003623 return 1;
3624 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003625 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003626 output = arg;
3627 Py_INCREF(output);
3628 }
3629 else {
3630 arg = PyUnicode_FromObject(arg);
3631 if (!arg)
3632 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003633 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003634 Py_DECREF(arg);
3635 if (!output)
3636 return 0;
3637 if (!PyBytes_Check(output)) {
3638 Py_DECREF(output);
3639 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3640 return 0;
3641 }
3642 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003643 size = PyBytes_GET_SIZE(output);
3644 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003645 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003646 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003647 Py_DECREF(output);
3648 return 0;
3649 }
3650 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003651 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652}
3653
3654
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003655int
3656PyUnicode_FSDecoder(PyObject* arg, void* addr)
3657{
3658 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003659 if (arg == NULL) {
3660 Py_DECREF(*(PyObject**)addr);
3661 return 1;
3662 }
3663 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003664 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003665 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003666 output = arg;
3667 Py_INCREF(output);
3668 }
3669 else {
3670 arg = PyBytes_FromObject(arg);
3671 if (!arg)
3672 return 0;
3673 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3674 PyBytes_GET_SIZE(arg));
3675 Py_DECREF(arg);
3676 if (!output)
3677 return 0;
3678 if (!PyUnicode_Check(output)) {
3679 Py_DECREF(output);
3680 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3681 return 0;
3682 }
3683 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003684 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003685 Py_DECREF(output);
3686 return 0;
3687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003688 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003689 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003690 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003691 Py_DECREF(output);
3692 return 0;
3693 }
3694 *(PyObject**)addr = output;
3695 return Py_CLEANUP_SUPPORTED;
3696}
3697
3698
Martin v. Löwis5b222132007-06-10 09:51:05 +00003699char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003700PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003701{
Christian Heimesf3863112007-11-22 07:46:41 +00003702 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003703
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003704 if (!PyUnicode_Check(unicode)) {
3705 PyErr_BadArgument();
3706 return NULL;
3707 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003708 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003709 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003710
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003711 if (PyUnicode_UTF8(unicode) == NULL) {
3712 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003713 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3714 if (bytes == NULL)
3715 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003716 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3717 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003718 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719 Py_DECREF(bytes);
3720 return NULL;
3721 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003722 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3723 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3724 PyBytes_AS_STRING(bytes),
3725 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726 Py_DECREF(bytes);
3727 }
3728
3729 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003730 *psize = PyUnicode_UTF8_LENGTH(unicode);
3731 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003732}
3733
3734char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003735PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003736{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003737 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3738}
3739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003740Py_UNICODE *
3741PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3742{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 const unsigned char *one_byte;
3744#if SIZEOF_WCHAR_T == 4
3745 const Py_UCS2 *two_bytes;
3746#else
3747 const Py_UCS4 *four_bytes;
3748 const Py_UCS4 *ucs4_end;
3749 Py_ssize_t num_surrogates;
3750#endif
3751 wchar_t *w;
3752 wchar_t *wchar_end;
3753
3754 if (!PyUnicode_Check(unicode)) {
3755 PyErr_BadArgument();
3756 return NULL;
3757 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003758 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003759 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003760 assert(_PyUnicode_KIND(unicode) != 0);
3761 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003762
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003763 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003765 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3766 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767 num_surrogates = 0;
3768
3769 for (; four_bytes < ucs4_end; ++four_bytes) {
3770 if (*four_bytes > 0xFFFF)
3771 ++num_surrogates;
3772 }
3773
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003774 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3775 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3776 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777 PyErr_NoMemory();
3778 return NULL;
3779 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003780 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003781
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003782 w = _PyUnicode_WSTR(unicode);
3783 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3784 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3786 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003787 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003789 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3790 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 }
3792 else
3793 *w = *four_bytes;
3794
3795 if (w > wchar_end) {
3796 assert(0 && "Miscalculated string end");
3797 }
3798 }
3799 *w = 0;
3800#else
3801 /* sizeof(wchar_t) == 4 */
3802 Py_FatalError("Impossible unicode object state, wstr and str "
3803 "should share memory already.");
3804 return NULL;
3805#endif
3806 }
3807 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003808 if ((size_t)_PyUnicode_LENGTH(unicode) >
3809 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3810 PyErr_NoMemory();
3811 return NULL;
3812 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003813 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3814 (_PyUnicode_LENGTH(unicode) + 1));
3815 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816 PyErr_NoMemory();
3817 return NULL;
3818 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003819 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3820 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3821 w = _PyUnicode_WSTR(unicode);
3822 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003824 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3825 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826 for (; w < wchar_end; ++one_byte, ++w)
3827 *w = *one_byte;
3828 /* null-terminate the wstr */
3829 *w = 0;
3830 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003831 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003832#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003833 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834 for (; w < wchar_end; ++two_bytes, ++w)
3835 *w = *two_bytes;
3836 /* null-terminate the wstr */
3837 *w = 0;
3838#else
3839 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 PyObject_FREE(_PyUnicode_WSTR(unicode));
3841 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 Py_FatalError("Impossible unicode object state, wstr "
3843 "and str should share memory already.");
3844 return NULL;
3845#endif
3846 }
3847 else {
3848 assert(0 && "This should never happen.");
3849 }
3850 }
3851 }
3852 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003853 *size = PyUnicode_WSTR_LENGTH(unicode);
3854 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003855}
3856
Alexander Belopolsky40018472011-02-26 01:02:56 +00003857Py_UNICODE *
3858PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003859{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003861}
3862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863
Alexander Belopolsky40018472011-02-26 01:02:56 +00003864Py_ssize_t
3865PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003866{
3867 if (!PyUnicode_Check(unicode)) {
3868 PyErr_BadArgument();
3869 goto onError;
3870 }
3871 return PyUnicode_GET_SIZE(unicode);
3872
Benjamin Peterson29060642009-01-31 22:14:21 +00003873 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003874 return -1;
3875}
3876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003877Py_ssize_t
3878PyUnicode_GetLength(PyObject *unicode)
3879{
Victor Stinner07621332012-06-16 04:53:46 +02003880 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881 PyErr_BadArgument();
3882 return -1;
3883 }
Victor Stinner07621332012-06-16 04:53:46 +02003884 if (PyUnicode_READY(unicode) == -1)
3885 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003886 return PyUnicode_GET_LENGTH(unicode);
3887}
3888
3889Py_UCS4
3890PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3891{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003892 void *data;
3893 int kind;
3894
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003895 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3896 PyErr_BadArgument();
3897 return (Py_UCS4)-1;
3898 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003899 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003900 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003901 return (Py_UCS4)-1;
3902 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003903 data = PyUnicode_DATA(unicode);
3904 kind = PyUnicode_KIND(unicode);
3905 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906}
3907
3908int
3909PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3910{
3911 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003912 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913 return -1;
3914 }
Victor Stinner488fa492011-12-12 00:01:39 +01003915 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003916 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003917 PyErr_SetString(PyExc_IndexError, "string index out of range");
3918 return -1;
3919 }
Victor Stinner488fa492011-12-12 00:01:39 +01003920 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003921 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003922 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3923 PyErr_SetString(PyExc_ValueError, "character out of range");
3924 return -1;
3925 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3927 index, ch);
3928 return 0;
3929}
3930
Alexander Belopolsky40018472011-02-26 01:02:56 +00003931const char *
3932PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003933{
Victor Stinner42cb4622010-09-01 19:39:01 +00003934 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003935}
3936
Victor Stinner554f3f02010-06-16 23:33:54 +00003937/* create or adjust a UnicodeDecodeError */
3938static void
3939make_decode_exception(PyObject **exceptionObject,
3940 const char *encoding,
3941 const char *input, Py_ssize_t length,
3942 Py_ssize_t startpos, Py_ssize_t endpos,
3943 const char *reason)
3944{
3945 if (*exceptionObject == NULL) {
3946 *exceptionObject = PyUnicodeDecodeError_Create(
3947 encoding, input, length, startpos, endpos, reason);
3948 }
3949 else {
3950 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3951 goto onError;
3952 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3953 goto onError;
3954 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3955 goto onError;
3956 }
3957 return;
3958
3959onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003960 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003961}
3962
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003963#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003964/* error handling callback helper:
3965 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003966 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003967 and adjust various state variables.
3968 return 0 on success, -1 on error
3969*/
3970
Alexander Belopolsky40018472011-02-26 01:02:56 +00003971static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003972unicode_decode_call_errorhandler_wchar(
3973 const char *errors, PyObject **errorHandler,
3974 const char *encoding, const char *reason,
3975 const char **input, const char **inend, Py_ssize_t *startinpos,
3976 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3977 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003978{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003979 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003980
3981 PyObject *restuple = NULL;
3982 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003983 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003984 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003985 Py_ssize_t requiredsize;
3986 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003987 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003988 wchar_t *repwstr;
3989 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003990
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003991 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3992 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01003993
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003994 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003995 *errorHandler = PyCodec_LookupError(errors);
3996 if (*errorHandler == NULL)
3997 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003998 }
3999
Victor Stinner554f3f02010-06-16 23:33:54 +00004000 make_decode_exception(exceptionObject,
4001 encoding,
4002 *input, *inend - *input,
4003 *startinpos, *endinpos,
4004 reason);
4005 if (*exceptionObject == NULL)
4006 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004007
4008 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4009 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004010 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004011 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004012 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004013 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014 }
4015 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004016 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004017
4018 /* Copy back the bytes variables, which might have been modified by the
4019 callback */
4020 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4021 if (!inputobj)
4022 goto onError;
4023 if (!PyBytes_Check(inputobj)) {
4024 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4025 }
4026 *input = PyBytes_AS_STRING(inputobj);
4027 insize = PyBytes_GET_SIZE(inputobj);
4028 *inend = *input + insize;
4029 /* we can DECREF safely, as the exception has another reference,
4030 so the object won't go away. */
4031 Py_DECREF(inputobj);
4032
4033 if (newpos<0)
4034 newpos = insize+newpos;
4035 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004036 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004037 goto onError;
4038 }
4039
4040 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4041 if (repwstr == NULL)
4042 goto onError;
4043 /* need more space? (at least enough for what we
4044 have+the replacement+the rest of the string (starting
4045 at the new input position), so we won't have to check space
4046 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004047 requiredsize = *outpos;
4048 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4049 goto overflow;
4050 requiredsize += repwlen;
4051 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4052 goto overflow;
4053 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004054 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004055 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004056 requiredsize = 2*outsize;
4057 if (unicode_resize(output, requiredsize) < 0)
4058 goto onError;
4059 }
4060 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4061 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004062 *endinpos = newpos;
4063 *inptr = *input + newpos;
4064
4065 /* we made it! */
4066 Py_XDECREF(restuple);
4067 return 0;
4068
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004069 overflow:
4070 PyErr_SetString(PyExc_OverflowError,
4071 "decoded result is too long for a Python string");
4072
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004073 onError:
4074 Py_XDECREF(restuple);
4075 return -1;
4076}
4077#endif /* HAVE_MBCS */
4078
4079static int
4080unicode_decode_call_errorhandler_writer(
4081 const char *errors, PyObject **errorHandler,
4082 const char *encoding, const char *reason,
4083 const char **input, const char **inend, Py_ssize_t *startinpos,
4084 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4085 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4086{
4087 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4088
4089 PyObject *restuple = NULL;
4090 PyObject *repunicode = NULL;
4091 Py_ssize_t insize;
4092 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004093 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004094 PyObject *inputobj = NULL;
4095
4096 if (*errorHandler == NULL) {
4097 *errorHandler = PyCodec_LookupError(errors);
4098 if (*errorHandler == NULL)
4099 goto onError;
4100 }
4101
4102 make_decode_exception(exceptionObject,
4103 encoding,
4104 *input, *inend - *input,
4105 *startinpos, *endinpos,
4106 reason);
4107 if (*exceptionObject == NULL)
4108 goto onError;
4109
4110 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4111 if (restuple == NULL)
4112 goto onError;
4113 if (!PyTuple_Check(restuple)) {
4114 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4115 goto onError;
4116 }
4117 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004118 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004119
4120 /* Copy back the bytes variables, which might have been modified by the
4121 callback */
4122 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4123 if (!inputobj)
4124 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004125 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004126 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004127 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004128 *input = PyBytes_AS_STRING(inputobj);
4129 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004130 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004131 /* we can DECREF safely, as the exception has another reference,
4132 so the object won't go away. */
4133 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004134
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004136 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004137 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004138 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004139 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004140 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004141
Victor Stinner8f674cc2013-04-17 23:02:17 +02004142 if (PyUnicode_READY(repunicode) < 0)
4143 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004144 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004145 if (replen > 1) {
4146 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004147 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004148 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4149 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4150 goto onError;
4151 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004152 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004153 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004154
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004155 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004156 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004157
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004158 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004159 Py_XDECREF(restuple);
4160 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004161
Benjamin Peterson29060642009-01-31 22:14:21 +00004162 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004163 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004164 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165}
4166
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004167/* --- UTF-7 Codec -------------------------------------------------------- */
4168
Antoine Pitrou244651a2009-05-04 18:56:13 +00004169/* See RFC2152 for details. We encode conservatively and decode liberally. */
4170
4171/* Three simple macros defining base-64. */
4172
4173/* Is c a base-64 character? */
4174
4175#define IS_BASE64(c) \
4176 (((c) >= 'A' && (c) <= 'Z') || \
4177 ((c) >= 'a' && (c) <= 'z') || \
4178 ((c) >= '0' && (c) <= '9') || \
4179 (c) == '+' || (c) == '/')
4180
4181/* given that c is a base-64 character, what is its base-64 value? */
4182
4183#define FROM_BASE64(c) \
4184 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4185 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4186 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4187 (c) == '+' ? 62 : 63)
4188
4189/* What is the base-64 character of the bottom 6 bits of n? */
4190
4191#define TO_BASE64(n) \
4192 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4193
4194/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4195 * decoded as itself. We are permissive on decoding; the only ASCII
4196 * byte not decoding to itself is the + which begins a base64
4197 * string. */
4198
4199#define DECODE_DIRECT(c) \
4200 ((c) <= 127 && (c) != '+')
4201
4202/* The UTF-7 encoder treats ASCII characters differently according to
4203 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4204 * the above). See RFC2152. This array identifies these different
4205 * sets:
4206 * 0 : "Set D"
4207 * alphanumeric and '(),-./:?
4208 * 1 : "Set O"
4209 * !"#$%&*;<=>@[]^_`{|}
4210 * 2 : "whitespace"
4211 * ht nl cr sp
4212 * 3 : special (must be base64 encoded)
4213 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4214 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004215
Tim Petersced69f82003-09-16 20:30:58 +00004216static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004217char utf7_category[128] = {
4218/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4219 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4220/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4221 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4222/* sp ! " # $ % & ' ( ) * + , - . / */
4223 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4224/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4225 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4226/* @ A B C D E F G H I J K L M N O */
4227 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4228/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4229 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4230/* ` a b c d e f g h i j k l m n o */
4231 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4232/* p q r s t u v w x y z { | } ~ del */
4233 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004234};
4235
Antoine Pitrou244651a2009-05-04 18:56:13 +00004236/* ENCODE_DIRECT: this character should be encoded as itself. The
4237 * answer depends on whether we are encoding set O as itself, and also
4238 * on whether we are encoding whitespace as itself. RFC2152 makes it
4239 * clear that the answers to these questions vary between
4240 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004241
Antoine Pitrou244651a2009-05-04 18:56:13 +00004242#define ENCODE_DIRECT(c, directO, directWS) \
4243 ((c) < 128 && (c) > 0 && \
4244 ((utf7_category[(c)] == 0) || \
4245 (directWS && (utf7_category[(c)] == 2)) || \
4246 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004247
Alexander Belopolsky40018472011-02-26 01:02:56 +00004248PyObject *
4249PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004250 Py_ssize_t size,
4251 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004252{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004253 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4254}
4255
Antoine Pitrou244651a2009-05-04 18:56:13 +00004256/* The decoder. The only state we preserve is our read position,
4257 * i.e. how many characters we have consumed. So if we end in the
4258 * middle of a shift sequence we have to back off the read position
4259 * and the output to the beginning of the sequence, otherwise we lose
4260 * all the shift state (seen bits, number of bits seen, high
4261 * surrogate). */
4262
Alexander Belopolsky40018472011-02-26 01:02:56 +00004263PyObject *
4264PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004265 Py_ssize_t size,
4266 const char *errors,
4267 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004268{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004269 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004270 Py_ssize_t startinpos;
4271 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004272 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004273 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274 const char *errmsg = "";
4275 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004276 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 unsigned int base64bits = 0;
4278 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004279 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004280 PyObject *errorHandler = NULL;
4281 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004282
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004283 if (size == 0) {
4284 if (consumed)
4285 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004286 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004287 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004289 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004290 _PyUnicodeWriter_Init(&writer);
4291 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004292
4293 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004294 e = s + size;
4295
4296 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004297 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004298 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004299 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004300
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301 if (inShift) { /* in a base-64 section */
4302 if (IS_BASE64(ch)) { /* consume a base-64 character */
4303 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4304 base64bits += 6;
4305 s++;
4306 if (base64bits >= 16) {
4307 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004308 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004309 base64bits -= 16;
4310 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004311 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004312 if (surrogate) {
4313 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004314 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4315 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004316 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004317 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004318 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004319 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004320 }
4321 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004322 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004323 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 }
4326 }
Victor Stinner551ac952011-11-29 22:58:13 +01004327 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004328 /* first surrogate */
4329 surrogate = outCh;
4330 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004331 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004332 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004334 }
4335 }
4336 }
4337 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004338 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004339 if (base64bits > 0) { /* left-over bits */
4340 if (base64bits >= 6) {
4341 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004342 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343 errmsg = "partial character in shift sequence";
4344 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 else {
4347 /* Some bits remain; they should be zero */
4348 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004349 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004350 errmsg = "non-zero padding bits in shift sequence";
4351 goto utf7Error;
4352 }
4353 }
4354 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004355 if (surrogate && DECODE_DIRECT(ch)) {
4356 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4357 goto onError;
4358 }
4359 surrogate = 0;
4360 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 /* '-' is absorbed; other terminating
4362 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004363 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004364 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004365 }
4366 }
4367 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004368 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 s++; /* consume '+' */
4370 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004372 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004373 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 }
4375 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004376 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004377 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004378 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004380 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
4382 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004385 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004386 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 else {
4389 startinpos = s-starts;
4390 s++;
4391 errmsg = "unexpected special character";
4392 goto utf7Error;
4393 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004394 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004396 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004397 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004398 errors, &errorHandler,
4399 "utf7", errmsg,
4400 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004401 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004403 }
4404
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 /* end of string */
4406
4407 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4408 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004409 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 if (surrogate ||
4411 (base64bits >= 6) ||
4412 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004413 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004414 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 errors, &errorHandler,
4416 "utf7", "unterminated shift sequence",
4417 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004418 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 goto onError;
4420 if (s < e)
4421 goto restart;
4422 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004423 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424
4425 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004426 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004428 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004429 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004430 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004431 writer.kind, writer.data, shiftOutStart);
4432 Py_XDECREF(errorHandler);
4433 Py_XDECREF(exc);
4434 _PyUnicodeWriter_Dealloc(&writer);
4435 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004436 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004437 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 }
4439 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004440 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004442 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004443
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004444 Py_XDECREF(errorHandler);
4445 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004446 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004449 Py_XDECREF(errorHandler);
4450 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004451 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 return NULL;
4453}
4454
4455
Alexander Belopolsky40018472011-02-26 01:02:56 +00004456PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004457_PyUnicode_EncodeUTF7(PyObject *str,
4458 int base64SetO,
4459 int base64WhiteSpace,
4460 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004461{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004462 int kind;
4463 void *data;
4464 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004465 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004467 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 unsigned int base64bits = 0;
4469 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004470 char * out;
4471 char * start;
4472
Benjamin Petersonbac79492012-01-14 13:34:47 -05004473 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004474 return NULL;
4475 kind = PyUnicode_KIND(str);
4476 data = PyUnicode_DATA(str);
4477 len = PyUnicode_GET_LENGTH(str);
4478
4479 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004482 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004483 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004484 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004485 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486 if (v == NULL)
4487 return NULL;
4488
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004489 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004490 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004491 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492
Antoine Pitrou244651a2009-05-04 18:56:13 +00004493 if (inShift) {
4494 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4495 /* shifting out */
4496 if (base64bits) { /* output remaining bits */
4497 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4498 base64buffer = 0;
4499 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 }
4501 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 /* Characters not in the BASE64 set implicitly unshift the sequence
4503 so no '-' is required, except if the character is itself a '-' */
4504 if (IS_BASE64(ch) || ch == '-') {
4505 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 *out++ = (char) ch;
4508 }
4509 else {
4510 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004511 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513 else { /* not in a shift sequence */
4514 if (ch == '+') {
4515 *out++ = '+';
4516 *out++ = '-';
4517 }
4518 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4519 *out++ = (char) ch;
4520 }
4521 else {
4522 *out++ = '+';
4523 inShift = 1;
4524 goto encode_char;
4525 }
4526 }
4527 continue;
4528encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004529 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004530 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004531
Antoine Pitrou244651a2009-05-04 18:56:13 +00004532 /* code first surrogate */
4533 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004534 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 while (base64bits >= 6) {
4536 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4537 base64bits -= 6;
4538 }
4539 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004540 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004541 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 base64bits += 16;
4543 base64buffer = (base64buffer << 16) | ch;
4544 while (base64bits >= 6) {
4545 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4546 base64bits -= 6;
4547 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 if (base64bits)
4550 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4551 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004552 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004553 if (_PyBytes_Resize(&v, out - start) < 0)
4554 return NULL;
4555 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004557PyObject *
4558PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4559 Py_ssize_t size,
4560 int base64SetO,
4561 int base64WhiteSpace,
4562 const char *errors)
4563{
4564 PyObject *result;
4565 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4566 if (tmp == NULL)
4567 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004568 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004569 base64WhiteSpace, errors);
4570 Py_DECREF(tmp);
4571 return result;
4572}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004573
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574#undef IS_BASE64
4575#undef FROM_BASE64
4576#undef TO_BASE64
4577#undef DECODE_DIRECT
4578#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004579
Guido van Rossumd57fd912000-03-10 22:53:23 +00004580/* --- UTF-8 Codec -------------------------------------------------------- */
4581
Alexander Belopolsky40018472011-02-26 01:02:56 +00004582PyObject *
4583PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004584 Py_ssize_t size,
4585 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004586{
Walter Dörwald69652032004-09-07 20:24:22 +00004587 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4588}
4589
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004590#include "stringlib/asciilib.h"
4591#include "stringlib/codecs.h"
4592#include "stringlib/undef.h"
4593
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004594#include "stringlib/ucs1lib.h"
4595#include "stringlib/codecs.h"
4596#include "stringlib/undef.h"
4597
4598#include "stringlib/ucs2lib.h"
4599#include "stringlib/codecs.h"
4600#include "stringlib/undef.h"
4601
4602#include "stringlib/ucs4lib.h"
4603#include "stringlib/codecs.h"
4604#include "stringlib/undef.h"
4605
Antoine Pitrouab868312009-01-10 15:40:25 +00004606/* Mask to quickly check whether a C 'long' contains a
4607 non-ASCII, UTF8-encoded char. */
4608#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004609# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004610#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004611# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004612#else
4613# error C 'long' size should be either 4 or 8!
4614#endif
4615
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004616static Py_ssize_t
4617ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004618{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004619 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004620 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004621
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004622 /*
4623 * Issue #17237: m68k is a bit different from most architectures in
4624 * that objects do not use "natural alignment" - for example, int and
4625 * long are only aligned at 2-byte boundaries. Therefore the assert()
4626 * won't work; also, tests have shown that skipping the "optimised
4627 * version" will even speed up m68k.
4628 */
4629#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004630#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004631 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4632 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004633 /* Fast path, see in STRINGLIB(utf8_decode) for
4634 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004635 /* Help allocation */
4636 const char *_p = p;
4637 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004638 while (_p < aligned_end) {
4639 unsigned long value = *(const unsigned long *) _p;
4640 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004641 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004642 *((unsigned long *)q) = value;
4643 _p += SIZEOF_LONG;
4644 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004645 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004646 p = _p;
4647 while (p < end) {
4648 if ((unsigned char)*p & 0x80)
4649 break;
4650 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004651 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004652 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004653 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004655#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004656 while (p < end) {
4657 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4658 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004659 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004660 /* Help allocation */
4661 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004662 while (_p < aligned_end) {
4663 unsigned long value = *(unsigned long *) _p;
4664 if (value & ASCII_CHAR_MASK)
4665 break;
4666 _p += SIZEOF_LONG;
4667 }
4668 p = _p;
4669 if (_p == end)
4670 break;
4671 }
4672 if ((unsigned char)*p & 0x80)
4673 break;
4674 ++p;
4675 }
4676 memcpy(dest, start, p - start);
4677 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004678}
Antoine Pitrouab868312009-01-10 15:40:25 +00004679
Victor Stinner785938e2011-12-11 20:09:03 +01004680PyObject *
4681PyUnicode_DecodeUTF8Stateful(const char *s,
4682 Py_ssize_t size,
4683 const char *errors,
4684 Py_ssize_t *consumed)
4685{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004686 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004687 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004689
4690 Py_ssize_t startinpos;
4691 Py_ssize_t endinpos;
4692 const char *errmsg = "";
4693 PyObject *errorHandler = NULL;
4694 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004695
4696 if (size == 0) {
4697 if (consumed)
4698 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004699 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004700 }
4701
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004702 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4703 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004704 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004705 *consumed = 1;
4706 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004707 }
4708
Victor Stinner8f674cc2013-04-17 23:02:17 +02004709 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004710 writer.min_length = size;
4711 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004712 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004713
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004714 writer.pos = ascii_decode(s, end, writer.data);
4715 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004716 while (s < end) {
4717 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004718 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004719 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004720 if (PyUnicode_IS_ASCII(writer.buffer))
4721 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004722 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004723 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004725 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004726 } else {
4727 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004729 }
4730
4731 switch (ch) {
4732 case 0:
4733 if (s == end || consumed)
4734 goto End;
4735 errmsg = "unexpected end of data";
4736 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004737 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 break;
4739 case 1:
4740 errmsg = "invalid start byte";
4741 startinpos = s - starts;
4742 endinpos = startinpos + 1;
4743 break;
4744 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004745 case 3:
4746 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004747 errmsg = "invalid continuation byte";
4748 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004749 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 break;
4751 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004752 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 goto onError;
4754 continue;
4755 }
4756
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004757 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 errors, &errorHandler,
4759 "utf-8", errmsg,
4760 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004761 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004763 }
4764
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 if (consumed)
4767 *consumed = s - starts;
4768
4769 Py_XDECREF(errorHandler);
4770 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004771 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772
4773onError:
4774 Py_XDECREF(errorHandler);
4775 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004776 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004778}
4779
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004780#ifdef __APPLE__
4781
4782/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004783 used to decode the command line arguments on Mac OS X.
4784
4785 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004786 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004787
4788wchar_t*
4789_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4790{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004791 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 wchar_t *unicode;
4793 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004794
4795 /* Note: size will always be longer than the resulting Unicode
4796 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004797 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004798 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004799 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004800 if (!unicode)
4801 return NULL;
4802
4803 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004804 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004805 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004806 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004808#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004809 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004810#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004812#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004813 if (ch > 0xFF) {
4814#if SIZEOF_WCHAR_T == 4
4815 assert(0);
4816#else
4817 assert(Py_UNICODE_IS_SURROGATE(ch));
4818 /* compute and append the two surrogates: */
4819 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4820 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4821#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823 else {
4824 if (!ch && s == e)
4825 break;
4826 /* surrogateescape */
4827 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4828 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004830 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004831 return unicode;
4832}
4833
4834#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004835
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004836/* Primary internal function which creates utf8 encoded bytes objects.
4837
4838 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004839 and allocate exactly as much space needed at the end. Else allocate the
4840 maximum possible needed (4 result bytes per Unicode character), and return
4841 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004842*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004843PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004844_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004845{
Victor Stinner6099a032011-12-18 14:22:26 +01004846 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004847 void *data;
4848 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004850 if (!PyUnicode_Check(unicode)) {
4851 PyErr_BadArgument();
4852 return NULL;
4853 }
4854
4855 if (PyUnicode_READY(unicode) == -1)
4856 return NULL;
4857
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004858 if (PyUnicode_UTF8(unicode))
4859 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4860 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004861
4862 kind = PyUnicode_KIND(unicode);
4863 data = PyUnicode_DATA(unicode);
4864 size = PyUnicode_GET_LENGTH(unicode);
4865
Benjamin Petersonead6b532011-12-20 17:23:42 -06004866 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004867 default:
4868 assert(0);
4869 case PyUnicode_1BYTE_KIND:
4870 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4871 assert(!PyUnicode_IS_ASCII(unicode));
4872 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4873 case PyUnicode_2BYTE_KIND:
4874 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4875 case PyUnicode_4BYTE_KIND:
4876 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004877 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004878}
4879
Alexander Belopolsky40018472011-02-26 01:02:56 +00004880PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4882 Py_ssize_t size,
4883 const char *errors)
4884{
4885 PyObject *v, *unicode;
4886
4887 unicode = PyUnicode_FromUnicode(s, size);
4888 if (unicode == NULL)
4889 return NULL;
4890 v = _PyUnicode_AsUTF8String(unicode, errors);
4891 Py_DECREF(unicode);
4892 return v;
4893}
4894
4895PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004896PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004898 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004899}
4900
Walter Dörwald41980ca2007-08-16 21:55:45 +00004901/* --- UTF-32 Codec ------------------------------------------------------- */
4902
4903PyObject *
4904PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004905 Py_ssize_t size,
4906 const char *errors,
4907 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004908{
4909 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4910}
4911
4912PyObject *
4913PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004914 Py_ssize_t size,
4915 const char *errors,
4916 int *byteorder,
4917 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004918{
4919 const char *starts = s;
4920 Py_ssize_t startinpos;
4921 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004922 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004923 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004924 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004925 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004926 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004927 PyObject *errorHandler = NULL;
4928 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004929
Walter Dörwald41980ca2007-08-16 21:55:45 +00004930 q = (unsigned char *)s;
4931 e = q + size;
4932
4933 if (byteorder)
4934 bo = *byteorder;
4935
4936 /* Check for BOM marks (U+FEFF) in the input and adjust current
4937 byte order setting accordingly. In native mode, the leading BOM
4938 mark is skipped, in all other modes, it is copied to the output
4939 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004940 if (bo == 0 && size >= 4) {
4941 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4942 if (bom == 0x0000FEFF) {
4943 bo = -1;
4944 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004945 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004946 else if (bom == 0xFFFE0000) {
4947 bo = 1;
4948 q += 4;
4949 }
4950 if (byteorder)
4951 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004952 }
4953
Victor Stinnere64322e2012-10-30 23:12:47 +01004954 if (q == e) {
4955 if (consumed)
4956 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004957 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004958 }
4959
Victor Stinnere64322e2012-10-30 23:12:47 +01004960#ifdef WORDS_BIGENDIAN
4961 le = bo < 0;
4962#else
4963 le = bo <= 0;
4964#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004965 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004966
Victor Stinner8f674cc2013-04-17 23:02:17 +02004967 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004968 writer.min_length = (e - q + 3) / 4;
4969 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004970 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004971
Victor Stinnere64322e2012-10-30 23:12:47 +01004972 while (1) {
4973 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004974 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004975
Victor Stinnere64322e2012-10-30 23:12:47 +01004976 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004977 enum PyUnicode_Kind kind = writer.kind;
4978 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004979 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004980 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004981 if (le) {
4982 do {
4983 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4984 if (ch > maxch)
4985 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004986 if (kind != PyUnicode_1BYTE_KIND &&
4987 Py_UNICODE_IS_SURROGATE(ch))
4988 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004989 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004990 q += 4;
4991 } while (q <= last);
4992 }
4993 else {
4994 do {
4995 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
4996 if (ch > maxch)
4997 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004998 if (kind != PyUnicode_1BYTE_KIND &&
4999 Py_UNICODE_IS_SURROGATE(ch))
5000 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005001 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005002 q += 4;
5003 } while (q <= last);
5004 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005005 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005006 }
5007
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005008 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005009 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005010 startinpos = ((const char *)q) - starts;
5011 endinpos = startinpos + 4;
5012 }
5013 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005014 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005015 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005016 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005017 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005018 startinpos = ((const char *)q) - starts;
5019 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 else {
5022 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005023 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 goto onError;
5025 q += 4;
5026 continue;
5027 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005028 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005029 startinpos = ((const char *)q) - starts;
5030 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005032
5033 /* The remaining input chars are ignored if the callback
5034 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005037 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005038 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005039 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005040 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005041 }
5042
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005044 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045
Walter Dörwald41980ca2007-08-16 21:55:45 +00005046 Py_XDECREF(errorHandler);
5047 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005048 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005049
Benjamin Peterson29060642009-01-31 22:14:21 +00005050 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005051 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052 Py_XDECREF(errorHandler);
5053 Py_XDECREF(exc);
5054 return NULL;
5055}
5056
5057PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005058_PyUnicode_EncodeUTF32(PyObject *str,
5059 const char *errors,
5060 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005061{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005062 enum PyUnicode_Kind kind;
5063 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005064 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005065 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005066 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005067#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005068 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005069#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005070 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005072 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005073 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005074 PyObject *errorHandler = NULL;
5075 PyObject *exc = NULL;
5076 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005078 if (!PyUnicode_Check(str)) {
5079 PyErr_BadArgument();
5080 return NULL;
5081 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005082 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005083 return NULL;
5084 kind = PyUnicode_KIND(str);
5085 data = PyUnicode_DATA(str);
5086 len = PyUnicode_GET_LENGTH(str);
5087
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005088 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005089 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005090 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005091 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092 if (v == NULL)
5093 return NULL;
5094
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005095 /* output buffer is 4-bytes aligned */
5096 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5097 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005099 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005100 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005101 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005102
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005103 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005104 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005105 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005106 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005107 else
5108 encoding = "utf-32";
5109
5110 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005111 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5112 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113 }
5114
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005115 pos = 0;
5116 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005117 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005118
5119 if (kind == PyUnicode_2BYTE_KIND) {
5120 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5121 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005122 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005123 else {
5124 assert(kind == PyUnicode_4BYTE_KIND);
5125 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5126 &out, native_ordering);
5127 }
5128 if (pos == len)
5129 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005130
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005131 rep = unicode_encode_call_errorhandler(
5132 errors, &errorHandler,
5133 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005134 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005135 if (!rep)
5136 goto error;
5137
5138 if (PyBytes_Check(rep)) {
5139 repsize = PyBytes_GET_SIZE(rep);
5140 if (repsize & 3) {
5141 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005142 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005143 "surrogates not allowed");
5144 goto error;
5145 }
5146 moreunits = repsize / 4;
5147 }
5148 else {
5149 assert(PyUnicode_Check(rep));
5150 if (PyUnicode_READY(rep) < 0)
5151 goto error;
5152 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5153 if (!PyUnicode_IS_ASCII(rep)) {
5154 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005155 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005156 "surrogates not allowed");
5157 goto error;
5158 }
5159 }
5160
5161 /* four bytes are reserved for each surrogate */
5162 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005163 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005164 Py_ssize_t morebytes = 4 * (moreunits - 1);
5165 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5166 /* integer overflow */
5167 PyErr_NoMemory();
5168 goto error;
5169 }
5170 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5171 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005172 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005173 }
5174
5175 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005176 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5177 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005178 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005179 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005180 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5181 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005182 }
5183
5184 Py_CLEAR(rep);
5185 }
5186
5187 /* Cut back to size actually needed. This is necessary for, for example,
5188 encoding of a string containing isolated surrogates and the 'ignore'
5189 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005190 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005191 if (nsize != PyBytes_GET_SIZE(v))
5192 _PyBytes_Resize(&v, nsize);
5193 Py_XDECREF(errorHandler);
5194 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005195 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005196 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005197 error:
5198 Py_XDECREF(rep);
5199 Py_XDECREF(errorHandler);
5200 Py_XDECREF(exc);
5201 Py_XDECREF(v);
5202 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005203}
5204
Alexander Belopolsky40018472011-02-26 01:02:56 +00005205PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005206PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5207 Py_ssize_t size,
5208 const char *errors,
5209 int byteorder)
5210{
5211 PyObject *result;
5212 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5213 if (tmp == NULL)
5214 return NULL;
5215 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5216 Py_DECREF(tmp);
5217 return result;
5218}
5219
5220PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005221PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005222{
Victor Stinnerb960b342011-11-20 19:12:52 +01005223 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005224}
5225
Guido van Rossumd57fd912000-03-10 22:53:23 +00005226/* --- UTF-16 Codec ------------------------------------------------------- */
5227
Tim Peters772747b2001-08-09 22:21:55 +00005228PyObject *
5229PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005230 Py_ssize_t size,
5231 const char *errors,
5232 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005233{
Walter Dörwald69652032004-09-07 20:24:22 +00005234 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5235}
5236
5237PyObject *
5238PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 Py_ssize_t size,
5240 const char *errors,
5241 int *byteorder,
5242 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005243{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005244 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005245 Py_ssize_t startinpos;
5246 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005247 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005248 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005249 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005250 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005251 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005252 PyObject *errorHandler = NULL;
5253 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005254 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005255
Tim Peters772747b2001-08-09 22:21:55 +00005256 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005257 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005258
5259 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005260 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005261
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005262 /* Check for BOM marks (U+FEFF) in the input and adjust current
5263 byte order setting accordingly. In native mode, the leading BOM
5264 mark is skipped, in all other modes, it is copied to the output
5265 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005266 if (bo == 0 && size >= 2) {
5267 const Py_UCS4 bom = (q[1] << 8) | q[0];
5268 if (bom == 0xFEFF) {
5269 q += 2;
5270 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005271 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005272 else if (bom == 0xFFFE) {
5273 q += 2;
5274 bo = 1;
5275 }
5276 if (byteorder)
5277 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005278 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005279
Antoine Pitrou63065d72012-05-15 23:48:04 +02005280 if (q == e) {
5281 if (consumed)
5282 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005283 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005284 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005285
Christian Heimes743e0cd2012-10-17 23:52:17 +02005286#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005287 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005288 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005289#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005290 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005291 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005292#endif
Tim Peters772747b2001-08-09 22:21:55 +00005293
Antoine Pitrou63065d72012-05-15 23:48:04 +02005294 /* Note: size will always be longer than the resulting Unicode
5295 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005296 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005297 writer.min_length = (e - q + 1) / 2;
5298 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005299 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005300
Antoine Pitrou63065d72012-05-15 23:48:04 +02005301 while (1) {
5302 Py_UCS4 ch = 0;
5303 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005304 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005305 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005306 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005307 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005308 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005309 native_ordering);
5310 else
5311 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005312 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005313 native_ordering);
5314 } else if (kind == PyUnicode_2BYTE_KIND) {
5315 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005316 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005317 native_ordering);
5318 } else {
5319 assert(kind == PyUnicode_4BYTE_KIND);
5320 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005321 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005322 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005323 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005324 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005325
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 switch (ch)
5327 {
5328 case 0:
5329 /* remaining byte at the end? (size should be even) */
5330 if (q == e || consumed)
5331 goto End;
5332 errmsg = "truncated data";
5333 startinpos = ((const char *)q) - starts;
5334 endinpos = ((const char *)e) - starts;
5335 break;
5336 /* The remaining input chars are ignored if the callback
5337 chooses to skip the input */
5338 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005339 q -= 2;
5340 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005341 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005342 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005343 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005344 endinpos = ((const char *)e) - starts;
5345 break;
5346 case 2:
5347 errmsg = "illegal encoding";
5348 startinpos = ((const char *)q) - 2 - starts;
5349 endinpos = startinpos + 2;
5350 break;
5351 case 3:
5352 errmsg = "illegal UTF-16 surrogate";
5353 startinpos = ((const char *)q) - 4 - starts;
5354 endinpos = startinpos + 2;
5355 break;
5356 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005357 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005358 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 continue;
5360 }
5361
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005363 errors,
5364 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005365 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005366 &starts,
5367 (const char **)&e,
5368 &startinpos,
5369 &endinpos,
5370 &exc,
5371 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005372 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005374 }
5375
Antoine Pitrou63065d72012-05-15 23:48:04 +02005376End:
Walter Dörwald69652032004-09-07 20:24:22 +00005377 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005379
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005380 Py_XDECREF(errorHandler);
5381 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005382 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005383
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005385 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005386 Py_XDECREF(errorHandler);
5387 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005388 return NULL;
5389}
5390
Tim Peters772747b2001-08-09 22:21:55 +00005391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005392_PyUnicode_EncodeUTF16(PyObject *str,
5393 const char *errors,
5394 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005396 enum PyUnicode_Kind kind;
5397 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005398 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005399 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005400 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005401 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005402#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005403 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005404#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005405 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005406#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005407 const char *encoding;
5408 Py_ssize_t nsize, pos;
5409 PyObject *errorHandler = NULL;
5410 PyObject *exc = NULL;
5411 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005412
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005413 if (!PyUnicode_Check(str)) {
5414 PyErr_BadArgument();
5415 return NULL;
5416 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005417 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005418 return NULL;
5419 kind = PyUnicode_KIND(str);
5420 data = PyUnicode_DATA(str);
5421 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005422
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005423 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005424 if (kind == PyUnicode_4BYTE_KIND) {
5425 const Py_UCS4 *in = (const Py_UCS4 *)data;
5426 const Py_UCS4 *end = in + len;
5427 while (in < end)
5428 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005429 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005430 }
5431 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005433 nsize = len + pairs + (byteorder == 0);
5434 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005435 if (v == NULL)
5436 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005438 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005439 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005440 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005442 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005443 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005444 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005445
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005446 if (kind == PyUnicode_1BYTE_KIND) {
5447 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5448 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005449 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005450
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005451 if (byteorder < 0)
5452 encoding = "utf-16-le";
5453 else if (byteorder > 0)
5454 encoding = "utf-16-be";
5455 else
5456 encoding = "utf-16";
5457
5458 pos = 0;
5459 while (pos < len) {
5460 Py_ssize_t repsize, moreunits;
5461
5462 if (kind == PyUnicode_2BYTE_KIND) {
5463 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5464 &out, native_ordering);
5465 }
5466 else {
5467 assert(kind == PyUnicode_4BYTE_KIND);
5468 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5469 &out, native_ordering);
5470 }
5471 if (pos == len)
5472 break;
5473
5474 rep = unicode_encode_call_errorhandler(
5475 errors, &errorHandler,
5476 encoding, "surrogates not allowed",
5477 str, &exc, pos, pos + 1, &pos);
5478 if (!rep)
5479 goto error;
5480
5481 if (PyBytes_Check(rep)) {
5482 repsize = PyBytes_GET_SIZE(rep);
5483 if (repsize & 1) {
5484 raise_encode_exception(&exc, encoding,
5485 str, pos - 1, pos,
5486 "surrogates not allowed");
5487 goto error;
5488 }
5489 moreunits = repsize / 2;
5490 }
5491 else {
5492 assert(PyUnicode_Check(rep));
5493 if (PyUnicode_READY(rep) < 0)
5494 goto error;
5495 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5496 if (!PyUnicode_IS_ASCII(rep)) {
5497 raise_encode_exception(&exc, encoding,
5498 str, pos - 1, pos,
5499 "surrogates not allowed");
5500 goto error;
5501 }
5502 }
5503
5504 /* two bytes are reserved for each surrogate */
5505 if (moreunits > 1) {
5506 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5507 Py_ssize_t morebytes = 2 * (moreunits - 1);
5508 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5509 /* integer overflow */
5510 PyErr_NoMemory();
5511 goto error;
5512 }
5513 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5514 goto error;
5515 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5516 }
5517
5518 if (PyBytes_Check(rep)) {
5519 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5520 out += moreunits;
5521 } else /* rep is unicode */ {
5522 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5523 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5524 &out, native_ordering);
5525 }
5526
5527 Py_CLEAR(rep);
5528 }
5529
5530 /* Cut back to size actually needed. This is necessary for, for example,
5531 encoding of a string containing isolated surrogates and the 'ignore' handler
5532 is used. */
5533 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5534 if (nsize != PyBytes_GET_SIZE(v))
5535 _PyBytes_Resize(&v, nsize);
5536 Py_XDECREF(errorHandler);
5537 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005538 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005539 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005540 error:
5541 Py_XDECREF(rep);
5542 Py_XDECREF(errorHandler);
5543 Py_XDECREF(exc);
5544 Py_XDECREF(v);
5545 return NULL;
5546#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547}
5548
Alexander Belopolsky40018472011-02-26 01:02:56 +00005549PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005550PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5551 Py_ssize_t size,
5552 const char *errors,
5553 int byteorder)
5554{
5555 PyObject *result;
5556 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5557 if (tmp == NULL)
5558 return NULL;
5559 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5560 Py_DECREF(tmp);
5561 return result;
5562}
5563
5564PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005565PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005567 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005568}
5569
5570/* --- Unicode Escape Codec ----------------------------------------------- */
5571
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005572/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5573 if all the escapes in the string make it still a valid ASCII string.
5574 Returns -1 if any escapes were found which cause the string to
5575 pop out of ASCII range. Otherwise returns the length of the
5576 required buffer to hold the string.
5577 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005578static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005579length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5580{
5581 const unsigned char *p = (const unsigned char *)s;
5582 const unsigned char *end = p + size;
5583 Py_ssize_t length = 0;
5584
5585 if (size < 0)
5586 return -1;
5587
5588 for (; p < end; ++p) {
5589 if (*p > 127) {
5590 /* Non-ASCII */
5591 return -1;
5592 }
5593 else if (*p != '\\') {
5594 /* Normal character */
5595 ++length;
5596 }
5597 else {
5598 /* Backslash-escape, check next char */
5599 ++p;
5600 /* Escape sequence reaches till end of string or
5601 non-ASCII follow-up. */
5602 if (p >= end || *p > 127)
5603 return -1;
5604 switch (*p) {
5605 case '\n':
5606 /* backslash + \n result in zero characters */
5607 break;
5608 case '\\': case '\'': case '\"':
5609 case 'b': case 'f': case 't':
5610 case 'n': case 'r': case 'v': case 'a':
5611 ++length;
5612 break;
5613 case '0': case '1': case '2': case '3':
5614 case '4': case '5': case '6': case '7':
5615 case 'x': case 'u': case 'U': case 'N':
5616 /* these do not guarantee ASCII characters */
5617 return -1;
5618 default:
5619 /* count the backslash + the other character */
5620 length += 2;
5621 }
5622 }
5623 }
5624 return length;
5625}
5626
Fredrik Lundh06d12682001-01-24 07:59:11 +00005627static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005628
Alexander Belopolsky40018472011-02-26 01:02:56 +00005629PyObject *
5630PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005631 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005632 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005634 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005635 Py_ssize_t startinpos;
5636 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005637 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005638 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005639 char* message;
5640 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005641 PyObject *errorHandler = NULL;
5642 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005643 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005644
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005645 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005646 if (len == 0)
5647 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005648
5649 /* After length_of_escaped_ascii_string() there are two alternatives,
5650 either the string is pure ASCII with named escapes like \n, etc.
5651 and we determined it's exact size (common case)
5652 or it contains \x, \u, ... escape sequences. then we create a
5653 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005654 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005655 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005656 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005657 }
5658 else {
5659 /* Escaped strings will always be longer than the resulting
5660 Unicode string, so we start with size here and then reduce the
5661 length after conversion to the true value.
5662 (but if the error callback returns a long replacement string
5663 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005664 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005665 }
5666
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005668 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005669 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005670
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 while (s < end) {
5672 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005673 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675
5676 /* Non-escape characters are interpreted as Unicode ordinals */
5677 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005678 x = (unsigned char)*s;
5679 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005680 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005681 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682 continue;
5683 }
5684
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005685 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 /* \ - Escapes */
5687 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005688 c = *s++;
5689 if (s > end)
5690 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005691
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005692 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693
Benjamin Peterson29060642009-01-31 22:14:21 +00005694 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005695#define WRITECHAR(ch) \
5696 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005697 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005698 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005699 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005700
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005702 case '\\': WRITECHAR('\\'); break;
5703 case '\'': WRITECHAR('\''); break;
5704 case '\"': WRITECHAR('\"'); break;
5705 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005706 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005707 case 'f': WRITECHAR('\014'); break;
5708 case 't': WRITECHAR('\t'); break;
5709 case 'n': WRITECHAR('\n'); break;
5710 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005712 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005713 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005714 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005715
Benjamin Peterson29060642009-01-31 22:14:21 +00005716 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717 case '0': case '1': case '2': case '3':
5718 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005719 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005720 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005721 x = (x<<3) + *s++ - '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 Rossumd57fd912000-03-10 22:53:23 +00005724 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005725 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 break;
5727
Benjamin Peterson29060642009-01-31 22:14:21 +00005728 /* hex escapes */
5729 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005731 digits = 2;
5732 message = "truncated \\xXX escape";
5733 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005737 digits = 4;
5738 message = "truncated \\uXXXX escape";
5739 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005742 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005743 digits = 8;
5744 message = "truncated \\UXXXXXXXX escape";
5745 hexescape:
5746 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005747 if (end - s < digits) {
5748 /* count only hex digits */
5749 for (; s < end; ++s) {
5750 c = (unsigned char)*s;
5751 if (!Py_ISXDIGIT(c))
5752 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005753 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005754 goto error;
5755 }
5756 for (; digits--; ++s) {
5757 c = (unsigned char)*s;
5758 if (!Py_ISXDIGIT(c))
5759 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005760 chr = (chr<<4) & ~0xF;
5761 if (c >= '0' && c <= '9')
5762 chr += c - '0';
5763 else if (c >= 'a' && c <= 'f')
5764 chr += 10 + c - 'a';
5765 else
5766 chr += 10 + c - 'A';
5767 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005768 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005769 /* _decoding_error will have already written into the
5770 target buffer. */
5771 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005772 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005773 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005774 message = "illegal Unicode character";
5775 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005776 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005777 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005778 break;
5779
Benjamin Peterson29060642009-01-31 22:14:21 +00005780 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005781 case 'N':
5782 message = "malformed \\N character escape";
5783 if (ucnhash_CAPI == NULL) {
5784 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005785 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5786 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005787 if (ucnhash_CAPI == NULL)
5788 goto ucnhashError;
5789 }
5790 if (*s == '{') {
5791 const char *start = s+1;
5792 /* look for the closing brace */
5793 while (*s != '}' && s < end)
5794 s++;
5795 if (s > start && s < end && *s == '}') {
5796 /* found a name. look it up in the unicode database */
5797 message = "unknown Unicode character name";
5798 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005799 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005800 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005801 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005802 goto store;
5803 }
5804 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005805 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005806
5807 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005808 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005809 message = "\\ at end of string";
5810 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005811 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005812 }
5813 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005814 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005815 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005816 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005817 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005819 continue;
5820
5821 error:
5822 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005823 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005824 errors, &errorHandler,
5825 "unicodeescape", message,
5826 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005827 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005828 goto onError;
5829 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005830 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005831#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005833 Py_XDECREF(errorHandler);
5834 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005835 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005836
Benjamin Peterson29060642009-01-31 22:14:21 +00005837 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005838 PyErr_SetString(
5839 PyExc_UnicodeError,
5840 "\\N escapes not supported (can't load unicodedata module)"
5841 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005842 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005843 Py_XDECREF(errorHandler);
5844 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005845 return NULL;
5846
Benjamin Peterson29060642009-01-31 22:14:21 +00005847 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005848 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005849 Py_XDECREF(errorHandler);
5850 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 return NULL;
5852}
5853
5854/* Return a Unicode-Escape string version of the Unicode object.
5855
5856 If quotes is true, the string is enclosed in u"" or u'' quotes as
5857 appropriate.
5858
5859*/
5860
Alexander Belopolsky40018472011-02-26 01:02:56 +00005861PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005862PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005863{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005864 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005865 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005867 int kind;
5868 void *data;
5869 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870
Ezio Melottie7f90372012-10-05 03:33:31 +03005871 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005872 escape.
5873
Ezio Melottie7f90372012-10-05 03:33:31 +03005874 For UCS1 strings it's '\xxx', 4 bytes per source character.
5875 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5876 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005877 */
5878
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005879 if (!PyUnicode_Check(unicode)) {
5880 PyErr_BadArgument();
5881 return NULL;
5882 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005883 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005884 return NULL;
5885 len = PyUnicode_GET_LENGTH(unicode);
5886 kind = PyUnicode_KIND(unicode);
5887 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005888 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5890 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5891 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5892 }
5893
5894 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005895 return PyBytes_FromStringAndSize(NULL, 0);
5896
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005897 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005898 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005899
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005900 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005902 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904 if (repr == NULL)
5905 return NULL;
5906
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005907 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005909 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005910 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005911
Walter Dörwald79e913e2007-05-12 11:08:06 +00005912 /* Escape backslashes */
5913 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 *p++ = '\\';
5915 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005916 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005917 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005918
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005919 /* Map 21-bit characters to '\U00xxxxxx' */
5920 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005921 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005922 *p++ = '\\';
5923 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005924 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5925 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5926 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5927 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5928 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5929 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5930 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5931 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005933 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005934
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005936 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 *p++ = '\\';
5938 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005939 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5940 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5941 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5942 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005944
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005945 /* Map special whitespace to '\t', \n', '\r' */
5946 else if (ch == '\t') {
5947 *p++ = '\\';
5948 *p++ = 't';
5949 }
5950 else if (ch == '\n') {
5951 *p++ = '\\';
5952 *p++ = 'n';
5953 }
5954 else if (ch == '\r') {
5955 *p++ = '\\';
5956 *p++ = 'r';
5957 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005958
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005959 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005960 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005962 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005963 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5964 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005965 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005966
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 /* Copy everything else as-is */
5968 else
5969 *p++ = (char) ch;
5970 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005972 assert(p - PyBytes_AS_STRING(repr) > 0);
5973 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5974 return NULL;
5975 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976}
5977
Alexander Belopolsky40018472011-02-26 01:02:56 +00005978PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005979PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5980 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005982 PyObject *result;
5983 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5984 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005986 result = PyUnicode_AsUnicodeEscapeString(tmp);
5987 Py_DECREF(tmp);
5988 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989}
5990
5991/* --- Raw Unicode Escape Codec ------------------------------------------- */
5992
Alexander Belopolsky40018472011-02-26 01:02:56 +00005993PyObject *
5994PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005995 Py_ssize_t size,
5996 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005998 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005999 Py_ssize_t startinpos;
6000 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006001 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006002 const char *end;
6003 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006004 PyObject *errorHandler = NULL;
6005 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006006
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006007 if (size == 0)
6008 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006009
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 /* Escaped strings will always be longer than the resulting
6011 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006012 length after conversion to the true value. (But decoding error
6013 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006014 _PyUnicodeWriter_Init(&writer);
6015 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006016
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017 end = s + size;
6018 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 unsigned char c;
6020 Py_UCS4 x;
6021 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006022 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 /* Non-escape characters are interpreted as Unicode ordinals */
6025 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006026 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006027 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006028 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006029 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006030 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 startinpos = s-starts;
6032
6033 /* \u-escapes are only interpreted iff the number of leading
6034 backslashes if odd */
6035 bs = s;
6036 for (;s < end;) {
6037 if (*s != '\\')
6038 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006039 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006040 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006041 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 }
6043 if (((s - bs) & 1) == 0 ||
6044 s >= end ||
6045 (*s != 'u' && *s != 'U')) {
6046 continue;
6047 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006048 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 count = *s=='u' ? 4 : 8;
6050 s++;
6051
6052 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006053 for (x = 0, i = 0; i < count; ++i, ++s) {
6054 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006055 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006057 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 errors, &errorHandler,
6059 "rawunicodeescape", "truncated \\uXXXX",
6060 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006061 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006062 goto onError;
6063 goto nextByte;
6064 }
6065 x = (x<<4) & ~0xF;
6066 if (c >= '0' && c <= '9')
6067 x += c - '0';
6068 else if (c >= 'a' && c <= 'f')
6069 x += 10 + c - 'a';
6070 else
6071 x += 10 + c - 'A';
6072 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006073 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006074 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006075 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006076 }
6077 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006078 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006079 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006080 errors, &errorHandler,
6081 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006083 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006085 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 nextByte:
6087 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006089 Py_XDECREF(errorHandler);
6090 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006091 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006092
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006094 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006095 Py_XDECREF(errorHandler);
6096 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 return NULL;
6098}
6099
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006100
Alexander Belopolsky40018472011-02-26 01:02:56 +00006101PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006102PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006104 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006105 char *p;
6106 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006107 Py_ssize_t expandsize, pos;
6108 int kind;
6109 void *data;
6110 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006112 if (!PyUnicode_Check(unicode)) {
6113 PyErr_BadArgument();
6114 return NULL;
6115 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006116 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006117 return NULL;
6118 kind = PyUnicode_KIND(unicode);
6119 data = PyUnicode_DATA(unicode);
6120 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006121 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6122 bytes, and 1 byte characters 4. */
6123 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006124
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006127
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129 if (repr == NULL)
6130 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006131 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006132 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006134 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135 for (pos = 0; pos < len; pos++) {
6136 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006137 /* Map 32-bit characters to '\Uxxxxxxxx' */
6138 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006139 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006140 *p++ = '\\';
6141 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006142 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6143 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6144 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6145 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6146 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6147 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6148 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6149 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006150 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153 *p++ = '\\';
6154 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006155 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6156 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6157 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6158 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 /* Copy everything else as-is */
6161 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162 *p++ = (char) ch;
6163 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006164
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165 assert(p > q);
6166 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006167 return NULL;
6168 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169}
6170
Alexander Belopolsky40018472011-02-26 01:02:56 +00006171PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006172PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6173 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 PyObject *result;
6176 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6177 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006178 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6180 Py_DECREF(tmp);
6181 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006182}
6183
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006184/* --- Unicode Internal Codec ------------------------------------------- */
6185
Alexander Belopolsky40018472011-02-26 01:02:56 +00006186PyObject *
6187_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006188 Py_ssize_t size,
6189 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006190{
6191 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006192 Py_ssize_t startinpos;
6193 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006194 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006195 const char *end;
6196 const char *reason;
6197 PyObject *errorHandler = NULL;
6198 PyObject *exc = NULL;
6199
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006200 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006201 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006202 1))
6203 return NULL;
6204
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006205 if (size == 0)
6206 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006207
Victor Stinner8f674cc2013-04-17 23:02:17 +02006208 _PyUnicodeWriter_Init(&writer);
6209 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6210 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006211 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006212 }
6213 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006214
Victor Stinner8f674cc2013-04-17 23:02:17 +02006215 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006216 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006217 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006218 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006219 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006220 endinpos = end-starts;
6221 reason = "truncated input";
6222 goto error;
6223 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006224 /* We copy the raw representation one byte at a time because the
6225 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006226 ((char *) &uch)[0] = s[0];
6227 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006228#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006229 ((char *) &uch)[2] = s[2];
6230 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006231#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006232 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006233#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006234 /* We have to sanity check the raw data, otherwise doom looms for
6235 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006236 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006237 endinpos = s - starts + Py_UNICODE_SIZE;
6238 reason = "illegal code point (> 0x10FFFF)";
6239 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006240 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006241#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006242 s += Py_UNICODE_SIZE;
6243#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006244 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006245 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006246 Py_UNICODE uch2;
6247 ((char *) &uch2)[0] = s[0];
6248 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006249 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006250 {
Victor Stinner551ac952011-11-29 22:58:13 +01006251 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006252 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006253 }
6254 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006255#endif
6256
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006257 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006258 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006259 continue;
6260
6261 error:
6262 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006263 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006264 errors, &errorHandler,
6265 "unicode_internal", reason,
6266 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006267 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006268 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006269 }
6270
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006271 Py_XDECREF(errorHandler);
6272 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006273 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006274
Benjamin Peterson29060642009-01-31 22:14:21 +00006275 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006276 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006277 Py_XDECREF(errorHandler);
6278 Py_XDECREF(exc);
6279 return NULL;
6280}
6281
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282/* --- Latin-1 Codec ------------------------------------------------------ */
6283
Alexander Belopolsky40018472011-02-26 01:02:56 +00006284PyObject *
6285PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006286 Py_ssize_t size,
6287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006288{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006289 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006290 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291}
6292
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006293/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006294static void
6295make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006296 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006297 PyObject *unicode,
6298 Py_ssize_t startpos, Py_ssize_t endpos,
6299 const char *reason)
6300{
6301 if (*exceptionObject == NULL) {
6302 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006303 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006304 encoding, unicode, startpos, endpos, reason);
6305 }
6306 else {
6307 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6308 goto onError;
6309 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6310 goto onError;
6311 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6312 goto onError;
6313 return;
6314 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006315 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006316 }
6317}
6318
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006319/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006320static void
6321raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006322 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006323 PyObject *unicode,
6324 Py_ssize_t startpos, Py_ssize_t endpos,
6325 const char *reason)
6326{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006327 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006328 encoding, unicode, startpos, endpos, reason);
6329 if (*exceptionObject != NULL)
6330 PyCodec_StrictErrors(*exceptionObject);
6331}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006332
6333/* error handling callback helper:
6334 build arguments, call the callback and check the arguments,
6335 put the result into newpos and return the replacement string, which
6336 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006337static PyObject *
6338unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006339 PyObject **errorHandler,
6340 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006341 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006342 Py_ssize_t startpos, Py_ssize_t endpos,
6343 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006344{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006345 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006346 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006347 PyObject *restuple;
6348 PyObject *resunicode;
6349
6350 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006351 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006352 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006353 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006354 }
6355
Benjamin Petersonbac79492012-01-14 13:34:47 -05006356 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 return NULL;
6358 len = PyUnicode_GET_LENGTH(unicode);
6359
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006360 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006362 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006364
6365 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006370 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 Py_DECREF(restuple);
6372 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006374 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006375 &resunicode, newpos)) {
6376 Py_DECREF(restuple);
6377 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006378 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006379 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6380 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6381 Py_DECREF(restuple);
6382 return NULL;
6383 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006384 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006385 *newpos = len + *newpos;
6386 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006387 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 Py_DECREF(restuple);
6389 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006390 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391 Py_INCREF(resunicode);
6392 Py_DECREF(restuple);
6393 return resunicode;
6394}
6395
Alexander Belopolsky40018472011-02-26 01:02:56 +00006396static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006397unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006398 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006399 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006400{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006401 /* input state */
6402 Py_ssize_t pos=0, size;
6403 int kind;
6404 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 /* output object */
6406 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407 /* pointer into the output */
6408 char *str;
6409 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006410 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006411 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6412 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006413 PyObject *errorHandler = NULL;
6414 PyObject *exc = NULL;
6415 /* the following variable is used for caching string comparisons
6416 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6417 int known_errorHandler = -1;
6418
Benjamin Petersonbac79492012-01-14 13:34:47 -05006419 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 return NULL;
6421 size = PyUnicode_GET_LENGTH(unicode);
6422 kind = PyUnicode_KIND(unicode);
6423 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 /* allocate enough for a simple encoding without
6425 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006426 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006427 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006428 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006430 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006431 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 ressize = size;
6433
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006434 while (pos < size) {
6435 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436
Benjamin Peterson29060642009-01-31 22:14:21 +00006437 /* can we encode this? */
6438 if (c<limit) {
6439 /* no overflow check, because we know that the space is enough */
6440 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006441 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006442 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006444 Py_ssize_t requiredsize;
6445 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006446 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006447 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 Py_ssize_t collstart = pos;
6449 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006451 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006452 ++collend;
6453 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6454 if (known_errorHandler==-1) {
6455 if ((errors==NULL) || (!strcmp(errors, "strict")))
6456 known_errorHandler = 1;
6457 else if (!strcmp(errors, "replace"))
6458 known_errorHandler = 2;
6459 else if (!strcmp(errors, "ignore"))
6460 known_errorHandler = 3;
6461 else if (!strcmp(errors, "xmlcharrefreplace"))
6462 known_errorHandler = 4;
6463 else
6464 known_errorHandler = 0;
6465 }
6466 switch (known_errorHandler) {
6467 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006468 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 goto onError;
6470 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006471 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 *str++ = '?'; /* fall through */
6473 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 break;
6476 case 4: /* xmlcharrefreplace */
6477 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006478 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006479 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006480 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006482 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006484 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006485 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006486 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006488 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006489 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006490 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006492 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006493 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006494 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006495 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006496 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006497 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006498 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006499 if (requiredsize > PY_SSIZE_T_MAX - incr)
6500 goto overflow;
6501 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006503 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6504 goto overflow;
6505 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006507 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006508 requiredsize = 2*ressize;
6509 if (_PyBytes_Resize(&res, requiredsize))
6510 goto onError;
6511 str = PyBytes_AS_STRING(res) + respos;
6512 ressize = requiredsize;
6513 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 /* generate replacement */
6515 for (i = collstart; i < collend; ++i) {
6516 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 break;
6520 default:
6521 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006522 encoding, reason, unicode, &exc,
6523 collstart, collend, &newpos);
6524 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006525 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006527 if (PyBytes_Check(repunicode)) {
6528 /* Directly copy bytes result to output. */
6529 repsize = PyBytes_Size(repunicode);
6530 if (repsize > 1) {
6531 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006532 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006533 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6534 Py_DECREF(repunicode);
6535 goto overflow;
6536 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006537 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6538 Py_DECREF(repunicode);
6539 goto onError;
6540 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006541 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006542 ressize += repsize-1;
6543 }
6544 memcpy(str, PyBytes_AsString(repunicode), repsize);
6545 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006547 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006548 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006549 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 /* need more space? (at least enough for what we
6551 have+the replacement+the rest of the string, so
6552 we won't have to check space for encodable characters) */
6553 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006554 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006555 requiredsize = respos;
6556 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6557 goto overflow;
6558 requiredsize += repsize;
6559 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6560 goto overflow;
6561 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006562 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006563 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 requiredsize = 2*ressize;
6565 if (_PyBytes_Resize(&res, requiredsize)) {
6566 Py_DECREF(repunicode);
6567 goto onError;
6568 }
6569 str = PyBytes_AS_STRING(res) + respos;
6570 ressize = requiredsize;
6571 }
6572 /* check if there is anything unencodable in the replacement
6573 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006574 for (i = 0; repsize-->0; ++i, ++str) {
6575 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006577 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 Py_DECREF(repunicode);
6580 goto onError;
6581 }
6582 *str = (char)c;
6583 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006584 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006585 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006586 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006587 }
6588 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006589 /* Resize if we allocated to much */
6590 size = str - PyBytes_AS_STRING(res);
6591 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006592 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006593 if (_PyBytes_Resize(&res, size) < 0)
6594 goto onError;
6595 }
6596
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006597 Py_XDECREF(errorHandler);
6598 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006599 return res;
6600
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006601 overflow:
6602 PyErr_SetString(PyExc_OverflowError,
6603 "encoded result is too long for a Python string");
6604
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006605 onError:
6606 Py_XDECREF(res);
6607 Py_XDECREF(errorHandler);
6608 Py_XDECREF(exc);
6609 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006610}
6611
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006612/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006613PyObject *
6614PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006615 Py_ssize_t size,
6616 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006617{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006618 PyObject *result;
6619 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6620 if (unicode == NULL)
6621 return NULL;
6622 result = unicode_encode_ucs1(unicode, errors, 256);
6623 Py_DECREF(unicode);
6624 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625}
6626
Alexander Belopolsky40018472011-02-26 01:02:56 +00006627PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006628_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006629{
6630 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 PyErr_BadArgument();
6632 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006634 if (PyUnicode_READY(unicode) == -1)
6635 return NULL;
6636 /* Fast path: if it is a one-byte string, construct
6637 bytes object directly. */
6638 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6639 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6640 PyUnicode_GET_LENGTH(unicode));
6641 /* Non-Latin-1 characters present. Defer to above function to
6642 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006644}
6645
6646PyObject*
6647PyUnicode_AsLatin1String(PyObject *unicode)
6648{
6649 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650}
6651
6652/* --- 7-bit ASCII Codec -------------------------------------------------- */
6653
Alexander Belopolsky40018472011-02-26 01:02:56 +00006654PyObject *
6655PyUnicode_DecodeASCII(const char *s,
6656 Py_ssize_t size,
6657 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006660 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006661 int kind;
6662 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006663 Py_ssize_t startinpos;
6664 Py_ssize_t endinpos;
6665 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 const char *e;
6667 PyObject *errorHandler = NULL;
6668 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006669
Guido van Rossumd57fd912000-03-10 22:53:23 +00006670 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006671 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006672
Guido van Rossumd57fd912000-03-10 22:53:23 +00006673 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006674 if (size == 1 && (unsigned char)s[0] < 128)
6675 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006676
Victor Stinner8f674cc2013-04-17 23:02:17 +02006677 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006678 writer.min_length = size;
6679 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006680 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006681
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006683 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006684 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006685 writer.pos = outpos;
6686 if (writer.pos == size)
6687 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006688
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006689 s += writer.pos;
6690 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006692 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006693 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006694 PyUnicode_WRITE(kind, data, writer.pos, c);
6695 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006696 ++s;
6697 }
6698 else {
6699 startinpos = s-starts;
6700 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006701 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 errors, &errorHandler,
6703 "ascii", "ordinal not in range(128)",
6704 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006705 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006707 kind = writer.kind;
6708 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 Py_XDECREF(errorHandler);
6712 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006713 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006714
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006716 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006717 Py_XDECREF(errorHandler);
6718 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006719 return NULL;
6720}
6721
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006722/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006723PyObject *
6724PyUnicode_EncodeASCII(const Py_UNICODE *p,
6725 Py_ssize_t size,
6726 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006727{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006728 PyObject *result;
6729 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6730 if (unicode == NULL)
6731 return NULL;
6732 result = unicode_encode_ucs1(unicode, errors, 128);
6733 Py_DECREF(unicode);
6734 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735}
6736
Alexander Belopolsky40018472011-02-26 01:02:56 +00006737PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006738_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006739{
6740 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 PyErr_BadArgument();
6742 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006744 if (PyUnicode_READY(unicode) == -1)
6745 return NULL;
6746 /* Fast path: if it is an ASCII-only string, construct bytes object
6747 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006748 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006749 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6750 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006752}
6753
6754PyObject *
6755PyUnicode_AsASCIIString(PyObject *unicode)
6756{
6757 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006758}
6759
Victor Stinner99b95382011-07-04 14:23:54 +02006760#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006761
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006762/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006763
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006764#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006765#define NEED_RETRY
6766#endif
6767
Victor Stinner3a50e702011-10-18 21:21:00 +02006768#ifndef WC_ERR_INVALID_CHARS
6769# define WC_ERR_INVALID_CHARS 0x0080
6770#endif
6771
6772static char*
6773code_page_name(UINT code_page, PyObject **obj)
6774{
6775 *obj = NULL;
6776 if (code_page == CP_ACP)
6777 return "mbcs";
6778 if (code_page == CP_UTF7)
6779 return "CP_UTF7";
6780 if (code_page == CP_UTF8)
6781 return "CP_UTF8";
6782
6783 *obj = PyBytes_FromFormat("cp%u", code_page);
6784 if (*obj == NULL)
6785 return NULL;
6786 return PyBytes_AS_STRING(*obj);
6787}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006788
Victor Stinner3a50e702011-10-18 21:21:00 +02006789static DWORD
6790decode_code_page_flags(UINT code_page)
6791{
6792 if (code_page == CP_UTF7) {
6793 /* The CP_UTF7 decoder only supports flags=0 */
6794 return 0;
6795 }
6796 else
6797 return MB_ERR_INVALID_CHARS;
6798}
6799
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006800/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006801 * Decode a byte string from a Windows code page into unicode object in strict
6802 * mode.
6803 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006804 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6805 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006806 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006807static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006808decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006809 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006810 const char *in,
6811 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006812{
Victor Stinner3a50e702011-10-18 21:21:00 +02006813 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006814 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006815 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006816
6817 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006818 assert(insize > 0);
6819 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6820 if (outsize <= 0)
6821 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006822
6823 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006824 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006825 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006826 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006827 if (*v == NULL)
6828 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006829 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006830 }
6831 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006832 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006833 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006834 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006835 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006836 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837 }
6838
6839 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006840 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6841 if (outsize <= 0)
6842 goto error;
6843 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006844
Victor Stinner3a50e702011-10-18 21:21:00 +02006845error:
6846 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6847 return -2;
6848 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006849 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006850}
6851
Victor Stinner3a50e702011-10-18 21:21:00 +02006852/*
6853 * Decode a byte string from a code page into unicode object with an error
6854 * handler.
6855 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006856 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006857 * UnicodeDecodeError exception and returns -1 on error.
6858 */
6859static int
6860decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006861 PyObject **v,
6862 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006863 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006864{
6865 const char *startin = in;
6866 const char *endin = in + size;
6867 const DWORD flags = decode_code_page_flags(code_page);
6868 /* Ideally, we should get reason from FormatMessage. This is the Windows
6869 2000 English version of the message. */
6870 const char *reason = "No mapping for the Unicode character exists "
6871 "in the target code page.";
6872 /* each step cannot decode more than 1 character, but a character can be
6873 represented as a surrogate pair */
6874 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006875 int insize;
6876 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006877 PyObject *errorHandler = NULL;
6878 PyObject *exc = NULL;
6879 PyObject *encoding_obj = NULL;
6880 char *encoding;
6881 DWORD err;
6882 int ret = -1;
6883
6884 assert(size > 0);
6885
6886 encoding = code_page_name(code_page, &encoding_obj);
6887 if (encoding == NULL)
6888 return -1;
6889
Victor Stinner7d00cc12014-03-17 23:08:06 +01006890 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006891 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6892 UnicodeDecodeError. */
6893 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6894 if (exc != NULL) {
6895 PyCodec_StrictErrors(exc);
6896 Py_CLEAR(exc);
6897 }
6898 goto error;
6899 }
6900
6901 if (*v == NULL) {
6902 /* Create unicode object */
6903 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6904 PyErr_NoMemory();
6905 goto error;
6906 }
Victor Stinnerab595942011-12-17 04:59:06 +01006907 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006908 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006909 if (*v == NULL)
6910 goto error;
6911 startout = PyUnicode_AS_UNICODE(*v);
6912 }
6913 else {
6914 /* Extend unicode object */
6915 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6916 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6917 PyErr_NoMemory();
6918 goto error;
6919 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006920 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006921 goto error;
6922 startout = PyUnicode_AS_UNICODE(*v) + n;
6923 }
6924
6925 /* Decode the byte string character per character */
6926 out = startout;
6927 while (in < endin)
6928 {
6929 /* Decode a character */
6930 insize = 1;
6931 do
6932 {
6933 outsize = MultiByteToWideChar(code_page, flags,
6934 in, insize,
6935 buffer, Py_ARRAY_LENGTH(buffer));
6936 if (outsize > 0)
6937 break;
6938 err = GetLastError();
6939 if (err != ERROR_NO_UNICODE_TRANSLATION
6940 && err != ERROR_INSUFFICIENT_BUFFER)
6941 {
6942 PyErr_SetFromWindowsErr(0);
6943 goto error;
6944 }
6945 insize++;
6946 }
6947 /* 4=maximum length of a UTF-8 sequence */
6948 while (insize <= 4 && (in + insize) <= endin);
6949
6950 if (outsize <= 0) {
6951 Py_ssize_t startinpos, endinpos, outpos;
6952
Victor Stinner7d00cc12014-03-17 23:08:06 +01006953 /* last character in partial decode? */
6954 if (in + insize >= endin && !final)
6955 break;
6956
Victor Stinner3a50e702011-10-18 21:21:00 +02006957 startinpos = in - startin;
6958 endinpos = startinpos + 1;
6959 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006960 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 errors, &errorHandler,
6962 encoding, reason,
6963 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006964 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006965 {
6966 goto error;
6967 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006968 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006969 }
6970 else {
6971 in += insize;
6972 memcpy(out, buffer, outsize * sizeof(wchar_t));
6973 out += outsize;
6974 }
6975 }
6976
6977 /* write a NUL character at the end */
6978 *out = 0;
6979
6980 /* Extend unicode object */
6981 outsize = out - startout;
6982 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006983 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006984 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02006985 /* (in - startin) <= size and size is an int */
6986 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02006987
6988error:
6989 Py_XDECREF(encoding_obj);
6990 Py_XDECREF(errorHandler);
6991 Py_XDECREF(exc);
6992 return ret;
6993}
6994
Victor Stinner3a50e702011-10-18 21:21:00 +02006995static PyObject *
6996decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006997 const char *s, Py_ssize_t size,
6998 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006999{
Victor Stinner76a31a62011-11-04 00:05:13 +01007000 PyObject *v = NULL;
7001 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007002
Victor Stinner3a50e702011-10-18 21:21:00 +02007003 if (code_page < 0) {
7004 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7005 return NULL;
7006 }
7007
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007008 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007009 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007010
Victor Stinner76a31a62011-11-04 00:05:13 +01007011 do
7012 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007013#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007014 if (size > INT_MAX) {
7015 chunk_size = INT_MAX;
7016 final = 0;
7017 done = 0;
7018 }
7019 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007021 {
7022 chunk_size = (int)size;
7023 final = (consumed == NULL);
7024 done = 1;
7025 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007026
Victor Stinner76a31a62011-11-04 00:05:13 +01007027 if (chunk_size == 0 && done) {
7028 if (v != NULL)
7029 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007030 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007031 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007032
Victor Stinner76a31a62011-11-04 00:05:13 +01007033 converted = decode_code_page_strict(code_page, &v,
7034 s, chunk_size);
7035 if (converted == -2)
7036 converted = decode_code_page_errors(code_page, &v,
7037 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007038 errors, final);
7039 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007040
7041 if (converted < 0) {
7042 Py_XDECREF(v);
7043 return NULL;
7044 }
7045
7046 if (consumed)
7047 *consumed += converted;
7048
7049 s += converted;
7050 size -= converted;
7051 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007052
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007053 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054}
7055
Alexander Belopolsky40018472011-02-26 01:02:56 +00007056PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007057PyUnicode_DecodeCodePageStateful(int code_page,
7058 const char *s,
7059 Py_ssize_t size,
7060 const char *errors,
7061 Py_ssize_t *consumed)
7062{
7063 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7064}
7065
7066PyObject *
7067PyUnicode_DecodeMBCSStateful(const char *s,
7068 Py_ssize_t size,
7069 const char *errors,
7070 Py_ssize_t *consumed)
7071{
7072 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7073}
7074
7075PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007076PyUnicode_DecodeMBCS(const char *s,
7077 Py_ssize_t size,
7078 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007079{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7081}
7082
Victor Stinner3a50e702011-10-18 21:21:00 +02007083static DWORD
7084encode_code_page_flags(UINT code_page, const char *errors)
7085{
7086 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007087 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 }
7089 else if (code_page == CP_UTF7) {
7090 /* CP_UTF7 only supports flags=0 */
7091 return 0;
7092 }
7093 else {
7094 if (errors != NULL && strcmp(errors, "replace") == 0)
7095 return 0;
7096 else
7097 return WC_NO_BEST_FIT_CHARS;
7098 }
7099}
7100
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007101/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 * Encode a Unicode string to a Windows code page into a byte string in strict
7103 * mode.
7104 *
7105 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007106 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007107 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007108static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007109encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007110 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112{
Victor Stinner554f3f02010-06-16 23:33:54 +00007113 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007114 BOOL *pusedDefaultChar = &usedDefaultChar;
7115 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007116 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007117 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007118 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007119 const DWORD flags = encode_code_page_flags(code_page, NULL);
7120 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007121 /* Create a substring so that we can get the UTF-16 representation
7122 of just the slice under consideration. */
7123 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007124
Martin v. Löwis3d325192011-11-04 18:23:06 +01007125 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007126
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007128 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007130 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007131
Victor Stinner2fc507f2011-11-04 20:06:39 +01007132 substring = PyUnicode_Substring(unicode, offset, offset+len);
7133 if (substring == NULL)
7134 return -1;
7135 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7136 if (p == NULL) {
7137 Py_DECREF(substring);
7138 return -1;
7139 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007140 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007141
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007142 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007144 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 NULL, 0,
7146 NULL, pusedDefaultChar);
7147 if (outsize <= 0)
7148 goto error;
7149 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007150 if (pusedDefaultChar && *pusedDefaultChar) {
7151 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007153 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007154
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007156 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007158 if (*outbytes == NULL) {
7159 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007160 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007161 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007163 }
7164 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007165 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 const Py_ssize_t n = PyBytes_Size(*outbytes);
7167 if (outsize > PY_SSIZE_T_MAX - n) {
7168 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007169 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007170 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007172 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7173 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007175 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007177 }
7178
7179 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007181 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 out, outsize,
7183 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007184 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 if (outsize <= 0)
7186 goto error;
7187 if (pusedDefaultChar && *pusedDefaultChar)
7188 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007189 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007190
Victor Stinner3a50e702011-10-18 21:21:00 +02007191error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007192 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7194 return -2;
7195 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007196 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007197}
7198
Victor Stinner3a50e702011-10-18 21:21:00 +02007199/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007200 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 * error handler.
7202 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007203 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 * -1 on other error.
7205 */
7206static int
7207encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007208 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007209 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007210{
Victor Stinner3a50e702011-10-18 21:21:00 +02007211 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007212 Py_ssize_t pos = unicode_offset;
7213 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 /* Ideally, we should get reason from FormatMessage. This is the Windows
7215 2000 English version of the message. */
7216 const char *reason = "invalid character";
7217 /* 4=maximum length of a UTF-8 sequence */
7218 char buffer[4];
7219 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7220 Py_ssize_t outsize;
7221 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 PyObject *errorHandler = NULL;
7223 PyObject *exc = NULL;
7224 PyObject *encoding_obj = NULL;
7225 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007226 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 PyObject *rep;
7228 int ret = -1;
7229
7230 assert(insize > 0);
7231
7232 encoding = code_page_name(code_page, &encoding_obj);
7233 if (encoding == NULL)
7234 return -1;
7235
7236 if (errors == NULL || strcmp(errors, "strict") == 0) {
7237 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7238 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007239 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 if (exc != NULL) {
7241 PyCodec_StrictErrors(exc);
7242 Py_DECREF(exc);
7243 }
7244 Py_XDECREF(encoding_obj);
7245 return -1;
7246 }
7247
7248 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7249 pusedDefaultChar = &usedDefaultChar;
7250 else
7251 pusedDefaultChar = NULL;
7252
7253 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7254 PyErr_NoMemory();
7255 goto error;
7256 }
7257 outsize = insize * Py_ARRAY_LENGTH(buffer);
7258
7259 if (*outbytes == NULL) {
7260 /* Create string object */
7261 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7262 if (*outbytes == NULL)
7263 goto error;
7264 out = PyBytes_AS_STRING(*outbytes);
7265 }
7266 else {
7267 /* Extend string object */
7268 Py_ssize_t n = PyBytes_Size(*outbytes);
7269 if (n > PY_SSIZE_T_MAX - outsize) {
7270 PyErr_NoMemory();
7271 goto error;
7272 }
7273 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7274 goto error;
7275 out = PyBytes_AS_STRING(*outbytes) + n;
7276 }
7277
7278 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007279 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007280 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007281 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7282 wchar_t chars[2];
7283 int charsize;
7284 if (ch < 0x10000) {
7285 chars[0] = (wchar_t)ch;
7286 charsize = 1;
7287 }
7288 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007289 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7290 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007291 charsize = 2;
7292 }
7293
Victor Stinner3a50e702011-10-18 21:21:00 +02007294 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007295 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007296 buffer, Py_ARRAY_LENGTH(buffer),
7297 NULL, pusedDefaultChar);
7298 if (outsize > 0) {
7299 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7300 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007301 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007302 memcpy(out, buffer, outsize);
7303 out += outsize;
7304 continue;
7305 }
7306 }
7307 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7308 PyErr_SetFromWindowsErr(0);
7309 goto error;
7310 }
7311
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 rep = unicode_encode_call_errorhandler(
7313 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007314 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007315 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007316 if (rep == NULL)
7317 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007318 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007319
7320 if (PyBytes_Check(rep)) {
7321 outsize = PyBytes_GET_SIZE(rep);
7322 if (outsize != 1) {
7323 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7324 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7325 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7326 Py_DECREF(rep);
7327 goto error;
7328 }
7329 out = PyBytes_AS_STRING(*outbytes) + offset;
7330 }
7331 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7332 out += outsize;
7333 }
7334 else {
7335 Py_ssize_t i;
7336 enum PyUnicode_Kind kind;
7337 void *data;
7338
Benjamin Petersonbac79492012-01-14 13:34:47 -05007339 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007340 Py_DECREF(rep);
7341 goto error;
7342 }
7343
7344 outsize = PyUnicode_GET_LENGTH(rep);
7345 if (outsize != 1) {
7346 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7347 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7348 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7349 Py_DECREF(rep);
7350 goto error;
7351 }
7352 out = PyBytes_AS_STRING(*outbytes) + offset;
7353 }
7354 kind = PyUnicode_KIND(rep);
7355 data = PyUnicode_DATA(rep);
7356 for (i=0; i < outsize; i++) {
7357 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7358 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007359 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007360 encoding, unicode,
7361 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007362 "unable to encode error handler result to ASCII");
7363 Py_DECREF(rep);
7364 goto error;
7365 }
7366 *out = (unsigned char)ch;
7367 out++;
7368 }
7369 }
7370 Py_DECREF(rep);
7371 }
7372 /* write a NUL byte */
7373 *out = 0;
7374 outsize = out - PyBytes_AS_STRING(*outbytes);
7375 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7376 if (_PyBytes_Resize(outbytes, outsize) < 0)
7377 goto error;
7378 ret = 0;
7379
7380error:
7381 Py_XDECREF(encoding_obj);
7382 Py_XDECREF(errorHandler);
7383 Py_XDECREF(exc);
7384 return ret;
7385}
7386
Victor Stinner3a50e702011-10-18 21:21:00 +02007387static PyObject *
7388encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007389 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 const char *errors)
7391{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007392 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007394 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007395 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007396
Victor Stinner29dacf22015-01-26 16:41:32 +01007397 if (!PyUnicode_Check(unicode)) {
7398 PyErr_BadArgument();
7399 return NULL;
7400 }
7401
Benjamin Petersonbac79492012-01-14 13:34:47 -05007402 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007403 return NULL;
7404 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007405
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 if (code_page < 0) {
7407 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7408 return NULL;
7409 }
7410
Martin v. Löwis3d325192011-11-04 18:23:06 +01007411 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007412 return PyBytes_FromStringAndSize(NULL, 0);
7413
Victor Stinner7581cef2011-11-03 22:32:33 +01007414 offset = 0;
7415 do
7416 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007417#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007418 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007419 chunks. */
7420 if (len > INT_MAX/2) {
7421 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007422 done = 0;
7423 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007424 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007425#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007426 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007427 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007428 done = 1;
7429 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007430
Victor Stinner76a31a62011-11-04 00:05:13 +01007431 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007432 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007433 errors);
7434 if (ret == -2)
7435 ret = encode_code_page_errors(code_page, &outbytes,
7436 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007437 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007438 if (ret < 0) {
7439 Py_XDECREF(outbytes);
7440 return NULL;
7441 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007442
Victor Stinner7581cef2011-11-03 22:32:33 +01007443 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007444 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007445 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007446
Victor Stinner3a50e702011-10-18 21:21:00 +02007447 return outbytes;
7448}
7449
7450PyObject *
7451PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7452 Py_ssize_t size,
7453 const char *errors)
7454{
Victor Stinner7581cef2011-11-03 22:32:33 +01007455 PyObject *unicode, *res;
7456 unicode = PyUnicode_FromUnicode(p, size);
7457 if (unicode == NULL)
7458 return NULL;
7459 res = encode_code_page(CP_ACP, unicode, errors);
7460 Py_DECREF(unicode);
7461 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007462}
7463
7464PyObject *
7465PyUnicode_EncodeCodePage(int code_page,
7466 PyObject *unicode,
7467 const char *errors)
7468{
Victor Stinner7581cef2011-11-03 22:32:33 +01007469 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007470}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007471
Alexander Belopolsky40018472011-02-26 01:02:56 +00007472PyObject *
7473PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007474{
Victor Stinner7581cef2011-11-03 22:32:33 +01007475 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007476}
7477
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007478#undef NEED_RETRY
7479
Victor Stinner99b95382011-07-04 14:23:54 +02007480#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007481
Guido van Rossumd57fd912000-03-10 22:53:23 +00007482/* --- Character Mapping Codec -------------------------------------------- */
7483
Victor Stinnerfb161b12013-04-18 01:44:27 +02007484static int
7485charmap_decode_string(const char *s,
7486 Py_ssize_t size,
7487 PyObject *mapping,
7488 const char *errors,
7489 _PyUnicodeWriter *writer)
7490{
7491 const char *starts = s;
7492 const char *e;
7493 Py_ssize_t startinpos, endinpos;
7494 PyObject *errorHandler = NULL, *exc = NULL;
7495 Py_ssize_t maplen;
7496 enum PyUnicode_Kind mapkind;
7497 void *mapdata;
7498 Py_UCS4 x;
7499 unsigned char ch;
7500
7501 if (PyUnicode_READY(mapping) == -1)
7502 return -1;
7503
7504 maplen = PyUnicode_GET_LENGTH(mapping);
7505 mapdata = PyUnicode_DATA(mapping);
7506 mapkind = PyUnicode_KIND(mapping);
7507
7508 e = s + size;
7509
7510 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7511 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7512 * is disabled in encoding aliases, latin1 is preferred because
7513 * its implementation is faster. */
7514 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7515 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7516 Py_UCS4 maxchar = writer->maxchar;
7517
7518 assert (writer->kind == PyUnicode_1BYTE_KIND);
7519 while (s < e) {
7520 ch = *s;
7521 x = mapdata_ucs1[ch];
7522 if (x > maxchar) {
7523 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7524 goto onError;
7525 maxchar = writer->maxchar;
7526 outdata = (Py_UCS1 *)writer->data;
7527 }
7528 outdata[writer->pos] = x;
7529 writer->pos++;
7530 ++s;
7531 }
7532 return 0;
7533 }
7534
7535 while (s < e) {
7536 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7537 enum PyUnicode_Kind outkind = writer->kind;
7538 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7539 if (outkind == PyUnicode_1BYTE_KIND) {
7540 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7541 Py_UCS4 maxchar = writer->maxchar;
7542 while (s < e) {
7543 ch = *s;
7544 x = mapdata_ucs2[ch];
7545 if (x > maxchar)
7546 goto Error;
7547 outdata[writer->pos] = x;
7548 writer->pos++;
7549 ++s;
7550 }
7551 break;
7552 }
7553 else if (outkind == PyUnicode_2BYTE_KIND) {
7554 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7555 while (s < e) {
7556 ch = *s;
7557 x = mapdata_ucs2[ch];
7558 if (x == 0xFFFE)
7559 goto Error;
7560 outdata[writer->pos] = x;
7561 writer->pos++;
7562 ++s;
7563 }
7564 break;
7565 }
7566 }
7567 ch = *s;
7568
7569 if (ch < maplen)
7570 x = PyUnicode_READ(mapkind, mapdata, ch);
7571 else
7572 x = 0xfffe; /* invalid value */
7573Error:
7574 if (x == 0xfffe)
7575 {
7576 /* undefined mapping */
7577 startinpos = s-starts;
7578 endinpos = startinpos+1;
7579 if (unicode_decode_call_errorhandler_writer(
7580 errors, &errorHandler,
7581 "charmap", "character maps to <undefined>",
7582 &starts, &e, &startinpos, &endinpos, &exc, &s,
7583 writer)) {
7584 goto onError;
7585 }
7586 continue;
7587 }
7588
7589 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7590 goto onError;
7591 ++s;
7592 }
7593 Py_XDECREF(errorHandler);
7594 Py_XDECREF(exc);
7595 return 0;
7596
7597onError:
7598 Py_XDECREF(errorHandler);
7599 Py_XDECREF(exc);
7600 return -1;
7601}
7602
7603static int
7604charmap_decode_mapping(const char *s,
7605 Py_ssize_t size,
7606 PyObject *mapping,
7607 const char *errors,
7608 _PyUnicodeWriter *writer)
7609{
7610 const char *starts = s;
7611 const char *e;
7612 Py_ssize_t startinpos, endinpos;
7613 PyObject *errorHandler = NULL, *exc = NULL;
7614 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007615 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007616
7617 e = s + size;
7618
7619 while (s < e) {
7620 ch = *s;
7621
7622 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7623 key = PyLong_FromLong((long)ch);
7624 if (key == NULL)
7625 goto onError;
7626
7627 item = PyObject_GetItem(mapping, key);
7628 Py_DECREF(key);
7629 if (item == NULL) {
7630 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7631 /* No mapping found means: mapping is undefined. */
7632 PyErr_Clear();
7633 goto Undefined;
7634 } else
7635 goto onError;
7636 }
7637
7638 /* Apply mapping */
7639 if (item == Py_None)
7640 goto Undefined;
7641 if (PyLong_Check(item)) {
7642 long value = PyLong_AS_LONG(item);
7643 if (value == 0xFFFE)
7644 goto Undefined;
7645 if (value < 0 || value > MAX_UNICODE) {
7646 PyErr_Format(PyExc_TypeError,
7647 "character mapping must be in range(0x%lx)",
7648 (unsigned long)MAX_UNICODE + 1);
7649 goto onError;
7650 }
7651
7652 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7653 goto onError;
7654 }
7655 else if (PyUnicode_Check(item)) {
7656 if (PyUnicode_READY(item) == -1)
7657 goto onError;
7658 if (PyUnicode_GET_LENGTH(item) == 1) {
7659 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7660 if (value == 0xFFFE)
7661 goto Undefined;
7662 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7663 goto onError;
7664 }
7665 else {
7666 writer->overallocate = 1;
7667 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7668 goto onError;
7669 }
7670 }
7671 else {
7672 /* wrong return value */
7673 PyErr_SetString(PyExc_TypeError,
7674 "character mapping must return integer, None or str");
7675 goto onError;
7676 }
7677 Py_CLEAR(item);
7678 ++s;
7679 continue;
7680
7681Undefined:
7682 /* undefined mapping */
7683 Py_CLEAR(item);
7684 startinpos = s-starts;
7685 endinpos = startinpos+1;
7686 if (unicode_decode_call_errorhandler_writer(
7687 errors, &errorHandler,
7688 "charmap", "character maps to <undefined>",
7689 &starts, &e, &startinpos, &endinpos, &exc, &s,
7690 writer)) {
7691 goto onError;
7692 }
7693 }
7694 Py_XDECREF(errorHandler);
7695 Py_XDECREF(exc);
7696 return 0;
7697
7698onError:
7699 Py_XDECREF(item);
7700 Py_XDECREF(errorHandler);
7701 Py_XDECREF(exc);
7702 return -1;
7703}
7704
Alexander Belopolsky40018472011-02-26 01:02:56 +00007705PyObject *
7706PyUnicode_DecodeCharmap(const char *s,
7707 Py_ssize_t size,
7708 PyObject *mapping,
7709 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007710{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007711 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007712
Guido van Rossumd57fd912000-03-10 22:53:23 +00007713 /* Default to Latin-1 */
7714 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007715 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007716
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007718 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007719 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007720 writer.min_length = size;
7721 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007722 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007723
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007724 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007725 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7726 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007727 }
7728 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007729 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7730 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007731 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007732 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007733
Benjamin Peterson29060642009-01-31 22:14:21 +00007734 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007735 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007736 return NULL;
7737}
7738
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007739/* Charmap encoding: the lookup table */
7740
Alexander Belopolsky40018472011-02-26 01:02:56 +00007741struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007742 PyObject_HEAD
7743 unsigned char level1[32];
7744 int count2, count3;
7745 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007746};
7747
7748static PyObject*
7749encoding_map_size(PyObject *obj, PyObject* args)
7750{
7751 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007752 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007753 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007754}
7755
7756static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007757 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007758 PyDoc_STR("Return the size (in bytes) of this object") },
7759 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007760};
7761
7762static void
7763encoding_map_dealloc(PyObject* o)
7764{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007765 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007766}
7767
7768static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007769 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 "EncodingMap", /*tp_name*/
7771 sizeof(struct encoding_map), /*tp_basicsize*/
7772 0, /*tp_itemsize*/
7773 /* methods */
7774 encoding_map_dealloc, /*tp_dealloc*/
7775 0, /*tp_print*/
7776 0, /*tp_getattr*/
7777 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007778 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 0, /*tp_repr*/
7780 0, /*tp_as_number*/
7781 0, /*tp_as_sequence*/
7782 0, /*tp_as_mapping*/
7783 0, /*tp_hash*/
7784 0, /*tp_call*/
7785 0, /*tp_str*/
7786 0, /*tp_getattro*/
7787 0, /*tp_setattro*/
7788 0, /*tp_as_buffer*/
7789 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7790 0, /*tp_doc*/
7791 0, /*tp_traverse*/
7792 0, /*tp_clear*/
7793 0, /*tp_richcompare*/
7794 0, /*tp_weaklistoffset*/
7795 0, /*tp_iter*/
7796 0, /*tp_iternext*/
7797 encoding_map_methods, /*tp_methods*/
7798 0, /*tp_members*/
7799 0, /*tp_getset*/
7800 0, /*tp_base*/
7801 0, /*tp_dict*/
7802 0, /*tp_descr_get*/
7803 0, /*tp_descr_set*/
7804 0, /*tp_dictoffset*/
7805 0, /*tp_init*/
7806 0, /*tp_alloc*/
7807 0, /*tp_new*/
7808 0, /*tp_free*/
7809 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007810};
7811
7812PyObject*
7813PyUnicode_BuildEncodingMap(PyObject* string)
7814{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007815 PyObject *result;
7816 struct encoding_map *mresult;
7817 int i;
7818 int need_dict = 0;
7819 unsigned char level1[32];
7820 unsigned char level2[512];
7821 unsigned char *mlevel1, *mlevel2, *mlevel3;
7822 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007823 int kind;
7824 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007825 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007826 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007827
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007828 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829 PyErr_BadArgument();
7830 return NULL;
7831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007832 kind = PyUnicode_KIND(string);
7833 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007834 length = PyUnicode_GET_LENGTH(string);
7835 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007836 memset(level1, 0xFF, sizeof level1);
7837 memset(level2, 0xFF, sizeof level2);
7838
7839 /* If there isn't a one-to-one mapping of NULL to \0,
7840 or if there are non-BMP characters, we need to use
7841 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007842 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007844 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007845 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007846 ch = PyUnicode_READ(kind, data, i);
7847 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007848 need_dict = 1;
7849 break;
7850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007851 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852 /* unmapped character */
7853 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007854 l1 = ch >> 11;
7855 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007856 if (level1[l1] == 0xFF)
7857 level1[l1] = count2++;
7858 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007859 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007860 }
7861
7862 if (count2 >= 0xFF || count3 >= 0xFF)
7863 need_dict = 1;
7864
7865 if (need_dict) {
7866 PyObject *result = PyDict_New();
7867 PyObject *key, *value;
7868 if (!result)
7869 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007870 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007871 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007872 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873 if (!key || !value)
7874 goto failed1;
7875 if (PyDict_SetItem(result, key, value) == -1)
7876 goto failed1;
7877 Py_DECREF(key);
7878 Py_DECREF(value);
7879 }
7880 return result;
7881 failed1:
7882 Py_XDECREF(key);
7883 Py_XDECREF(value);
7884 Py_DECREF(result);
7885 return NULL;
7886 }
7887
7888 /* Create a three-level trie */
7889 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7890 16*count2 + 128*count3 - 1);
7891 if (!result)
7892 return PyErr_NoMemory();
7893 PyObject_Init(result, &EncodingMapType);
7894 mresult = (struct encoding_map*)result;
7895 mresult->count2 = count2;
7896 mresult->count3 = count3;
7897 mlevel1 = mresult->level1;
7898 mlevel2 = mresult->level23;
7899 mlevel3 = mresult->level23 + 16*count2;
7900 memcpy(mlevel1, level1, 32);
7901 memset(mlevel2, 0xFF, 16*count2);
7902 memset(mlevel3, 0, 128*count3);
7903 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007904 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007906 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7907 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007908 /* unmapped character */
7909 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007910 o1 = ch>>11;
7911 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 i2 = 16*mlevel1[o1] + o2;
7913 if (mlevel2[i2] == 0xFF)
7914 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007915 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916 i3 = 128*mlevel2[i2] + o3;
7917 mlevel3[i3] = i;
7918 }
7919 return result;
7920}
7921
7922static int
Victor Stinner22168992011-11-20 17:09:18 +01007923encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007924{
7925 struct encoding_map *map = (struct encoding_map*)mapping;
7926 int l1 = c>>11;
7927 int l2 = (c>>7) & 0xF;
7928 int l3 = c & 0x7F;
7929 int i;
7930
Victor Stinner22168992011-11-20 17:09:18 +01007931 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 if (c == 0)
7934 return 0;
7935 /* level 1*/
7936 i = map->level1[l1];
7937 if (i == 0xFF) {
7938 return -1;
7939 }
7940 /* level 2*/
7941 i = map->level23[16*i+l2];
7942 if (i == 0xFF) {
7943 return -1;
7944 }
7945 /* level 3 */
7946 i = map->level23[16*map->count2 + 128*i + l3];
7947 if (i == 0) {
7948 return -1;
7949 }
7950 return i;
7951}
7952
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007953/* Lookup the character ch in the mapping. If the character
7954 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007955 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007956static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007957charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007958{
Christian Heimes217cfd12007-12-02 14:31:20 +00007959 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007960 PyObject *x;
7961
7962 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964 x = PyObject_GetItem(mapping, w);
7965 Py_DECREF(w);
7966 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007967 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7968 /* No mapping found means: mapping is undefined. */
7969 PyErr_Clear();
7970 x = Py_None;
7971 Py_INCREF(x);
7972 return x;
7973 } else
7974 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007975 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007976 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007978 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007979 long value = PyLong_AS_LONG(x);
7980 if (value < 0 || value > 255) {
7981 PyErr_SetString(PyExc_TypeError,
7982 "character mapping must be in range(256)");
7983 Py_DECREF(x);
7984 return NULL;
7985 }
7986 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007988 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007991 /* wrong return value */
7992 PyErr_Format(PyExc_TypeError,
7993 "character mapping must return integer, bytes or None, not %.400s",
7994 x->ob_type->tp_name);
7995 Py_DECREF(x);
7996 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 }
7998}
7999
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008000static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008001charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008003 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8004 /* exponentially overallocate to minimize reallocations */
8005 if (requiredsize < 2*outsize)
8006 requiredsize = 2*outsize;
8007 if (_PyBytes_Resize(outobj, requiredsize))
8008 return -1;
8009 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010}
8011
Benjamin Peterson14339b62009-01-31 16:36:08 +00008012typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008013 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008014} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008015/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008016 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008017 space is available. Return a new reference to the object that
8018 was put in the output buffer, or Py_None, if the mapping was undefined
8019 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008020 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008021static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008022charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008023 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008024{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 PyObject *rep;
8026 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008027 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008028
Christian Heimes90aa7642007-12-19 02:45:37 +00008029 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008030 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032 if (res == -1)
8033 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008034 if (outsize<requiredsize)
8035 if (charmapencode_resize(outobj, outpos, requiredsize))
8036 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008037 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 outstart[(*outpos)++] = (char)res;
8039 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040 }
8041
8042 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 Py_DECREF(rep);
8047 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008048 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 if (PyLong_Check(rep)) {
8050 Py_ssize_t requiredsize = *outpos+1;
8051 if (outsize<requiredsize)
8052 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8053 Py_DECREF(rep);
8054 return enc_EXCEPTION;
8055 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008056 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008058 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 else {
8060 const char *repchars = PyBytes_AS_STRING(rep);
8061 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8062 Py_ssize_t requiredsize = *outpos+repsize;
8063 if (outsize<requiredsize)
8064 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8065 Py_DECREF(rep);
8066 return enc_EXCEPTION;
8067 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008068 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 memcpy(outstart + *outpos, repchars, repsize);
8070 *outpos += repsize;
8071 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008072 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073 Py_DECREF(rep);
8074 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075}
8076
8077/* handle an error in PyUnicode_EncodeCharmap
8078 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008079static int
8080charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008081 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008082 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008083 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008084 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085{
8086 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008087 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008088 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008089 enum PyUnicode_Kind kind;
8090 void *data;
8091 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008093 Py_ssize_t collstartpos = *inpos;
8094 Py_ssize_t collendpos = *inpos+1;
8095 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008096 char *encoding = "charmap";
8097 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008099 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008100 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008101
Benjamin Petersonbac79492012-01-14 13:34:47 -05008102 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008103 return -1;
8104 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 /* find all unencodable characters */
8106 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008108 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008109 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008110 val = encoding_map_lookup(ch, mapping);
8111 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 break;
8113 ++collendpos;
8114 continue;
8115 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008117 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8118 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008119 if (rep==NULL)
8120 return -1;
8121 else if (rep!=Py_None) {
8122 Py_DECREF(rep);
8123 break;
8124 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008125 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127 }
8128 /* cache callback name lookup
8129 * (if not done yet, i.e. it's the first error) */
8130 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 if ((errors==NULL) || (!strcmp(errors, "strict")))
8132 *known_errorHandler = 1;
8133 else if (!strcmp(errors, "replace"))
8134 *known_errorHandler = 2;
8135 else if (!strcmp(errors, "ignore"))
8136 *known_errorHandler = 3;
8137 else if (!strcmp(errors, "xmlcharrefreplace"))
8138 *known_errorHandler = 4;
8139 else
8140 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141 }
8142 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008143 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008144 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008145 return -1;
8146 case 2: /* replace */
8147 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 x = charmapencode_output('?', mapping, res, respos);
8149 if (x==enc_EXCEPTION) {
8150 return -1;
8151 }
8152 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008153 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 return -1;
8155 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 }
8157 /* fall through */
8158 case 3: /* ignore */
8159 *inpos = collendpos;
8160 break;
8161 case 4: /* xmlcharrefreplace */
8162 /* generate replacement (temporarily (mis)uses p) */
8163 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 char buffer[2+29+1+1];
8165 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008166 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 for (cp = buffer; *cp; ++cp) {
8168 x = charmapencode_output(*cp, mapping, res, respos);
8169 if (x==enc_EXCEPTION)
8170 return -1;
8171 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008172 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 return -1;
8174 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008175 }
8176 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 *inpos = collendpos;
8178 break;
8179 default:
8180 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008181 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008185 if (PyBytes_Check(repunicode)) {
8186 /* Directly copy bytes result to output. */
8187 Py_ssize_t outsize = PyBytes_Size(*res);
8188 Py_ssize_t requiredsize;
8189 repsize = PyBytes_Size(repunicode);
8190 requiredsize = *respos + repsize;
8191 if (requiredsize > outsize)
8192 /* Make room for all additional bytes. */
8193 if (charmapencode_resize(res, respos, requiredsize)) {
8194 Py_DECREF(repunicode);
8195 return -1;
8196 }
8197 memcpy(PyBytes_AsString(*res) + *respos,
8198 PyBytes_AsString(repunicode), repsize);
8199 *respos += repsize;
8200 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008201 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008202 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008203 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008205 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008206 Py_DECREF(repunicode);
8207 return -1;
8208 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008209 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008210 data = PyUnicode_DATA(repunicode);
8211 kind = PyUnicode_KIND(repunicode);
8212 for (index = 0; index < repsize; index++) {
8213 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8214 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008216 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008217 return -1;
8218 }
8219 else if (x==enc_FAILED) {
8220 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008221 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 return -1;
8223 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008224 }
8225 *inpos = newpos;
8226 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227 }
8228 return 0;
8229}
8230
Alexander Belopolsky40018472011-02-26 01:02:56 +00008231PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008232_PyUnicode_EncodeCharmap(PyObject *unicode,
8233 PyObject *mapping,
8234 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008235{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 /* output object */
8237 PyObject *res = NULL;
8238 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008239 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008240 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008242 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 PyObject *errorHandler = NULL;
8244 PyObject *exc = NULL;
8245 /* the following variable is used for caching string comparisons
8246 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8247 * 3=ignore, 4=xmlcharrefreplace */
8248 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008249 void *data;
8250 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251
Benjamin Petersonbac79492012-01-14 13:34:47 -05008252 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008253 return NULL;
8254 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008255 data = PyUnicode_DATA(unicode);
8256 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008257
Guido van Rossumd57fd912000-03-10 22:53:23 +00008258 /* Default to Latin-1 */
8259 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008260 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008261
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 /* allocate enough for a simple encoding without
8263 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008264 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 if (res == NULL)
8266 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008267 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008268 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008269
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008270 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008271 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008273 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 if (x==enc_EXCEPTION) /* error */
8275 goto onError;
8276 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008277 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 &exc,
8279 &known_errorHandler, &errorHandler, errors,
8280 &res, &respos)) {
8281 goto onError;
8282 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008283 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 else
8285 /* done with this character => adjust input position */
8286 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008288
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008290 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008291 if (_PyBytes_Resize(&res, respos) < 0)
8292 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008293
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294 Py_XDECREF(exc);
8295 Py_XDECREF(errorHandler);
8296 return res;
8297
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299 Py_XDECREF(res);
8300 Py_XDECREF(exc);
8301 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008302 return NULL;
8303}
8304
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008305/* Deprecated */
8306PyObject *
8307PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8308 Py_ssize_t size,
8309 PyObject *mapping,
8310 const char *errors)
8311{
8312 PyObject *result;
8313 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8314 if (unicode == NULL)
8315 return NULL;
8316 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8317 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008318 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008319}
8320
Alexander Belopolsky40018472011-02-26 01:02:56 +00008321PyObject *
8322PyUnicode_AsCharmapString(PyObject *unicode,
8323 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324{
8325 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 PyErr_BadArgument();
8327 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008328 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008329 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330}
8331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008333static void
8334make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008335 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008336 Py_ssize_t startpos, Py_ssize_t endpos,
8337 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008340 *exceptionObject = _PyUnicodeTranslateError_Create(
8341 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008342 }
8343 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8345 goto onError;
8346 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8347 goto onError;
8348 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8349 goto onError;
8350 return;
8351 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008352 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353 }
8354}
8355
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356/* error handling callback helper:
8357 build arguments, call the callback and check the arguments,
8358 put the result into newpos and return the replacement string, which
8359 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008360static PyObject *
8361unicode_translate_call_errorhandler(const char *errors,
8362 PyObject **errorHandler,
8363 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008365 Py_ssize_t startpos, Py_ssize_t endpos,
8366 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008368 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008370 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 PyObject *restuple;
8372 PyObject *resunicode;
8373
8374 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 }
8379
8380 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008381 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008383 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384
8385 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008387 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008390 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 Py_DECREF(restuple);
8392 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 }
8394 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 &resunicode, &i_newpos)) {
8396 Py_DECREF(restuple);
8397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008399 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008400 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008401 else
8402 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008403 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008404 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 Py_DECREF(restuple);
8406 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008407 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 Py_INCREF(resunicode);
8409 Py_DECREF(restuple);
8410 return resunicode;
8411}
8412
8413/* Lookup the character ch in the mapping and put the result in result,
8414 which must be decrefed by the caller.
8415 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008416static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418{
Christian Heimes217cfd12007-12-02 14:31:20 +00008419 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420 PyObject *x;
8421
8422 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424 x = PyObject_GetItem(mapping, w);
8425 Py_DECREF(w);
8426 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8428 /* No mapping found means: use 1:1 mapping. */
8429 PyErr_Clear();
8430 *result = NULL;
8431 return 0;
8432 } else
8433 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 }
8435 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 *result = x;
8437 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008439 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008441 if (value < 0 || value > MAX_UNICODE) {
8442 PyErr_Format(PyExc_ValueError,
8443 "character mapping must be in range(0x%x)",
8444 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 Py_DECREF(x);
8446 return -1;
8447 }
8448 *result = x;
8449 return 0;
8450 }
8451 else if (PyUnicode_Check(x)) {
8452 *result = x;
8453 return 0;
8454 }
8455 else {
8456 /* wrong return value */
8457 PyErr_SetString(PyExc_TypeError,
8458 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 Py_DECREF(x);
8460 return -1;
8461 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462}
Victor Stinner1194ea02014-04-04 19:37:40 +02008463
8464/* lookup the character, write the result into the writer.
8465 Return 1 if the result was written into the writer, return 0 if the mapping
8466 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008467static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008468charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8469 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470{
Victor Stinner1194ea02014-04-04 19:37:40 +02008471 PyObject *item;
8472
8473 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008475
8476 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008478 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008481 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008483
8484 if (item == Py_None) {
8485 Py_DECREF(item);
8486 return 0;
8487 }
8488
8489 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008490 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8491 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8492 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008493 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8494 Py_DECREF(item);
8495 return -1;
8496 }
8497 Py_DECREF(item);
8498 return 1;
8499 }
8500
8501 if (!PyUnicode_Check(item)) {
8502 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008504 }
8505
8506 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8507 Py_DECREF(item);
8508 return -1;
8509 }
8510
8511 Py_DECREF(item);
8512 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513}
8514
Victor Stinner89a76ab2014-04-05 11:44:04 +02008515static int
8516unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8517 Py_UCS1 *translate)
8518{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008519 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008520 int ret = 0;
8521
Victor Stinner89a76ab2014-04-05 11:44:04 +02008522 if (charmaptranslate_lookup(ch, mapping, &item)) {
8523 return -1;
8524 }
8525
8526 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008527 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008528 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008529 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008530 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008531 /* not found => default to 1:1 mapping */
8532 translate[ch] = ch;
8533 return 1;
8534 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008535 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008536 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008537 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8538 used it */
8539 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008540 /* invalid character or character outside ASCII:
8541 skip the fast translate */
8542 goto exit;
8543 }
8544 translate[ch] = (Py_UCS1)replace;
8545 }
8546 else if (PyUnicode_Check(item)) {
8547 Py_UCS4 replace;
8548
8549 if (PyUnicode_READY(item) == -1) {
8550 Py_DECREF(item);
8551 return -1;
8552 }
8553 if (PyUnicode_GET_LENGTH(item) != 1)
8554 goto exit;
8555
8556 replace = PyUnicode_READ_CHAR(item, 0);
8557 if (replace > 127)
8558 goto exit;
8559 translate[ch] = (Py_UCS1)replace;
8560 }
8561 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008562 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008563 goto exit;
8564 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008565 ret = 1;
8566
Benjamin Peterson1365de72014-04-07 20:15:41 -04008567 exit:
8568 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008569 return ret;
8570}
8571
8572/* Fast path for ascii => ascii translation. Return 1 if the whole string
8573 was translated into writer, return 0 if the input string was partially
8574 translated into writer, raise an exception and return -1 on error. */
8575static int
8576unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008577 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008578{
Victor Stinner872b2912014-04-05 14:27:07 +02008579 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008580 Py_ssize_t len;
8581 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008582 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008583
8584 if (PyUnicode_READY(input) == -1)
8585 return -1;
8586 if (!PyUnicode_IS_ASCII(input))
8587 return 0;
8588 len = PyUnicode_GET_LENGTH(input);
8589
Victor Stinner872b2912014-04-05 14:27:07 +02008590 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008591
8592 in = PyUnicode_1BYTE_DATA(input);
8593 end = in + len;
8594
8595 assert(PyUnicode_IS_ASCII(writer->buffer));
8596 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8597 out = PyUnicode_1BYTE_DATA(writer->buffer);
8598
Victor Stinner872b2912014-04-05 14:27:07 +02008599 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008600 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008601 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008602 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008603 int translate = unicode_fast_translate_lookup(mapping, ch,
8604 ascii_table);
8605 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008606 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008607 if (translate == 0)
8608 goto exit;
8609 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008610 }
Victor Stinner872b2912014-04-05 14:27:07 +02008611 if (ch2 == 0xfe) {
8612 if (ignore)
8613 continue;
8614 goto exit;
8615 }
8616 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008617 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008618 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008619 }
Victor Stinner872b2912014-04-05 14:27:07 +02008620 res = 1;
8621
8622exit:
8623 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8624 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
8669 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008670 if (res < 0) {
8671 _PyUnicodeWriter_Dealloc(&writer);
8672 return NULL;
8673 }
8674 if (res == 1)
8675 return _PyUnicodeWriter_Finish(&writer);
8676
Victor Stinner89a76ab2014-04-05 11:44:04 +02008677 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008680 int translate;
8681 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8682 Py_ssize_t newpos;
8683 /* startpos for collecting untranslatable chars */
8684 Py_ssize_t collstart;
8685 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008686 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008687
Victor Stinner1194ea02014-04-04 19:37:40 +02008688 ch = PyUnicode_READ(kind, data, i);
8689 translate = charmaptranslate_output(ch, mapping, &writer);
8690 if (translate < 0)
8691 goto onError;
8692
8693 if (translate != 0) {
8694 /* it worked => adjust input pointer */
8695 ++i;
8696 continue;
8697 }
8698
8699 /* untranslatable character */
8700 collstart = i;
8701 collend = i+1;
8702
8703 /* find all untranslatable characters */
8704 while (collend < size) {
8705 PyObject *x;
8706 ch = PyUnicode_READ(kind, data, collend);
8707 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008708 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008709 Py_XDECREF(x);
8710 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008712 ++collend;
8713 }
8714
8715 if (ignore) {
8716 i = collend;
8717 }
8718 else {
8719 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8720 reason, input, &exc,
8721 collstart, collend, &newpos);
8722 if (repunicode == NULL)
8723 goto onError;
8724 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008726 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008727 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008728 Py_DECREF(repunicode);
8729 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008730 }
8731 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008732 Py_XDECREF(exc);
8733 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008734 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008735
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 Py_XDECREF(exc);
8739 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008740 return NULL;
8741}
8742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743/* Deprecated. Use PyUnicode_Translate instead. */
8744PyObject *
8745PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8746 Py_ssize_t size,
8747 PyObject *mapping,
8748 const char *errors)
8749{
Christian Heimes5f520f42012-09-11 14:03:25 +02008750 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8752 if (!unicode)
8753 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008754 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8755 Py_DECREF(unicode);
8756 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008757}
8758
Alexander Belopolsky40018472011-02-26 01:02:56 +00008759PyObject *
8760PyUnicode_Translate(PyObject *str,
8761 PyObject *mapping,
8762 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008763{
8764 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008765
Guido van Rossumd57fd912000-03-10 22:53:23 +00008766 str = PyUnicode_FromObject(str);
8767 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008768 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008770 Py_DECREF(str);
8771 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772}
Tim Petersced69f82003-09-16 20:30:58 +00008773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008774static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008775fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776{
8777 /* No need to call PyUnicode_READY(self) because this function is only
8778 called as a callback from fixup() which does it already. */
8779 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8780 const int kind = PyUnicode_KIND(self);
8781 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008782 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008783 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 Py_ssize_t i;
8785
8786 for (i = 0; i < len; ++i) {
8787 ch = PyUnicode_READ(kind, data, i);
8788 fixed = 0;
8789 if (ch > 127) {
8790 if (Py_UNICODE_ISSPACE(ch))
8791 fixed = ' ';
8792 else {
8793 const int decimal = Py_UNICODE_TODECIMAL(ch);
8794 if (decimal >= 0)
8795 fixed = '0' + decimal;
8796 }
8797 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008798 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008799 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 PyUnicode_WRITE(kind, data, i, fixed);
8801 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008802 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008803 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008804 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 }
8806
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008807 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808}
8809
8810PyObject *
8811_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8812{
8813 if (!PyUnicode_Check(unicode)) {
8814 PyErr_BadInternalCall();
8815 return NULL;
8816 }
8817 if (PyUnicode_READY(unicode) == -1)
8818 return NULL;
8819 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8820 /* If the string is already ASCII, just return the same string */
8821 Py_INCREF(unicode);
8822 return unicode;
8823 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008824 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008825}
8826
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008827PyObject *
8828PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8829 Py_ssize_t length)
8830{
Victor Stinnerf0124502011-11-21 23:12:56 +01008831 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008832 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008833 Py_UCS4 maxchar;
8834 enum PyUnicode_Kind kind;
8835 void *data;
8836
Victor Stinner99d7ad02012-02-22 13:37:39 +01008837 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008838 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008839 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008840 if (ch > 127) {
8841 int decimal = Py_UNICODE_TODECIMAL(ch);
8842 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008843 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008844 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008845 }
8846 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008847
8848 /* Copy to a new string */
8849 decimal = PyUnicode_New(length, maxchar);
8850 if (decimal == NULL)
8851 return decimal;
8852 kind = PyUnicode_KIND(decimal);
8853 data = PyUnicode_DATA(decimal);
8854 /* Iterate over code points */
8855 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008856 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008857 if (ch > 127) {
8858 int decimal = Py_UNICODE_TODECIMAL(ch);
8859 if (decimal >= 0)
8860 ch = '0' + decimal;
8861 }
8862 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008864 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008865}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008866/* --- Decimal Encoder ---------------------------------------------------- */
8867
Alexander Belopolsky40018472011-02-26 01:02:56 +00008868int
8869PyUnicode_EncodeDecimal(Py_UNICODE *s,
8870 Py_ssize_t length,
8871 char *output,
8872 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008873{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008874 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008875 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008876 enum PyUnicode_Kind kind;
8877 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008878
8879 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008880 PyErr_BadArgument();
8881 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008882 }
8883
Victor Stinner42bf7752011-11-21 22:52:58 +01008884 unicode = PyUnicode_FromUnicode(s, length);
8885 if (unicode == NULL)
8886 return -1;
8887
Benjamin Petersonbac79492012-01-14 13:34:47 -05008888 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008889 Py_DECREF(unicode);
8890 return -1;
8891 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008892 kind = PyUnicode_KIND(unicode);
8893 data = PyUnicode_DATA(unicode);
8894
Victor Stinnerb84d7232011-11-22 01:50:07 +01008895 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008896 PyObject *exc;
8897 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008898 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008899 Py_ssize_t startpos;
8900
8901 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008902
Benjamin Peterson29060642009-01-31 22:14:21 +00008903 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008904 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008905 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008906 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008907 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008908 decimal = Py_UNICODE_TODECIMAL(ch);
8909 if (decimal >= 0) {
8910 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008911 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008912 continue;
8913 }
8914 if (0 < ch && ch < 256) {
8915 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008916 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 continue;
8918 }
Victor Stinner6345be92011-11-25 20:09:01 +01008919
Victor Stinner42bf7752011-11-21 22:52:58 +01008920 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008921 exc = NULL;
8922 raise_encode_exception(&exc, "decimal", unicode,
8923 startpos, startpos+1,
8924 "invalid decimal Unicode string");
8925 Py_XDECREF(exc);
8926 Py_DECREF(unicode);
8927 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008928 }
8929 /* 0-terminate the output string */
8930 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008931 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008932 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008933}
8934
Guido van Rossumd57fd912000-03-10 22:53:23 +00008935/* --- Helpers ------------------------------------------------------------ */
8936
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008937/* helper macro to fixup start/end slice values */
8938#define ADJUST_INDICES(start, end, len) \
8939 if (end > len) \
8940 end = len; \
8941 else if (end < 0) { \
8942 end += len; \
8943 if (end < 0) \
8944 end = 0; \
8945 } \
8946 if (start < 0) { \
8947 start += len; \
8948 if (start < 0) \
8949 start = 0; \
8950 }
8951
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008953any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008954 Py_ssize_t start,
8955 Py_ssize_t end)
8956{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008957 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 void *buf1, *buf2;
8959 Py_ssize_t len1, len2, result;
8960
8961 kind1 = PyUnicode_KIND(s1);
8962 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008963 if (kind1 < kind2)
8964 return -1;
8965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966 len1 = PyUnicode_GET_LENGTH(s1);
8967 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008968 ADJUST_INDICES(start, end, len1);
8969 if (end - start < len2)
8970 return -1;
8971
8972 buf1 = PyUnicode_DATA(s1);
8973 buf2 = PyUnicode_DATA(s2);
8974 if (len2 == 1) {
8975 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
8976 result = findchar((const char *)buf1 + kind1*start,
8977 kind1, end - start, ch, direction);
8978 if (result == -1)
8979 return -1;
8980 else
8981 return start + result;
8982 }
8983
8984 if (kind2 != kind1) {
8985 buf2 = _PyUnicode_AsKind(s2, kind1);
8986 if (!buf2)
8987 return -2;
8988 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989
Victor Stinner794d5672011-10-10 03:21:36 +02008990 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008991 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02008992 case PyUnicode_1BYTE_KIND:
8993 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8994 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8995 else
8996 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8997 break;
8998 case PyUnicode_2BYTE_KIND:
8999 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9000 break;
9001 case PyUnicode_4BYTE_KIND:
9002 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9003 break;
9004 default:
9005 assert(0); result = -2;
9006 }
9007 }
9008 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009009 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009010 case PyUnicode_1BYTE_KIND:
9011 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9012 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9013 else
9014 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9015 break;
9016 case PyUnicode_2BYTE_KIND:
9017 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9018 break;
9019 case PyUnicode_4BYTE_KIND:
9020 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9021 break;
9022 default:
9023 assert(0); result = -2;
9024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009025 }
9026
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009027 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028 PyMem_Free(buf2);
9029
9030 return result;
9031}
9032
9033Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009034_PyUnicode_InsertThousandsGrouping(
9035 PyObject *unicode, Py_ssize_t index,
9036 Py_ssize_t n_buffer,
9037 void *digits, Py_ssize_t n_digits,
9038 Py_ssize_t min_width,
9039 const char *grouping, PyObject *thousands_sep,
9040 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009041{
Victor Stinner41a863c2012-02-24 00:37:51 +01009042 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009043 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009044 Py_ssize_t thousands_sep_len;
9045 Py_ssize_t len;
9046
9047 if (unicode != NULL) {
9048 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009049 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009050 }
9051 else {
9052 kind = PyUnicode_1BYTE_KIND;
9053 data = NULL;
9054 }
9055 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9056 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9057 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9058 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009059 if (thousands_sep_kind < kind) {
9060 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9061 if (!thousands_sep_data)
9062 return -1;
9063 }
9064 else {
9065 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9066 if (!data)
9067 return -1;
9068 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009069 }
9070
Benjamin Petersonead6b532011-12-20 17:23:42 -06009071 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009073 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009074 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009075 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009076 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009077 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009078 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009079 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009080 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009081 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009082 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009083 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009085 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009086 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009087 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009088 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009091 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009092 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009094 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009095 break;
9096 default:
9097 assert(0);
9098 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009099 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009100 if (unicode != NULL && thousands_sep_kind != kind) {
9101 if (thousands_sep_kind < kind)
9102 PyMem_Free(thousands_sep_data);
9103 else
9104 PyMem_Free(data);
9105 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009106 if (unicode == NULL) {
9107 *maxchar = 127;
9108 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009109 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009110 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009111 }
9112 }
9113 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114}
9115
9116
Alexander Belopolsky40018472011-02-26 01:02:56 +00009117Py_ssize_t
9118PyUnicode_Count(PyObject *str,
9119 PyObject *substr,
9120 Py_ssize_t start,
9121 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009122{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009123 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009124 PyObject* str_obj;
9125 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009126 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009127 void *buf1 = NULL, *buf2 = NULL;
9128 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009129
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009130 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009131 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009132 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009133 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009134 if (!sub_obj) {
9135 Py_DECREF(str_obj);
9136 return -1;
9137 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009138 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009139 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 Py_DECREF(str_obj);
9141 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009142 }
Tim Petersced69f82003-09-16 20:30:58 +00009143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009144 kind1 = PyUnicode_KIND(str_obj);
9145 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009146 if (kind1 < kind2) {
9147 Py_DECREF(sub_obj);
9148 Py_DECREF(str_obj);
9149 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009150 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 len1 = PyUnicode_GET_LENGTH(str_obj);
9153 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009154 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009155 if (end - start < len2) {
9156 Py_DECREF(sub_obj);
9157 Py_DECREF(str_obj);
9158 return 0;
9159 }
9160
9161 buf1 = PyUnicode_DATA(str_obj);
9162 buf2 = PyUnicode_DATA(sub_obj);
9163 if (kind2 != kind1) {
9164 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9165 if (!buf2)
9166 goto onError;
9167 }
9168
9169 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009170 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009171 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9172 result = asciilib_count(
9173 ((Py_UCS1*)buf1) + start, end - start,
9174 buf2, len2, PY_SSIZE_T_MAX
9175 );
9176 else
9177 result = ucs1lib_count(
9178 ((Py_UCS1*)buf1) + start, end - start,
9179 buf2, len2, PY_SSIZE_T_MAX
9180 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 break;
9182 case PyUnicode_2BYTE_KIND:
9183 result = ucs2lib_count(
9184 ((Py_UCS2*)buf1) + start, end - start,
9185 buf2, len2, PY_SSIZE_T_MAX
9186 );
9187 break;
9188 case PyUnicode_4BYTE_KIND:
9189 result = ucs4lib_count(
9190 ((Py_UCS4*)buf1) + start, end - start,
9191 buf2, len2, PY_SSIZE_T_MAX
9192 );
9193 break;
9194 default:
9195 assert(0); result = 0;
9196 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009197
9198 Py_DECREF(sub_obj);
9199 Py_DECREF(str_obj);
9200
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009201 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 PyMem_Free(buf2);
9203
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 onError:
9206 Py_DECREF(sub_obj);
9207 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009208 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 PyMem_Free(buf2);
9210 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009211}
9212
Alexander Belopolsky40018472011-02-26 01:02:56 +00009213Py_ssize_t
9214PyUnicode_Find(PyObject *str,
9215 PyObject *sub,
9216 Py_ssize_t start,
9217 Py_ssize_t end,
9218 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009220 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009221
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009223 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009224 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009225 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009226 if (!sub) {
9227 Py_DECREF(str);
9228 return -2;
9229 }
9230 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9231 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009232 Py_DECREF(str);
9233 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234 }
Tim Petersced69f82003-09-16 20:30:58 +00009235
Victor Stinner794d5672011-10-10 03:21:36 +02009236 result = any_find_slice(direction,
9237 str, sub, start, end
9238 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009239
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009241 Py_DECREF(sub);
9242
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243 return result;
9244}
9245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009246Py_ssize_t
9247PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9248 Py_ssize_t start, Py_ssize_t end,
9249 int direction)
9250{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009251 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009252 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 if (PyUnicode_READY(str) == -1)
9254 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009255 if (start < 0 || end < 0) {
9256 PyErr_SetString(PyExc_IndexError, "string index out of range");
9257 return -2;
9258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (end > PyUnicode_GET_LENGTH(str))
9260 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009261 if (start >= end)
9262 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009264 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9265 kind, end-start, ch, direction);
9266 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009267 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009268 else
9269 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270}
9271
Alexander Belopolsky40018472011-02-26 01:02:56 +00009272static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009273tailmatch(PyObject *self,
9274 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009275 Py_ssize_t start,
9276 Py_ssize_t end,
9277 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 int kind_self;
9280 int kind_sub;
9281 void *data_self;
9282 void *data_sub;
9283 Py_ssize_t offset;
9284 Py_ssize_t i;
9285 Py_ssize_t end_sub;
9286
9287 if (PyUnicode_READY(self) == -1 ||
9288 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009289 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9292 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009294 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009295
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009296 if (PyUnicode_GET_LENGTH(substring) == 0)
9297 return 1;
9298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299 kind_self = PyUnicode_KIND(self);
9300 data_self = PyUnicode_DATA(self);
9301 kind_sub = PyUnicode_KIND(substring);
9302 data_sub = PyUnicode_DATA(substring);
9303 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9304
9305 if (direction > 0)
9306 offset = end;
9307 else
9308 offset = start;
9309
9310 if (PyUnicode_READ(kind_self, data_self, offset) ==
9311 PyUnicode_READ(kind_sub, data_sub, 0) &&
9312 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9313 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9314 /* If both are of the same kind, memcmp is sufficient */
9315 if (kind_self == kind_sub) {
9316 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009317 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318 data_sub,
9319 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009320 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 }
9322 /* otherwise we have to compare each character by first accesing it */
9323 else {
9324 /* We do not need to compare 0 and len(substring)-1 because
9325 the if statement above ensured already that they are equal
9326 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 for (i = 1; i < end_sub; ++i) {
9328 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9329 PyUnicode_READ(kind_sub, data_sub, i))
9330 return 0;
9331 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009332 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009334 }
9335
9336 return 0;
9337}
9338
Alexander Belopolsky40018472011-02-26 01:02:56 +00009339Py_ssize_t
9340PyUnicode_Tailmatch(PyObject *str,
9341 PyObject *substr,
9342 Py_ssize_t start,
9343 Py_ssize_t end,
9344 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009346 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009347
Guido van Rossumd57fd912000-03-10 22:53:23 +00009348 str = PyUnicode_FromObject(str);
9349 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009350 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351 substr = PyUnicode_FromObject(substr);
9352 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009353 Py_DECREF(str);
9354 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009355 }
Tim Petersced69f82003-09-16 20:30:58 +00009356
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009357 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009358 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009359 Py_DECREF(str);
9360 Py_DECREF(substr);
9361 return result;
9362}
9363
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364/* Apply fixfct filter to the Unicode object self and return a
9365 reference to the modified object */
9366
Alexander Belopolsky40018472011-02-26 01:02:56 +00009367static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009368fixup(PyObject *self,
9369 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371 PyObject *u;
9372 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009373 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009375 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009377 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009378 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 /* fix functions return the new maximum character in a string,
9381 if the kind of the resulting unicode object does not change,
9382 everything is fine. Otherwise we need to change the string kind
9383 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009384 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009385
9386 if (maxchar_new == 0) {
9387 /* no changes */;
9388 if (PyUnicode_CheckExact(self)) {
9389 Py_DECREF(u);
9390 Py_INCREF(self);
9391 return self;
9392 }
9393 else
9394 return u;
9395 }
9396
Victor Stinnere6abb482012-05-02 01:15:40 +02009397 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398
Victor Stinnereaab6042011-12-11 22:22:39 +01009399 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009401
9402 /* In case the maximum character changed, we need to
9403 convert the string to the new category. */
9404 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9405 if (v == NULL) {
9406 Py_DECREF(u);
9407 return NULL;
9408 }
9409 if (maxchar_new > maxchar_old) {
9410 /* If the maxchar increased so that the kind changed, not all
9411 characters are representable anymore and we need to fix the
9412 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009413 _PyUnicode_FastCopyCharacters(v, 0,
9414 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009415 maxchar_old = fixfct(v);
9416 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 }
9418 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009419 _PyUnicode_FastCopyCharacters(v, 0,
9420 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009422 Py_DECREF(u);
9423 assert(_PyUnicode_CheckConsistency(v, 1));
9424 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009425}
9426
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009427static PyObject *
9428ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009430 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9431 char *resdata, *data = PyUnicode_DATA(self);
9432 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009433
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009434 res = PyUnicode_New(len, 127);
9435 if (res == NULL)
9436 return NULL;
9437 resdata = PyUnicode_DATA(res);
9438 if (lower)
9439 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009440 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009441 _Py_bytes_upper(resdata, data, len);
9442 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009443}
9444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009446handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009447{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009448 Py_ssize_t j;
9449 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009450 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009451 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009452
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009453 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9454
9455 where ! is a negation and \p{xxx} is a character with property xxx.
9456 */
9457 for (j = i - 1; j >= 0; j--) {
9458 c = PyUnicode_READ(kind, data, j);
9459 if (!_PyUnicode_IsCaseIgnorable(c))
9460 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009462 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9463 if (final_sigma) {
9464 for (j = i + 1; j < length; j++) {
9465 c = PyUnicode_READ(kind, data, j);
9466 if (!_PyUnicode_IsCaseIgnorable(c))
9467 break;
9468 }
9469 final_sigma = j == length || !_PyUnicode_IsCased(c);
9470 }
9471 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472}
9473
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009474static int
9475lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9476 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009478 /* Obscure special case. */
9479 if (c == 0x3A3) {
9480 mapped[0] = handle_capital_sigma(kind, data, length, i);
9481 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009483 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484}
9485
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009486static Py_ssize_t
9487do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009489 Py_ssize_t i, k = 0;
9490 int n_res, j;
9491 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009492
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009493 c = PyUnicode_READ(kind, data, 0);
9494 n_res = _PyUnicode_ToUpperFull(c, mapped);
9495 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009496 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009497 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009499 for (i = 1; i < length; i++) {
9500 c = PyUnicode_READ(kind, data, i);
9501 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9502 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009503 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009504 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009505 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009506 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009507 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508}
9509
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009510static Py_ssize_t
9511do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9512 Py_ssize_t i, k = 0;
9513
9514 for (i = 0; i < length; i++) {
9515 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9516 int n_res, j;
9517 if (Py_UNICODE_ISUPPER(c)) {
9518 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9519 }
9520 else if (Py_UNICODE_ISLOWER(c)) {
9521 n_res = _PyUnicode_ToUpperFull(c, mapped);
9522 }
9523 else {
9524 n_res = 1;
9525 mapped[0] = c;
9526 }
9527 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009528 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009529 res[k++] = mapped[j];
9530 }
9531 }
9532 return k;
9533}
9534
9535static Py_ssize_t
9536do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9537 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009538{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009539 Py_ssize_t i, k = 0;
9540
9541 for (i = 0; i < length; i++) {
9542 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9543 int n_res, j;
9544 if (lower)
9545 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9546 else
9547 n_res = _PyUnicode_ToUpperFull(c, mapped);
9548 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009549 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009550 res[k++] = mapped[j];
9551 }
9552 }
9553 return k;
9554}
9555
9556static Py_ssize_t
9557do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9558{
9559 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9560}
9561
9562static Py_ssize_t
9563do_lower(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, 1);
9566}
9567
Benjamin Petersone51757f2012-01-12 21:10:29 -05009568static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009569do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9570{
9571 Py_ssize_t i, k = 0;
9572
9573 for (i = 0; i < length; i++) {
9574 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9575 Py_UCS4 mapped[3];
9576 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9577 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009578 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009579 res[k++] = mapped[j];
9580 }
9581 }
9582 return k;
9583}
9584
9585static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009586do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9587{
9588 Py_ssize_t i, k = 0;
9589 int previous_is_cased;
9590
9591 previous_is_cased = 0;
9592 for (i = 0; i < length; i++) {
9593 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9594 Py_UCS4 mapped[3];
9595 int n_res, j;
9596
9597 if (previous_is_cased)
9598 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9599 else
9600 n_res = _PyUnicode_ToTitleFull(c, mapped);
9601
9602 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009603 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009604 res[k++] = mapped[j];
9605 }
9606
9607 previous_is_cased = _PyUnicode_IsCased(c);
9608 }
9609 return k;
9610}
9611
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009612static PyObject *
9613case_operation(PyObject *self,
9614 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9615{
9616 PyObject *res = NULL;
9617 Py_ssize_t length, newlength = 0;
9618 int kind, outkind;
9619 void *data, *outdata;
9620 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9621
Benjamin Petersoneea48462012-01-16 14:28:50 -05009622 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009623
9624 kind = PyUnicode_KIND(self);
9625 data = PyUnicode_DATA(self);
9626 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009627 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009628 PyErr_SetString(PyExc_OverflowError, "string is too long");
9629 return NULL;
9630 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009631 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 if (tmp == NULL)
9633 return PyErr_NoMemory();
9634 newlength = perform(kind, data, length, tmp, &maxchar);
9635 res = PyUnicode_New(newlength, maxchar);
9636 if (res == NULL)
9637 goto leave;
9638 tmpend = tmp + newlength;
9639 outdata = PyUnicode_DATA(res);
9640 outkind = PyUnicode_KIND(res);
9641 switch (outkind) {
9642 case PyUnicode_1BYTE_KIND:
9643 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9644 break;
9645 case PyUnicode_2BYTE_KIND:
9646 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9647 break;
9648 case PyUnicode_4BYTE_KIND:
9649 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9650 break;
9651 default:
9652 assert(0);
9653 break;
9654 }
9655 leave:
9656 PyMem_FREE(tmp);
9657 return res;
9658}
9659
Tim Peters8ce9f162004-08-27 01:49:32 +00009660PyObject *
9661PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009664 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009666 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009667 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9668 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009669 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009671 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009672 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009673 int use_memcpy;
9674 unsigned char *res_data = NULL, *sep_data = NULL;
9675 PyObject *last_obj;
9676 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009677
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009678 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009679 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009680 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009681 }
9682
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009683 /* NOTE: the following code can't call back into Python code,
9684 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009685 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009686
Tim Peters05eba1f2004-08-27 21:32:02 +00009687 seqlen = PySequence_Fast_GET_SIZE(fseq);
9688 /* If empty sequence, return u"". */
9689 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009690 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009691 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009693
Tim Peters05eba1f2004-08-27 21:32:02 +00009694 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009695 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009696 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009697 if (seqlen == 1) {
9698 if (PyUnicode_CheckExact(items[0])) {
9699 res = items[0];
9700 Py_INCREF(res);
9701 Py_DECREF(fseq);
9702 return res;
9703 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009704 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009705 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009706 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009707 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009708 /* Set up sep and seplen */
9709 if (separator == NULL) {
9710 /* fall back to a blank space separator */
9711 sep = PyUnicode_FromOrdinal(' ');
9712 if (!sep)
9713 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009714 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009715 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009716 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009717 else {
9718 if (!PyUnicode_Check(separator)) {
9719 PyErr_Format(PyExc_TypeError,
9720 "separator: expected str instance,"
9721 " %.80s found",
9722 Py_TYPE(separator)->tp_name);
9723 goto onError;
9724 }
9725 if (PyUnicode_READY(separator))
9726 goto onError;
9727 sep = separator;
9728 seplen = PyUnicode_GET_LENGTH(separator);
9729 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9730 /* inc refcount to keep this code path symmetric with the
9731 above case of a blank separator */
9732 Py_INCREF(sep);
9733 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009734 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009735 }
9736
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009737 /* There are at least two things to join, or else we have a subclass
9738 * of str in the sequence.
9739 * Do a pre-pass to figure out the total amount of space we'll
9740 * need (sz), and see whether all argument are strings.
9741 */
9742 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009743#ifdef Py_DEBUG
9744 use_memcpy = 0;
9745#else
9746 use_memcpy = 1;
9747#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009748 for (i = 0; i < seqlen; i++) {
9749 const Py_ssize_t old_sz = sz;
9750 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009751 if (!PyUnicode_Check(item)) {
9752 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009753 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009754 " %.80s found",
9755 i, Py_TYPE(item)->tp_name);
9756 goto onError;
9757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009758 if (PyUnicode_READY(item) == -1)
9759 goto onError;
9760 sz += PyUnicode_GET_LENGTH(item);
9761 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009762 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 if (i != 0)
9764 sz += seplen;
9765 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9766 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009767 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009768 goto onError;
9769 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009770 if (use_memcpy && last_obj != NULL) {
9771 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9772 use_memcpy = 0;
9773 }
9774 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009775 }
Tim Petersced69f82003-09-16 20:30:58 +00009776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009778 if (res == NULL)
9779 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009780
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009781 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009782#ifdef Py_DEBUG
9783 use_memcpy = 0;
9784#else
9785 if (use_memcpy) {
9786 res_data = PyUnicode_1BYTE_DATA(res);
9787 kind = PyUnicode_KIND(res);
9788 if (seplen != 0)
9789 sep_data = PyUnicode_1BYTE_DATA(sep);
9790 }
9791#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009792 if (use_memcpy) {
9793 for (i = 0; i < seqlen; ++i) {
9794 Py_ssize_t itemlen;
9795 item = items[i];
9796
9797 /* Copy item, and maybe the separator. */
9798 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009799 Py_MEMCPY(res_data,
9800 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009801 kind * seplen);
9802 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009803 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009804
9805 itemlen = PyUnicode_GET_LENGTH(item);
9806 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009807 Py_MEMCPY(res_data,
9808 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009809 kind * itemlen);
9810 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009811 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009812 }
9813 assert(res_data == PyUnicode_1BYTE_DATA(res)
9814 + kind * PyUnicode_GET_LENGTH(res));
9815 }
9816 else {
9817 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9818 Py_ssize_t itemlen;
9819 item = items[i];
9820
9821 /* Copy item, and maybe the separator. */
9822 if (i && seplen != 0) {
9823 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9824 res_offset += seplen;
9825 }
9826
9827 itemlen = PyUnicode_GET_LENGTH(item);
9828 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009829 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009830 res_offset += itemlen;
9831 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009832 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009833 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009834 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009835
Tim Peters05eba1f2004-08-27 21:32:02 +00009836 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009838 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009839 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840
Benjamin Peterson29060642009-01-31 22:14:21 +00009841 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009842 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009843 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009844 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009845 return NULL;
9846}
9847
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848#define FILL(kind, data, value, start, length) \
9849 do { \
9850 Py_ssize_t i_ = 0; \
9851 assert(kind != PyUnicode_WCHAR_KIND); \
9852 switch ((kind)) { \
9853 case PyUnicode_1BYTE_KIND: { \
9854 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009855 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009856 break; \
9857 } \
9858 case PyUnicode_2BYTE_KIND: { \
9859 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9860 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9861 break; \
9862 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009863 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9865 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9866 break; \
9867 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009868 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 } \
9870 } while (0)
9871
Victor Stinnerd3f08822012-05-29 12:57:52 +02009872void
9873_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9874 Py_UCS4 fill_char)
9875{
9876 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9877 const void *data = PyUnicode_DATA(unicode);
9878 assert(PyUnicode_IS_READY(unicode));
9879 assert(unicode_modifiable(unicode));
9880 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9881 assert(start >= 0);
9882 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9883 FILL(kind, data, fill_char, start, length);
9884}
9885
Victor Stinner3fe55312012-01-04 00:33:50 +01009886Py_ssize_t
9887PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9888 Py_UCS4 fill_char)
9889{
9890 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009891
9892 if (!PyUnicode_Check(unicode)) {
9893 PyErr_BadInternalCall();
9894 return -1;
9895 }
9896 if (PyUnicode_READY(unicode) == -1)
9897 return -1;
9898 if (unicode_check_modifiable(unicode))
9899 return -1;
9900
Victor Stinnerd3f08822012-05-29 12:57:52 +02009901 if (start < 0) {
9902 PyErr_SetString(PyExc_IndexError, "string index out of range");
9903 return -1;
9904 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009905 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9906 PyErr_SetString(PyExc_ValueError,
9907 "fill character is bigger than "
9908 "the string maximum character");
9909 return -1;
9910 }
9911
9912 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9913 length = Py_MIN(maxlen, length);
9914 if (length <= 0)
9915 return 0;
9916
Victor Stinnerd3f08822012-05-29 12:57:52 +02009917 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009918 return length;
9919}
9920
Victor Stinner9310abb2011-10-05 00:59:23 +02009921static PyObject *
9922pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009923 Py_ssize_t left,
9924 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009926{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009927 PyObject *u;
9928 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009929 int kind;
9930 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009931
9932 if (left < 0)
9933 left = 0;
9934 if (right < 0)
9935 right = 0;
9936
Victor Stinnerc4b49542011-12-11 22:44:26 +01009937 if (left == 0 && right == 0)
9938 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9941 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009942 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9943 return NULL;
9944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009946 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009948 if (!u)
9949 return NULL;
9950
9951 kind = PyUnicode_KIND(u);
9952 data = PyUnicode_DATA(u);
9953 if (left)
9954 FILL(kind, data, fill, 0, left);
9955 if (right)
9956 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009957 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009958 assert(_PyUnicode_CheckConsistency(u, 1));
9959 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960}
9961
Alexander Belopolsky40018472011-02-26 01:02:56 +00009962PyObject *
9963PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009964{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009965 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966
9967 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009968 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009969 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009970 if (PyUnicode_READY(string) == -1) {
9971 Py_DECREF(string);
9972 return NULL;
9973 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009974
Benjamin Petersonead6b532011-12-20 17:23:42 -06009975 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977 if (PyUnicode_IS_ASCII(string))
9978 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009979 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009980 PyUnicode_GET_LENGTH(string), keepends);
9981 else
9982 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009984 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009985 break;
9986 case PyUnicode_2BYTE_KIND:
9987 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009988 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 PyUnicode_GET_LENGTH(string), keepends);
9990 break;
9991 case PyUnicode_4BYTE_KIND:
9992 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009993 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009994 PyUnicode_GET_LENGTH(string), keepends);
9995 break;
9996 default:
9997 assert(0);
9998 list = 0;
9999 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010000 Py_DECREF(string);
10001 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010002}
10003
Alexander Belopolsky40018472011-02-26 01:02:56 +000010004static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010005split(PyObject *self,
10006 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010007 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010009 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 void *buf1, *buf2;
10011 Py_ssize_t len1, len2;
10012 PyObject* out;
10013
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010015 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 if (PyUnicode_READY(self) == -1)
10018 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010021 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010023 if (PyUnicode_IS_ASCII(self))
10024 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010025 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026 PyUnicode_GET_LENGTH(self), maxcount
10027 );
10028 else
10029 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010030 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010031 PyUnicode_GET_LENGTH(self), maxcount
10032 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 case PyUnicode_2BYTE_KIND:
10034 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010035 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 PyUnicode_GET_LENGTH(self), maxcount
10037 );
10038 case PyUnicode_4BYTE_KIND:
10039 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010040 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 PyUnicode_GET_LENGTH(self), maxcount
10042 );
10043 default:
10044 assert(0);
10045 return NULL;
10046 }
10047
10048 if (PyUnicode_READY(substring) == -1)
10049 return NULL;
10050
10051 kind1 = PyUnicode_KIND(self);
10052 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 len1 = PyUnicode_GET_LENGTH(self);
10054 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010055 if (kind1 < kind2 || len1 < len2) {
10056 out = PyList_New(1);
10057 if (out == NULL)
10058 return NULL;
10059 Py_INCREF(self);
10060 PyList_SET_ITEM(out, 0, self);
10061 return out;
10062 }
10063 buf1 = PyUnicode_DATA(self);
10064 buf2 = PyUnicode_DATA(substring);
10065 if (kind2 != kind1) {
10066 buf2 = _PyUnicode_AsKind(substring, kind1);
10067 if (!buf2)
10068 return NULL;
10069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010071 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010073 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10074 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010075 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010076 else
10077 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010078 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 break;
10080 case PyUnicode_2BYTE_KIND:
10081 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010082 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 break;
10084 case PyUnicode_4BYTE_KIND:
10085 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010086 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 break;
10088 default:
10089 out = NULL;
10090 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010091 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 PyMem_Free(buf2);
10093 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010094}
10095
Alexander Belopolsky40018472011-02-26 01:02:56 +000010096static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010097rsplit(PyObject *self,
10098 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010099 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010100{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010101 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 void *buf1, *buf2;
10103 Py_ssize_t len1, len2;
10104 PyObject* out;
10105
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010106 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010107 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 if (PyUnicode_READY(self) == -1)
10110 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010113 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010115 if (PyUnicode_IS_ASCII(self))
10116 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010117 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010118 PyUnicode_GET_LENGTH(self), maxcount
10119 );
10120 else
10121 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010122 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010123 PyUnicode_GET_LENGTH(self), maxcount
10124 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 case PyUnicode_2BYTE_KIND:
10126 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 PyUnicode_GET_LENGTH(self), maxcount
10129 );
10130 case PyUnicode_4BYTE_KIND:
10131 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010132 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 PyUnicode_GET_LENGTH(self), maxcount
10134 );
10135 default:
10136 assert(0);
10137 return NULL;
10138 }
10139
10140 if (PyUnicode_READY(substring) == -1)
10141 return NULL;
10142
10143 kind1 = PyUnicode_KIND(self);
10144 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 len1 = PyUnicode_GET_LENGTH(self);
10146 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010147 if (kind1 < kind2 || len1 < len2) {
10148 out = PyList_New(1);
10149 if (out == NULL)
10150 return NULL;
10151 Py_INCREF(self);
10152 PyList_SET_ITEM(out, 0, self);
10153 return out;
10154 }
10155 buf1 = PyUnicode_DATA(self);
10156 buf2 = PyUnicode_DATA(substring);
10157 if (kind2 != kind1) {
10158 buf2 = _PyUnicode_AsKind(substring, kind1);
10159 if (!buf2)
10160 return NULL;
10161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010163 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010165 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10166 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010168 else
10169 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010170 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 break;
10172 case PyUnicode_2BYTE_KIND:
10173 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010174 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 break;
10176 case PyUnicode_4BYTE_KIND:
10177 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010178 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 break;
10180 default:
10181 out = NULL;
10182 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010183 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 PyMem_Free(buf2);
10185 return out;
10186}
10187
10188static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10190 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010192 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010194 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10195 return asciilib_find(buf1, len1, buf2, len2, offset);
10196 else
10197 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 case PyUnicode_2BYTE_KIND:
10199 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10200 case PyUnicode_4BYTE_KIND:
10201 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10202 }
10203 assert(0);
10204 return -1;
10205}
10206
10207static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010208anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10209 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010211 switch (kind) {
10212 case PyUnicode_1BYTE_KIND:
10213 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10214 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10215 else
10216 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10217 case PyUnicode_2BYTE_KIND:
10218 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10219 case PyUnicode_4BYTE_KIND:
10220 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10221 }
10222 assert(0);
10223 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010224}
10225
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010226static void
10227replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10228 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10229{
10230 int kind = PyUnicode_KIND(u);
10231 void *data = PyUnicode_DATA(u);
10232 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10233 if (kind == PyUnicode_1BYTE_KIND) {
10234 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10235 (Py_UCS1 *)data + len,
10236 u1, u2, maxcount);
10237 }
10238 else if (kind == PyUnicode_2BYTE_KIND) {
10239 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10240 (Py_UCS2 *)data + len,
10241 u1, u2, maxcount);
10242 }
10243 else {
10244 assert(kind == PyUnicode_4BYTE_KIND);
10245 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10246 (Py_UCS4 *)data + len,
10247 u1, u2, maxcount);
10248 }
10249}
10250
Alexander Belopolsky40018472011-02-26 01:02:56 +000010251static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252replace(PyObject *self, PyObject *str1,
10253 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 PyObject *u;
10256 char *sbuf = PyUnicode_DATA(self);
10257 char *buf1 = PyUnicode_DATA(str1);
10258 char *buf2 = PyUnicode_DATA(str2);
10259 int srelease = 0, release1 = 0, release2 = 0;
10260 int skind = PyUnicode_KIND(self);
10261 int kind1 = PyUnicode_KIND(str1);
10262 int kind2 = PyUnicode_KIND(str2);
10263 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10264 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10265 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010266 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010267 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268
10269 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010270 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010272 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273
Victor Stinner59de0ee2011-10-07 10:01:28 +020010274 if (str1 == str2)
10275 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276
Victor Stinner49a0a212011-10-12 23:46:10 +020010277 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010278 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10279 if (maxchar < maxchar_str1)
10280 /* substring too wide to be present */
10281 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010282 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10283 /* Replacing str1 with str2 may cause a maxchar reduction in the
10284 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010285 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010286 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010289 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010291 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010293 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010294 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010295 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010296
Victor Stinner69ed0f42013-04-09 21:48:24 +020010297 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010298 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010299 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010300 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010301 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010303 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010305
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010306 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10307 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010308 }
10309 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 int rkind = skind;
10311 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010312 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 if (kind1 < rkind) {
10315 /* widen substring */
10316 buf1 = _PyUnicode_AsKind(str1, rkind);
10317 if (!buf1) goto error;
10318 release1 = 1;
10319 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010320 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010321 if (i < 0)
10322 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 if (rkind > kind2) {
10324 /* widen replacement */
10325 buf2 = _PyUnicode_AsKind(str2, rkind);
10326 if (!buf2) goto error;
10327 release2 = 1;
10328 }
10329 else if (rkind < kind2) {
10330 /* widen self and buf1 */
10331 rkind = kind2;
10332 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010333 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 sbuf = _PyUnicode_AsKind(self, rkind);
10335 if (!sbuf) goto error;
10336 srelease = 1;
10337 buf1 = _PyUnicode_AsKind(str1, rkind);
10338 if (!buf1) goto error;
10339 release1 = 1;
10340 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010341 u = PyUnicode_New(slen, maxchar);
10342 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010344 assert(PyUnicode_KIND(u) == rkind);
10345 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010346
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010347 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010348 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010349 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010351 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010353
10354 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010355 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010356 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010357 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010358 if (i == -1)
10359 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010360 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010362 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010364 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010365 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010366 }
10367 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010369 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 int rkind = skind;
10371 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010374 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 buf1 = _PyUnicode_AsKind(str1, rkind);
10376 if (!buf1) goto error;
10377 release1 = 1;
10378 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010379 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010380 if (n == 0)
10381 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010383 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 buf2 = _PyUnicode_AsKind(str2, rkind);
10385 if (!buf2) goto error;
10386 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010389 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 rkind = kind2;
10391 sbuf = _PyUnicode_AsKind(self, rkind);
10392 if (!sbuf) goto error;
10393 srelease = 1;
10394 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010395 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 buf1 = _PyUnicode_AsKind(str1, rkind);
10397 if (!buf1) goto error;
10398 release1 = 1;
10399 }
10400 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10401 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010402 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 PyErr_SetString(PyExc_OverflowError,
10404 "replace string is too long");
10405 goto error;
10406 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010407 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010408 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010409 _Py_INCREF_UNICODE_EMPTY();
10410 if (!unicode_empty)
10411 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010412 u = unicode_empty;
10413 goto done;
10414 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010415 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 PyErr_SetString(PyExc_OverflowError,
10417 "replace string is too long");
10418 goto error;
10419 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010420 u = PyUnicode_New(new_size, maxchar);
10421 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010423 assert(PyUnicode_KIND(u) == rkind);
10424 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 ires = i = 0;
10426 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427 while (n-- > 0) {
10428 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010429 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010430 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010431 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010432 if (j == -1)
10433 break;
10434 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010435 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010436 memcpy(res + rkind * ires,
10437 sbuf + rkind * i,
10438 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010440 }
10441 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010443 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010445 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010447 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010449 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010451 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010452 memcpy(res + rkind * ires,
10453 sbuf + rkind * i,
10454 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010455 }
10456 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010457 /* interleave */
10458 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010459 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010461 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 if (--n <= 0)
10464 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010465 memcpy(res + rkind * ires,
10466 sbuf + rkind * i,
10467 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 ires++;
10469 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010470 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 memcpy(res + rkind * ires,
10472 sbuf + rkind * i,
10473 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010474 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010475 }
10476
10477 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010478 unicode_adjust_maxchar(&u);
10479 if (u == NULL)
10480 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010482
10483 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 if (srelease)
10485 PyMem_FREE(sbuf);
10486 if (release1)
10487 PyMem_FREE(buf1);
10488 if (release2)
10489 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010490 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010492
Benjamin Peterson29060642009-01-31 22:14:21 +000010493 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010494 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 if (srelease)
10496 PyMem_FREE(sbuf);
10497 if (release1)
10498 PyMem_FREE(buf1);
10499 if (release2)
10500 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010501 return unicode_result_unchanged(self);
10502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 error:
10504 if (srelease && sbuf)
10505 PyMem_FREE(sbuf);
10506 if (release1 && buf1)
10507 PyMem_FREE(buf1);
10508 if (release2 && buf2)
10509 PyMem_FREE(buf2);
10510 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010511}
10512
10513/* --- Unicode Object Methods --------------------------------------------- */
10514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010515PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010516 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517\n\
10518Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010519characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520
10521static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010522unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010524 if (PyUnicode_READY(self) == -1)
10525 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010526 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010527}
10528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010529PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010530 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531\n\
10532Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010533have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534
10535static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010536unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010538 if (PyUnicode_READY(self) == -1)
10539 return NULL;
10540 if (PyUnicode_GET_LENGTH(self) == 0)
10541 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010542 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543}
10544
Benjamin Petersond5890c82012-01-14 13:23:30 -050010545PyDoc_STRVAR(casefold__doc__,
10546 "S.casefold() -> str\n\
10547\n\
10548Return a version of S suitable for caseless comparisons.");
10549
10550static PyObject *
10551unicode_casefold(PyObject *self)
10552{
10553 if (PyUnicode_READY(self) == -1)
10554 return NULL;
10555 if (PyUnicode_IS_ASCII(self))
10556 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010557 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010558}
10559
10560
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010561/* Argument converter. Coerces to a single unicode character */
10562
10563static int
10564convert_uc(PyObject *obj, void *addr)
10565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010567 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010568
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569 uniobj = PyUnicode_FromObject(obj);
10570 if (uniobj == NULL) {
10571 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010572 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010573 return 0;
10574 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010576 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010577 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010578 Py_DECREF(uniobj);
10579 return 0;
10580 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010582 Py_DECREF(uniobj);
10583 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010584}
10585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010586PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010587 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010588\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010589Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010590done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010591
10592static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010593unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010595 Py_ssize_t marg, left;
10596 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 Py_UCS4 fillchar = ' ';
10598
Victor Stinnere9a29352011-10-01 02:14:59 +020010599 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010601
Benjamin Petersonbac79492012-01-14 13:34:47 -050010602 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010603 return NULL;
10604
Victor Stinnerc4b49542011-12-11 22:44:26 +010010605 if (PyUnicode_GET_LENGTH(self) >= width)
10606 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010607
Victor Stinnerc4b49542011-12-11 22:44:26 +010010608 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609 left = marg / 2 + (marg & width & 1);
10610
Victor Stinner9310abb2011-10-05 00:59:23 +020010611 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010612}
10613
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614/* This function assumes that str1 and str2 are readied by the caller. */
10615
Marc-André Lemburge5034372000-08-08 08:04:29 +000010616static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010617unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010618{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010619#define COMPARE(TYPE1, TYPE2) \
10620 do { \
10621 TYPE1* p1 = (TYPE1 *)data1; \
10622 TYPE2* p2 = (TYPE2 *)data2; \
10623 TYPE1* end = p1 + len; \
10624 Py_UCS4 c1, c2; \
10625 for (; p1 != end; p1++, p2++) { \
10626 c1 = *p1; \
10627 c2 = *p2; \
10628 if (c1 != c2) \
10629 return (c1 < c2) ? -1 : 1; \
10630 } \
10631 } \
10632 while (0)
10633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 int kind1, kind2;
10635 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010636 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010637
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 kind1 = PyUnicode_KIND(str1);
10639 kind2 = PyUnicode_KIND(str2);
10640 data1 = PyUnicode_DATA(str1);
10641 data2 = PyUnicode_DATA(str2);
10642 len1 = PyUnicode_GET_LENGTH(str1);
10643 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010644 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010645
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010646 switch(kind1) {
10647 case PyUnicode_1BYTE_KIND:
10648 {
10649 switch(kind2) {
10650 case PyUnicode_1BYTE_KIND:
10651 {
10652 int cmp = memcmp(data1, data2, len);
10653 /* normalize result of memcmp() into the range [-1; 1] */
10654 if (cmp < 0)
10655 return -1;
10656 if (cmp > 0)
10657 return 1;
10658 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010659 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010660 case PyUnicode_2BYTE_KIND:
10661 COMPARE(Py_UCS1, Py_UCS2);
10662 break;
10663 case PyUnicode_4BYTE_KIND:
10664 COMPARE(Py_UCS1, Py_UCS4);
10665 break;
10666 default:
10667 assert(0);
10668 }
10669 break;
10670 }
10671 case PyUnicode_2BYTE_KIND:
10672 {
10673 switch(kind2) {
10674 case PyUnicode_1BYTE_KIND:
10675 COMPARE(Py_UCS2, Py_UCS1);
10676 break;
10677 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010678 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010679 COMPARE(Py_UCS2, Py_UCS2);
10680 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010681 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010682 case PyUnicode_4BYTE_KIND:
10683 COMPARE(Py_UCS2, Py_UCS4);
10684 break;
10685 default:
10686 assert(0);
10687 }
10688 break;
10689 }
10690 case PyUnicode_4BYTE_KIND:
10691 {
10692 switch(kind2) {
10693 case PyUnicode_1BYTE_KIND:
10694 COMPARE(Py_UCS4, Py_UCS1);
10695 break;
10696 case PyUnicode_2BYTE_KIND:
10697 COMPARE(Py_UCS4, Py_UCS2);
10698 break;
10699 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010700 {
10701#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10702 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10703 /* normalize result of wmemcmp() into the range [-1; 1] */
10704 if (cmp < 0)
10705 return -1;
10706 if (cmp > 0)
10707 return 1;
10708#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010709 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010710#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010711 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010712 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010713 default:
10714 assert(0);
10715 }
10716 break;
10717 }
10718 default:
10719 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010720 }
10721
Victor Stinner770e19e2012-10-04 22:59:45 +020010722 if (len1 == len2)
10723 return 0;
10724 if (len1 < len2)
10725 return -1;
10726 else
10727 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010728
10729#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010730}
10731
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010732Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010733unicode_compare_eq(PyObject *str1, PyObject *str2)
10734{
10735 int kind;
10736 void *data1, *data2;
10737 Py_ssize_t len;
10738 int cmp;
10739
Victor Stinnere5567ad2012-10-23 02:48:49 +020010740 len = PyUnicode_GET_LENGTH(str1);
10741 if (PyUnicode_GET_LENGTH(str2) != len)
10742 return 0;
10743 kind = PyUnicode_KIND(str1);
10744 if (PyUnicode_KIND(str2) != kind)
10745 return 0;
10746 data1 = PyUnicode_DATA(str1);
10747 data2 = PyUnicode_DATA(str2);
10748
10749 cmp = memcmp(data1, data2, len * kind);
10750 return (cmp == 0);
10751}
10752
10753
Alexander Belopolsky40018472011-02-26 01:02:56 +000010754int
10755PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10758 if (PyUnicode_READY(left) == -1 ||
10759 PyUnicode_READY(right) == -1)
10760 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010761
10762 /* a string is equal to itself */
10763 if (left == right)
10764 return 0;
10765
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010766 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010768 PyErr_Format(PyExc_TypeError,
10769 "Can't compare %.100s and %.100s",
10770 left->ob_type->tp_name,
10771 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772 return -1;
10773}
10774
Martin v. Löwis5b222132007-06-10 09:51:05 +000010775int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010776_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10777{
10778 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10779 if (right_str == NULL)
10780 return -1;
10781 return PyUnicode_Compare(left, right_str);
10782}
10783
10784int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010785PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10786{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 Py_ssize_t i;
10788 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 Py_UCS4 chr;
10790
Victor Stinner910337b2011-10-03 03:20:16 +020010791 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 if (PyUnicode_READY(uni) == -1)
10793 return -1;
10794 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010795 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010796 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010797 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010798 size_t len, len2 = strlen(str);
10799 int cmp;
10800
10801 len = Py_MIN(len1, len2);
10802 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010803 if (cmp != 0) {
10804 if (cmp < 0)
10805 return -1;
10806 else
10807 return 1;
10808 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010809 if (len1 > len2)
10810 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010811 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010812 return -1; /* str is longer */
10813 return 0;
10814 }
10815 else {
10816 void *data = PyUnicode_DATA(uni);
10817 /* Compare Unicode string and source character set string */
10818 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010819 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010820 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10821 /* This check keeps Python strings that end in '\0' from comparing equal
10822 to C strings identical up to that point. */
10823 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10824 return 1; /* uni is longer */
10825 if (str[i])
10826 return -1; /* str is longer */
10827 return 0;
10828 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010829}
10830
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010831
Benjamin Peterson29060642009-01-31 22:14:21 +000010832#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010833 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010834
Alexander Belopolsky40018472011-02-26 01:02:56 +000010835PyObject *
10836PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010837{
10838 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010839 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010840
Victor Stinnere5567ad2012-10-23 02:48:49 +020010841 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10842 Py_RETURN_NOTIMPLEMENTED;
10843
10844 if (PyUnicode_READY(left) == -1 ||
10845 PyUnicode_READY(right) == -1)
10846 return NULL;
10847
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010848 if (left == right) {
10849 switch (op) {
10850 case Py_EQ:
10851 case Py_LE:
10852 case Py_GE:
10853 /* a string is equal to itself */
10854 v = Py_True;
10855 break;
10856 case Py_NE:
10857 case Py_LT:
10858 case Py_GT:
10859 v = Py_False;
10860 break;
10861 default:
10862 PyErr_BadArgument();
10863 return NULL;
10864 }
10865 }
10866 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010867 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010868 result ^= (op == Py_NE);
10869 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010870 }
10871 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010872 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010873
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010874 /* Convert the return value to a Boolean */
10875 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010876 case Py_LE:
10877 v = TEST_COND(result <= 0);
10878 break;
10879 case Py_GE:
10880 v = TEST_COND(result >= 0);
10881 break;
10882 case Py_LT:
10883 v = TEST_COND(result == -1);
10884 break;
10885 case Py_GT:
10886 v = TEST_COND(result == 1);
10887 break;
10888 default:
10889 PyErr_BadArgument();
10890 return NULL;
10891 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010892 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010893 Py_INCREF(v);
10894 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010895}
10896
Alexander Belopolsky40018472011-02-26 01:02:56 +000010897int
10898PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010899{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010900 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010901 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010902 void *buf1, *buf2;
10903 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010904 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010905
10906 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010907 sub = PyUnicode_FromObject(element);
10908 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010909 PyErr_Format(PyExc_TypeError,
10910 "'in <string>' requires string as left operand, not %s",
10911 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010912 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010913 }
10914
Thomas Wouters477c8d52006-05-27 19:21:47 +000010915 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010916 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010917 Py_DECREF(sub);
10918 return -1;
10919 }
10920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010921 kind1 = PyUnicode_KIND(str);
10922 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010923 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010925 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010926 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 }
10928 len1 = PyUnicode_GET_LENGTH(str);
10929 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010930 if (len1 < len2) {
10931 Py_DECREF(sub);
10932 Py_DECREF(str);
10933 return 0;
10934 }
10935 buf1 = PyUnicode_DATA(str);
10936 buf2 = PyUnicode_DATA(sub);
10937 if (len2 == 1) {
10938 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10939 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
10940 Py_DECREF(sub);
10941 Py_DECREF(str);
10942 return result;
10943 }
10944 if (kind2 != kind1) {
10945 buf2 = _PyUnicode_AsKind(sub, kind1);
10946 if (!buf2) {
10947 Py_DECREF(sub);
10948 Py_DECREF(str);
10949 return -1;
10950 }
10951 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952
Victor Stinner77282cb2013-04-14 19:22:47 +020010953 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 case PyUnicode_1BYTE_KIND:
10955 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10956 break;
10957 case PyUnicode_2BYTE_KIND:
10958 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10959 break;
10960 case PyUnicode_4BYTE_KIND:
10961 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10962 break;
10963 default:
10964 result = -1;
10965 assert(0);
10966 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010967
10968 Py_DECREF(str);
10969 Py_DECREF(sub);
10970
Victor Stinner77282cb2013-04-14 19:22:47 +020010971 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010972 PyMem_Free(buf2);
10973
Guido van Rossum403d68b2000-03-13 15:55:09 +000010974 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010975}
10976
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977/* Concat to string or Unicode object giving a new Unicode object. */
10978
Alexander Belopolsky40018472011-02-26 01:02:56 +000010979PyObject *
10980PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010983 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010984 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985
10986 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010989 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993
10994 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010995 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010999 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011000 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 }
11003
Victor Stinner488fa492011-12-12 00:01:39 +010011004 u_len = PyUnicode_GET_LENGTH(u);
11005 v_len = PyUnicode_GET_LENGTH(v);
11006 if (u_len > PY_SSIZE_T_MAX - v_len) {
11007 PyErr_SetString(PyExc_OverflowError,
11008 "strings are too large to concat");
11009 goto onError;
11010 }
11011 new_len = u_len + v_len;
11012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011014 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011015 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011018 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011020 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011021 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11022 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023 Py_DECREF(u);
11024 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011025 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027
Benjamin Peterson29060642009-01-31 22:14:21 +000011028 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029 Py_XDECREF(u);
11030 Py_XDECREF(v);
11031 return NULL;
11032}
11033
Walter Dörwald1ab83302007-05-18 17:15:44 +000011034void
Victor Stinner23e56682011-10-03 03:54:37 +020011035PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011036{
Victor Stinner23e56682011-10-03 03:54:37 +020011037 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011038 Py_UCS4 maxchar, maxchar2;
11039 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011040
11041 if (p_left == NULL) {
11042 if (!PyErr_Occurred())
11043 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011044 return;
11045 }
Victor Stinner23e56682011-10-03 03:54:37 +020011046 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011047 if (right == NULL || left == NULL
11048 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011049 if (!PyErr_Occurred())
11050 PyErr_BadInternalCall();
11051 goto error;
11052 }
11053
Benjamin Petersonbac79492012-01-14 13:34:47 -050011054 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011055 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011056 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011057 goto error;
11058
Victor Stinner488fa492011-12-12 00:01:39 +010011059 /* Shortcuts */
11060 if (left == unicode_empty) {
11061 Py_DECREF(left);
11062 Py_INCREF(right);
11063 *p_left = right;
11064 return;
11065 }
11066 if (right == unicode_empty)
11067 return;
11068
11069 left_len = PyUnicode_GET_LENGTH(left);
11070 right_len = PyUnicode_GET_LENGTH(right);
11071 if (left_len > PY_SSIZE_T_MAX - right_len) {
11072 PyErr_SetString(PyExc_OverflowError,
11073 "strings are too large to concat");
11074 goto error;
11075 }
11076 new_len = left_len + right_len;
11077
11078 if (unicode_modifiable(left)
11079 && PyUnicode_CheckExact(right)
11080 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011081 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11082 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011083 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011084 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011085 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11086 {
11087 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011088 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011089 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011090
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011091 /* copy 'right' into the newly allocated area of 'left' */
11092 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011093 }
Victor Stinner488fa492011-12-12 00:01:39 +010011094 else {
11095 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11096 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011097 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011098
Victor Stinner488fa492011-12-12 00:01:39 +010011099 /* Concat the two Unicode strings */
11100 res = PyUnicode_New(new_len, maxchar);
11101 if (res == NULL)
11102 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011103 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11104 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011105 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011106 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011107 }
11108 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011109 return;
11110
11111error:
Victor Stinner488fa492011-12-12 00:01:39 +010011112 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011113}
11114
11115void
11116PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11117{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011118 PyUnicode_Append(pleft, right);
11119 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011120}
11121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011122PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011123 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011125Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011126string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011127interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128
11129static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011130unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011132 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011133 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011134 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137 void *buf1, *buf2;
11138 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
Jesus Ceaac451502011-04-20 17:09:23 +020011140 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11141 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011142 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011144 kind1 = PyUnicode_KIND(self);
11145 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011146 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011147 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011148 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011149 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 len1 = PyUnicode_GET_LENGTH(self);
11151 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011153 if (end - start < len2) {
11154 Py_DECREF(substring);
11155 return PyLong_FromLong(0);
11156 }
11157 buf1 = PyUnicode_DATA(self);
11158 buf2 = PyUnicode_DATA(substring);
11159 if (kind2 != kind1) {
11160 buf2 = _PyUnicode_AsKind(substring, kind1);
11161 if (!buf2) {
11162 Py_DECREF(substring);
11163 return NULL;
11164 }
11165 }
11166 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 case PyUnicode_1BYTE_KIND:
11168 iresult = ucs1lib_count(
11169 ((Py_UCS1*)buf1) + start, end - start,
11170 buf2, len2, PY_SSIZE_T_MAX
11171 );
11172 break;
11173 case PyUnicode_2BYTE_KIND:
11174 iresult = ucs2lib_count(
11175 ((Py_UCS2*)buf1) + start, end - start,
11176 buf2, len2, PY_SSIZE_T_MAX
11177 );
11178 break;
11179 case PyUnicode_4BYTE_KIND:
11180 iresult = ucs4lib_count(
11181 ((Py_UCS4*)buf1) + start, end - start,
11182 buf2, len2, PY_SSIZE_T_MAX
11183 );
11184 break;
11185 default:
11186 assert(0); iresult = 0;
11187 }
11188
11189 result = PyLong_FromSsize_t(iresult);
11190
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011191 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193
11194 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011195
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 return result;
11197}
11198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011199PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011200 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011202Encode S using the codec registered for encoding. Default encoding\n\
11203is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011204handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011205a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11206'xmlcharrefreplace' as well as any other name registered with\n\
11207codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
11209static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011210unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011212 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213 char *encoding = NULL;
11214 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011215
Benjamin Peterson308d6372009-09-18 21:42:35 +000011216 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11217 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011219 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011220}
11221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011222PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011223 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224\n\
11225Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011226If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
11228static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011229unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011231 Py_ssize_t i, j, line_pos, src_len, incr;
11232 Py_UCS4 ch;
11233 PyObject *u;
11234 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011235 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011237 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011238 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239
Ezio Melotti745d54d2013-11-16 19:10:57 +020011240 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11241 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243
Antoine Pitrou22425222011-10-04 19:10:51 +020011244 if (PyUnicode_READY(self) == -1)
11245 return NULL;
11246
Thomas Wouters7e474022000-07-16 12:04:32 +000011247 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 src_len = PyUnicode_GET_LENGTH(self);
11249 i = j = line_pos = 0;
11250 kind = PyUnicode_KIND(self);
11251 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011252 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011253 for (; i < src_len; i++) {
11254 ch = PyUnicode_READ(kind, src_data, i);
11255 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011256 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011257 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011258 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 goto overflow;
11261 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011263 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011264 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011267 goto overflow;
11268 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011270 if (ch == '\n' || ch == '\r')
11271 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011273 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011274 if (!found)
11275 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011276
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279 if (!u)
11280 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011281 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Antoine Pitroue71d5742011-10-04 15:55:09 +020011283 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284
Antoine Pitroue71d5742011-10-04 15:55:09 +020011285 for (; i < src_len; i++) {
11286 ch = PyUnicode_READ(kind, src_data, i);
11287 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011289 incr = tabsize - (line_pos % tabsize);
11290 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011291 FILL(kind, dest_data, ' ', j, incr);
11292 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011293 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011294 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011295 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011296 line_pos++;
11297 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011298 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011299 if (ch == '\n' || ch == '\r')
11300 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011302 }
11303 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011304 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011305
Antoine Pitroue71d5742011-10-04 15:55:09 +020011306 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011307 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309}
11310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011311PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011312 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313\n\
11314Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011315such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316arguments start and end are interpreted as in slice notation.\n\
11317\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011318Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319
11320static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011323 /* initialize variables to prevent gcc warning */
11324 PyObject *substring = NULL;
11325 Py_ssize_t start = 0;
11326 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011327 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328
Jesus Ceaac451502011-04-20 17:09:23 +020011329 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11330 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332
Christian Heimesd47802e2013-06-29 21:33:36 +020011333 if (PyUnicode_READY(self) == -1) {
11334 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011336 }
11337 if (PyUnicode_READY(substring) == -1) {
11338 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011340 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011341
Victor Stinner7931d9a2011-11-04 00:22:48 +010011342 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
11344 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011345
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 if (result == -2)
11347 return NULL;
11348
Christian Heimes217cfd12007-12-02 14:31:20 +000011349 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350}
11351
11352static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011353unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011355 void *data;
11356 enum PyUnicode_Kind kind;
11357 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011358
11359 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11360 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011362 }
11363 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11364 PyErr_SetString(PyExc_IndexError, "string index out of range");
11365 return NULL;
11366 }
11367 kind = PyUnicode_KIND(self);
11368 data = PyUnicode_DATA(self);
11369 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011370 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371}
11372
Guido van Rossumc2504932007-09-18 19:42:40 +000011373/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011374 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011375static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011376unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377{
Guido van Rossumc2504932007-09-18 19:42:40 +000011378 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011379 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011380
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011381#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011382 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011383#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 if (_PyUnicode_HASH(self) != -1)
11385 return _PyUnicode_HASH(self);
11386 if (PyUnicode_READY(self) == -1)
11387 return -1;
11388 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011389 /*
11390 We make the hash of the empty string be 0, rather than using
11391 (prefix ^ suffix), since this slightly obfuscates the hash secret
11392 */
11393 if (len == 0) {
11394 _PyUnicode_HASH(self) = 0;
11395 return 0;
11396 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011397 x = _Py_HashBytes(PyUnicode_DATA(self),
11398 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011400 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401}
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011411 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011412 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011413 PyObject *substring = NULL;
11414 Py_ssize_t start = 0;
11415 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
Jesus Ceaac451502011-04-20 17:09:23 +020011417 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11418 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
Christian Heimesd47a0452013-06-29 21:21:37 +020011421 if (PyUnicode_READY(self) == -1) {
11422 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011424 }
11425 if (PyUnicode_READY(substring) == -1) {
11426 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011428 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429
Victor Stinner7931d9a2011-11-04 00:22:48 +010011430 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
11432 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 if (result == -2)
11435 return NULL;
11436
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 if (result < 0) {
11438 PyErr_SetString(PyExc_ValueError, "substring not found");
11439 return NULL;
11440 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011441
Christian Heimes217cfd12007-12-02 14:31:20 +000011442 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443}
11444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011445PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011448Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011449at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450
11451static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011452unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 Py_ssize_t i, length;
11455 int kind;
11456 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 int cased;
11458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (PyUnicode_READY(self) == -1)
11460 return NULL;
11461 length = PyUnicode_GET_LENGTH(self);
11462 kind = PyUnicode_KIND(self);
11463 data = PyUnicode_DATA(self);
11464
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 if (length == 1)
11467 return PyBool_FromLong(
11468 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011470 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 for (i = 0; i < length; i++) {
11476 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011477
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11479 return PyBool_FromLong(0);
11480 else if (!cased && Py_UNICODE_ISLOWER(ch))
11481 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011483 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484}
11485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011486PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011489Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011490at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491
11492static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011493unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 Py_ssize_t i, length;
11496 int kind;
11497 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 int cased;
11499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (PyUnicode_READY(self) == -1)
11501 return NULL;
11502 length = PyUnicode_GET_LENGTH(self);
11503 kind = PyUnicode_KIND(self);
11504 data = PyUnicode_DATA(self);
11505
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 if (length == 1)
11508 return PyBool_FromLong(
11509 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011511 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011514
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 for (i = 0; i < length; i++) {
11517 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011518
Benjamin Peterson29060642009-01-31 22:14:21 +000011519 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11520 return PyBool_FromLong(0);
11521 else if (!cased && Py_UNICODE_ISUPPER(ch))
11522 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011524 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525}
11526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011527PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011530Return True if S is a titlecased string and there is at least one\n\
11531character in S, i.e. upper- and titlecase characters may only\n\
11532follow uncased characters and lowercase characters only cased ones.\n\
11533Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534
11535static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011536unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 Py_ssize_t i, length;
11539 int kind;
11540 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 int cased, previous_is_cased;
11542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011543 if (PyUnicode_READY(self) == -1)
11544 return NULL;
11545 length = PyUnicode_GET_LENGTH(self);
11546 kind = PyUnicode_KIND(self);
11547 data = PyUnicode_DATA(self);
11548
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (length == 1) {
11551 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11552 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11553 (Py_UNICODE_ISUPPER(ch) != 0));
11554 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011556 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011559
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 cased = 0;
11561 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 for (i = 0; i < length; i++) {
11563 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011564
Benjamin Peterson29060642009-01-31 22:14:21 +000011565 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11566 if (previous_is_cased)
11567 return PyBool_FromLong(0);
11568 previous_is_cased = 1;
11569 cased = 1;
11570 }
11571 else if (Py_UNICODE_ISLOWER(ch)) {
11572 if (!previous_is_cased)
11573 return PyBool_FromLong(0);
11574 previous_is_cased = 1;
11575 cased = 1;
11576 }
11577 else
11578 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011580 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581}
11582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011583PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011586Return True if all characters in S are whitespace\n\
11587and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
11589static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011590unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011592 Py_ssize_t i, length;
11593 int kind;
11594 void *data;
11595
11596 if (PyUnicode_READY(self) == -1)
11597 return NULL;
11598 length = PyUnicode_GET_LENGTH(self);
11599 kind = PyUnicode_KIND(self);
11600 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 if (length == 1)
11604 return PyBool_FromLong(
11605 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011607 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011611 for (i = 0; i < length; i++) {
11612 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011613 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011616 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617}
11618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011619PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011621\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011622Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011623and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011624
11625static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011626unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011627{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 Py_ssize_t i, length;
11629 int kind;
11630 void *data;
11631
11632 if (PyUnicode_READY(self) == -1)
11633 return NULL;
11634 length = PyUnicode_GET_LENGTH(self);
11635 kind = PyUnicode_KIND(self);
11636 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011637
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011638 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 if (length == 1)
11640 return PyBool_FromLong(
11641 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011642
11643 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011645 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011646
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 for (i = 0; i < length; i++) {
11648 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011650 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011651 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652}
11653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011654PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011656\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011657Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011658and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011659
11660static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011661unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 int kind;
11664 void *data;
11665 Py_ssize_t len, i;
11666
11667 if (PyUnicode_READY(self) == -1)
11668 return NULL;
11669
11670 kind = PyUnicode_KIND(self);
11671 data = PyUnicode_DATA(self);
11672 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011673
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011674 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 if (len == 1) {
11676 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11677 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11678 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011679
11680 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011683
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 for (i = 0; i < len; i++) {
11685 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011686 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011689 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011690}
11691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011692PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011693 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011695Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011696False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697
11698static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011699unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 Py_ssize_t i, length;
11702 int kind;
11703 void *data;
11704
11705 if (PyUnicode_READY(self) == -1)
11706 return NULL;
11707 length = PyUnicode_GET_LENGTH(self);
11708 kind = PyUnicode_KIND(self);
11709 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 if (length == 1)
11713 return PyBool_FromLong(
11714 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011716 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011718 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 for (i = 0; i < length; i++) {
11721 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011722 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011724 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725}
11726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011727PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011730Return True if all characters in S are digits\n\
11731and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
11733static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011734unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 Py_ssize_t i, length;
11737 int kind;
11738 void *data;
11739
11740 if (PyUnicode_READY(self) == -1)
11741 return NULL;
11742 length = PyUnicode_GET_LENGTH(self);
11743 kind = PyUnicode_KIND(self);
11744 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747 if (length == 1) {
11748 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11749 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11750 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011752 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011754 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 for (i = 0; i < length; i++) {
11757 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011758 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011760 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761}
11762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011763PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011766Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011767False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
11769static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011770unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 Py_ssize_t i, length;
11773 int kind;
11774 void *data;
11775
11776 if (PyUnicode_READY(self) == -1)
11777 return NULL;
11778 length = PyUnicode_GET_LENGTH(self);
11779 kind = PyUnicode_KIND(self);
11780 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011783 if (length == 1)
11784 return PyBool_FromLong(
11785 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011787 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011788 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 for (i = 0; i < length; i++) {
11792 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011793 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011795 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796}
11797
Martin v. Löwis47383402007-08-15 07:32:56 +000011798int
11799PyUnicode_IsIdentifier(PyObject *self)
11800{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 int kind;
11802 void *data;
11803 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011804 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (PyUnicode_READY(self) == -1) {
11807 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011808 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011809 }
11810
11811 /* Special case for empty strings */
11812 if (PyUnicode_GET_LENGTH(self) == 0)
11813 return 0;
11814 kind = PyUnicode_KIND(self);
11815 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011816
11817 /* PEP 3131 says that the first character must be in
11818 XID_Start and subsequent characters in XID_Continue,
11819 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011820 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011821 letters, digits, underscore). However, given the current
11822 definition of XID_Start and XID_Continue, it is sufficient
11823 to check just for these, except that _ must be allowed
11824 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011826 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011827 return 0;
11828
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011829 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011831 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011832 return 1;
11833}
11834
11835PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011836 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011837\n\
11838Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011839to the language definition.\n\
11840\n\
11841Use keyword.iskeyword() to test for reserved identifiers\n\
11842such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011843
11844static PyObject*
11845unicode_isidentifier(PyObject *self)
11846{
11847 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11848}
11849
Georg Brandl559e5d72008-06-11 18:37:52 +000011850PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011851 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011852\n\
11853Return True if all characters in S are considered\n\
11854printable in repr() or S is empty, False otherwise.");
11855
11856static PyObject*
11857unicode_isprintable(PyObject *self)
11858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 Py_ssize_t i, length;
11860 int kind;
11861 void *data;
11862
11863 if (PyUnicode_READY(self) == -1)
11864 return NULL;
11865 length = PyUnicode_GET_LENGTH(self);
11866 kind = PyUnicode_KIND(self);
11867 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011868
11869 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 if (length == 1)
11871 return PyBool_FromLong(
11872 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 for (i = 0; i < length; i++) {
11875 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011876 Py_RETURN_FALSE;
11877 }
11878 }
11879 Py_RETURN_TRUE;
11880}
11881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011882PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011883 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884\n\
11885Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011886iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
11888static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011889unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011891 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892}
11893
Martin v. Löwis18e16552006-02-15 17:27:45 +000011894static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011895unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 if (PyUnicode_READY(self) == -1)
11898 return -1;
11899 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900}
11901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011902PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011903 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011905Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011906done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907
11908static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011909unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011911 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 Py_UCS4 fillchar = ' ';
11913
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011914 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915 return NULL;
11916
Benjamin Petersonbac79492012-01-14 13:34:47 -050011917 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011918 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919
Victor Stinnerc4b49542011-12-11 22:44:26 +010011920 if (PyUnicode_GET_LENGTH(self) >= width)
11921 return unicode_result_unchanged(self);
11922
11923 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924}
11925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011926PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011927 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011929Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930
11931static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011932unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011934 if (PyUnicode_READY(self) == -1)
11935 return NULL;
11936 if (PyUnicode_IS_ASCII(self))
11937 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011938 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939}
11940
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011941#define LEFTSTRIP 0
11942#define RIGHTSTRIP 1
11943#define BOTHSTRIP 2
11944
11945/* Arrays indexed by above */
11946static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11947
11948#define STRIPNAME(i) (stripformat[i]+3)
11949
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011950/* externally visible for str.strip(unicode) */
11951PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011952_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 void *data;
11955 int kind;
11956 Py_ssize_t i, j, len;
11957 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011958 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11961 return NULL;
11962
11963 kind = PyUnicode_KIND(self);
11964 data = PyUnicode_DATA(self);
11965 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011966 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11968 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011969 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011970
Benjamin Peterson14339b62009-01-31 16:36:08 +000011971 i = 0;
11972 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011973 while (i < len) {
11974 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11975 if (!BLOOM(sepmask, ch))
11976 break;
11977 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11978 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 i++;
11980 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011981 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011982
Benjamin Peterson14339b62009-01-31 16:36:08 +000011983 j = len;
11984 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011985 j--;
11986 while (j >= i) {
11987 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11988 if (!BLOOM(sepmask, ch))
11989 break;
11990 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11991 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011992 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011993 }
11994
Benjamin Peterson29060642009-01-31 22:14:21 +000011995 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011996 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011997
Victor Stinner7931d9a2011-11-04 00:22:48 +010011998 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999}
12000
12001PyObject*
12002PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12003{
12004 unsigned char *data;
12005 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012006 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007
Victor Stinnerde636f32011-10-01 03:55:54 +020012008 if (PyUnicode_READY(self) == -1)
12009 return NULL;
12010
Victor Stinner684d5fd2012-05-03 02:32:34 +020012011 length = PyUnicode_GET_LENGTH(self);
12012 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012013
Victor Stinner684d5fd2012-05-03 02:32:34 +020012014 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012015 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016
Victor Stinnerde636f32011-10-01 03:55:54 +020012017 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012018 PyErr_SetString(PyExc_IndexError, "string index out of range");
12019 return NULL;
12020 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012021 if (start >= length || end < start)
12022 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012023
Victor Stinner684d5fd2012-05-03 02:32:34 +020012024 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012025 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012026 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012027 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012028 }
12029 else {
12030 kind = PyUnicode_KIND(self);
12031 data = PyUnicode_1BYTE_DATA(self);
12032 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012033 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012034 length);
12035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037
12038static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012039do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 Py_ssize_t len, i, j;
12042
12043 if (PyUnicode_READY(self) == -1)
12044 return NULL;
12045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012047
Victor Stinnercc7af722013-04-09 22:39:24 +020012048 if (PyUnicode_IS_ASCII(self)) {
12049 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12050
12051 i = 0;
12052 if (striptype != RIGHTSTRIP) {
12053 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012054 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012055 if (!_Py_ascii_whitespace[ch])
12056 break;
12057 i++;
12058 }
12059 }
12060
12061 j = len;
12062 if (striptype != LEFTSTRIP) {
12063 j--;
12064 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012065 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012066 if (!_Py_ascii_whitespace[ch])
12067 break;
12068 j--;
12069 }
12070 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012071 }
12072 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012073 else {
12074 int kind = PyUnicode_KIND(self);
12075 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012076
Victor Stinnercc7af722013-04-09 22:39:24 +020012077 i = 0;
12078 if (striptype != RIGHTSTRIP) {
12079 while (i < len) {
12080 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12081 if (!Py_UNICODE_ISSPACE(ch))
12082 break;
12083 i++;
12084 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012085 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012086
12087 j = len;
12088 if (striptype != LEFTSTRIP) {
12089 j--;
12090 while (j >= i) {
12091 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12092 if (!Py_UNICODE_ISSPACE(ch))
12093 break;
12094 j--;
12095 }
12096 j++;
12097 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012098 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012099
Victor Stinner7931d9a2011-11-04 00:22:48 +010012100 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101}
12102
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012103
12104static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012105do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012106{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012107 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012108
Serhiy Storchakac6792272013-10-19 21:03:34 +030012109 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012110 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012111
Benjamin Peterson14339b62009-01-31 16:36:08 +000012112 if (sep != NULL && sep != Py_None) {
12113 if (PyUnicode_Check(sep))
12114 return _PyUnicode_XStrip(self, striptype, sep);
12115 else {
12116 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012117 "%s arg must be None or str",
12118 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012119 return NULL;
12120 }
12121 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122
Benjamin Peterson14339b62009-01-31 16:36:08 +000012123 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012124}
12125
12126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012127PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012128 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012129\n\
12130Return a copy of the string S with leading and trailing\n\
12131whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012132If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133
12134static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012135unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012137 if (PyTuple_GET_SIZE(args) == 0)
12138 return do_strip(self, BOTHSTRIP); /* Common case */
12139 else
12140 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141}
12142
12143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012144PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012145 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012146\n\
12147Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012148If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012149
12150static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012151unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012152{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012153 if (PyTuple_GET_SIZE(args) == 0)
12154 return do_strip(self, LEFTSTRIP); /* Common case */
12155 else
12156 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012157}
12158
12159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012160PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012161 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012162\n\
12163Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012164If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012165
12166static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012167unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012168{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012169 if (PyTuple_GET_SIZE(args) == 0)
12170 return do_strip(self, RIGHTSTRIP); /* Common case */
12171 else
12172 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012173}
12174
12175
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012177unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012179 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
Serhiy Storchaka05997252013-01-26 12:14:02 +020012182 if (len < 1)
12183 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184
Victor Stinnerc4b49542011-12-11 22:44:26 +010012185 /* no repeat, return original string */
12186 if (len == 1)
12187 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012188
Benjamin Petersonbac79492012-01-14 13:34:47 -050012189 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 return NULL;
12191
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012192 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012193 PyErr_SetString(PyExc_OverflowError,
12194 "repeated string is too long");
12195 return NULL;
12196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012197 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012198
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012199 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200 if (!u)
12201 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012202 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 if (PyUnicode_GET_LENGTH(str) == 1) {
12205 const int kind = PyUnicode_KIND(str);
12206 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012207 if (kind == PyUnicode_1BYTE_KIND) {
12208 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012209 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012210 }
12211 else if (kind == PyUnicode_2BYTE_KIND) {
12212 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012213 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012214 ucs2[n] = fill_char;
12215 } else {
12216 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12217 assert(kind == PyUnicode_4BYTE_KIND);
12218 for (n = 0; n < len; ++n)
12219 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 }
12222 else {
12223 /* number of characters copied this far */
12224 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012225 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 char *to = (char *) PyUnicode_DATA(u);
12227 Py_MEMCPY(to, PyUnicode_DATA(str),
12228 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012229 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 n = (done <= nchars-done) ? done : nchars-done;
12231 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012232 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012233 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234 }
12235
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012236 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012237 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238}
12239
Alexander Belopolsky40018472011-02-26 01:02:56 +000012240PyObject *
12241PyUnicode_Replace(PyObject *obj,
12242 PyObject *subobj,
12243 PyObject *replobj,
12244 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245{
12246 PyObject *self;
12247 PyObject *str1;
12248 PyObject *str2;
12249 PyObject *result;
12250
12251 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012252 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012253 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012255 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012256 Py_DECREF(self);
12257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258 }
12259 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012260 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012261 Py_DECREF(self);
12262 Py_DECREF(str1);
12263 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012265 if (PyUnicode_READY(self) == -1 ||
12266 PyUnicode_READY(str1) == -1 ||
12267 PyUnicode_READY(str2) == -1)
12268 result = NULL;
12269 else
12270 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271 Py_DECREF(self);
12272 Py_DECREF(str1);
12273 Py_DECREF(str2);
12274 return result;
12275}
12276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012277PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012278 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279\n\
12280Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012281old replaced by new. If the optional argument count is\n\
12282given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283
12284static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287 PyObject *str1;
12288 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012289 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 PyObject *result;
12291
Martin v. Löwis18e16552006-02-15 17:27:45 +000012292 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012294 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012295 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012297 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 return NULL;
12299 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012300 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012301 Py_DECREF(str1);
12302 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012303 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012304 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12305 result = NULL;
12306 else
12307 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308
12309 Py_DECREF(str1);
12310 Py_DECREF(str2);
12311 return result;
12312}
12313
Alexander Belopolsky40018472011-02-26 01:02:56 +000012314static PyObject *
12315unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012317 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 Py_ssize_t isize;
12319 Py_ssize_t osize, squote, dquote, i, o;
12320 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012321 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012325 return NULL;
12326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 isize = PyUnicode_GET_LENGTH(unicode);
12328 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 /* Compute length of output, quote characters, and
12331 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012332 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 max = 127;
12334 squote = dquote = 0;
12335 ikind = PyUnicode_KIND(unicode);
12336 for (i = 0; i < isize; i++) {
12337 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012338 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012340 case '\'': squote++; break;
12341 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012343 incr = 2;
12344 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 default:
12346 /* Fast-path ASCII */
12347 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012348 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012350 ;
12351 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012354 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012356 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012358 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012360 if (osize > PY_SSIZE_T_MAX - incr) {
12361 PyErr_SetString(PyExc_OverflowError,
12362 "string is too long to generate repr");
12363 return NULL;
12364 }
12365 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 }
12367
12368 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012369 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012371 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012372 if (dquote)
12373 /* Both squote and dquote present. Use squote,
12374 and escape them */
12375 osize += squote;
12376 else
12377 quote = '"';
12378 }
Victor Stinner55c08782013-04-14 18:45:39 +020012379 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380
12381 repr = PyUnicode_New(osize, max);
12382 if (repr == NULL)
12383 return NULL;
12384 okind = PyUnicode_KIND(repr);
12385 odata = PyUnicode_DATA(repr);
12386
12387 PyUnicode_WRITE(okind, odata, 0, quote);
12388 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012389 if (unchanged) {
12390 _PyUnicode_FastCopyCharacters(repr, 1,
12391 unicode, 0,
12392 isize);
12393 }
12394 else {
12395 for (i = 0, o = 1; i < isize; i++) {
12396 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397
Victor Stinner55c08782013-04-14 18:45:39 +020012398 /* Escape quotes and backslashes */
12399 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012400 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012402 continue;
12403 }
12404
12405 /* Map special whitespace to '\t', \n', '\r' */
12406 if (ch == '\t') {
12407 PyUnicode_WRITE(okind, odata, o++, '\\');
12408 PyUnicode_WRITE(okind, odata, o++, 't');
12409 }
12410 else if (ch == '\n') {
12411 PyUnicode_WRITE(okind, odata, o++, '\\');
12412 PyUnicode_WRITE(okind, odata, o++, 'n');
12413 }
12414 else if (ch == '\r') {
12415 PyUnicode_WRITE(okind, odata, o++, '\\');
12416 PyUnicode_WRITE(okind, odata, o++, 'r');
12417 }
12418
12419 /* Map non-printable US ASCII to '\xhh' */
12420 else if (ch < ' ' || ch == 0x7F) {
12421 PyUnicode_WRITE(okind, odata, o++, '\\');
12422 PyUnicode_WRITE(okind, odata, o++, 'x');
12423 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12424 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12425 }
12426
12427 /* Copy ASCII characters as-is */
12428 else if (ch < 0x7F) {
12429 PyUnicode_WRITE(okind, odata, o++, ch);
12430 }
12431
12432 /* Non-ASCII characters */
12433 else {
12434 /* Map Unicode whitespace and control characters
12435 (categories Z* and C* except ASCII space)
12436 */
12437 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12438 PyUnicode_WRITE(okind, odata, o++, '\\');
12439 /* Map 8-bit characters to '\xhh' */
12440 if (ch <= 0xff) {
12441 PyUnicode_WRITE(okind, odata, o++, 'x');
12442 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12443 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12444 }
12445 /* Map 16-bit characters to '\uxxxx' */
12446 else if (ch <= 0xffff) {
12447 PyUnicode_WRITE(okind, odata, o++, 'u');
12448 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12449 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12450 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12451 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12452 }
12453 /* Map 21-bit characters to '\U00xxxxxx' */
12454 else {
12455 PyUnicode_WRITE(okind, odata, o++, 'U');
12456 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12457 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12458 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12461 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12462 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12463 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12464 }
12465 }
12466 /* Copy characters as-is */
12467 else {
12468 PyUnicode_WRITE(okind, odata, o++, ch);
12469 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012470 }
12471 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012472 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012474 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012475 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476}
12477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012478PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012479 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012480\n\
12481Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012482such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483arguments start and end are interpreted as in slice notation.\n\
12484\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012485Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486
12487static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012490 /* initialize variables to prevent gcc warning */
12491 PyObject *substring = NULL;
12492 Py_ssize_t start = 0;
12493 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012494 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
Jesus Ceaac451502011-04-20 17:09:23 +020012496 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12497 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499
Christian Heimesea71a522013-06-29 21:17:34 +020012500 if (PyUnicode_READY(self) == -1) {
12501 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012503 }
12504 if (PyUnicode_READY(substring) == -1) {
12505 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012507 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012508
Victor Stinner7931d9a2011-11-04 00:22:48 +010012509 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510
12511 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 if (result == -2)
12514 return NULL;
12515
Christian Heimes217cfd12007-12-02 14:31:20 +000012516 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517}
12518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012519PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012520 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012522Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
12524static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012525unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012527 /* initialize variables to prevent gcc warning */
12528 PyObject *substring = NULL;
12529 Py_ssize_t start = 0;
12530 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012531 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532
Jesus Ceaac451502011-04-20 17:09:23 +020012533 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12534 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012535 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536
Christian Heimesea71a522013-06-29 21:17:34 +020012537 if (PyUnicode_READY(self) == -1) {
12538 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012540 }
12541 if (PyUnicode_READY(substring) == -1) {
12542 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012545
Victor Stinner7931d9a2011-11-04 00:22:48 +010012546 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547
12548 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 if (result == -2)
12551 return NULL;
12552
Guido van Rossumd57fd912000-03-10 22:53:23 +000012553 if (result < 0) {
12554 PyErr_SetString(PyExc_ValueError, "substring not found");
12555 return NULL;
12556 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557
Christian Heimes217cfd12007-12-02 14:31:20 +000012558 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559}
12560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012561PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012562 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012563\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012564Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012565done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012566
12567static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012568unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012569{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012570 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 Py_UCS4 fillchar = ' ';
12572
Victor Stinnere9a29352011-10-01 02:14:59 +020012573 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012575
Benjamin Petersonbac79492012-01-14 13:34:47 -050012576 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577 return NULL;
12578
Victor Stinnerc4b49542011-12-11 22:44:26 +010012579 if (PyUnicode_GET_LENGTH(self) >= width)
12580 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581
Victor Stinnerc4b49542011-12-11 22:44:26 +010012582 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583}
12584
Alexander Belopolsky40018472011-02-26 01:02:56 +000012585PyObject *
12586PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587{
12588 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012589
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590 s = PyUnicode_FromObject(s);
12591 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012592 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 if (sep != NULL) {
12594 sep = PyUnicode_FromObject(sep);
12595 if (sep == NULL) {
12596 Py_DECREF(s);
12597 return NULL;
12598 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599 }
12600
Victor Stinner9310abb2011-10-05 00:59:23 +020012601 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602
12603 Py_DECREF(s);
12604 Py_XDECREF(sep);
12605 return result;
12606}
12607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012608PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012609 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610\n\
12611Return a list of the words in S, using sep as the\n\
12612delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012613splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012614whitespace string is a separator and empty strings are\n\
12615removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616
12617static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012618unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012620 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012622 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012624 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12625 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626 return NULL;
12627
12628 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012629 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012631 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012633 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634}
12635
Thomas Wouters477c8d52006-05-27 19:21:47 +000012636PyObject *
12637PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12638{
12639 PyObject* str_obj;
12640 PyObject* sep_obj;
12641 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012642 int kind1, kind2;
12643 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012644 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012645
12646 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012647 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012648 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012649 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012650 if (!sep_obj) {
12651 Py_DECREF(str_obj);
12652 return NULL;
12653 }
12654 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12655 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012656 Py_DECREF(str_obj);
12657 return NULL;
12658 }
12659
Victor Stinner14f8f022011-10-05 20:58:25 +020012660 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662 len1 = PyUnicode_GET_LENGTH(str_obj);
12663 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012664 if (kind1 < kind2 || len1 < len2) {
12665 _Py_INCREF_UNICODE_EMPTY();
12666 if (!unicode_empty)
12667 out = NULL;
12668 else {
12669 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12670 Py_DECREF(unicode_empty);
12671 }
12672 Py_DECREF(sep_obj);
12673 Py_DECREF(str_obj);
12674 return out;
12675 }
12676 buf1 = PyUnicode_DATA(str_obj);
12677 buf2 = PyUnicode_DATA(sep_obj);
12678 if (kind2 != kind1) {
12679 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12680 if (!buf2)
12681 goto onError;
12682 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012683
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012684 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012685 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012686 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12687 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12688 else
12689 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690 break;
12691 case PyUnicode_2BYTE_KIND:
12692 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12693 break;
12694 case PyUnicode_4BYTE_KIND:
12695 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12696 break;
12697 default:
12698 assert(0);
12699 out = 0;
12700 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012701
12702 Py_DECREF(sep_obj);
12703 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012704 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012706
12707 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012708 onError:
12709 Py_DECREF(sep_obj);
12710 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012711 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 PyMem_Free(buf2);
12713 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012714}
12715
12716
12717PyObject *
12718PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12719{
12720 PyObject* str_obj;
12721 PyObject* sep_obj;
12722 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012723 int kind1, kind2;
12724 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012726
12727 str_obj = PyUnicode_FromObject(str_in);
12728 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012729 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012730 sep_obj = PyUnicode_FromObject(sep_in);
12731 if (!sep_obj) {
12732 Py_DECREF(str_obj);
12733 return NULL;
12734 }
12735
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012736 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012737 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 len1 = PyUnicode_GET_LENGTH(str_obj);
12739 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012740 if (kind1 < kind2 || len1 < len2) {
12741 _Py_INCREF_UNICODE_EMPTY();
12742 if (!unicode_empty)
12743 out = NULL;
12744 else {
12745 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12746 Py_DECREF(unicode_empty);
12747 }
12748 Py_DECREF(sep_obj);
12749 Py_DECREF(str_obj);
12750 return out;
12751 }
12752 buf1 = PyUnicode_DATA(str_obj);
12753 buf2 = PyUnicode_DATA(sep_obj);
12754 if (kind2 != kind1) {
12755 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12756 if (!buf2)
12757 goto onError;
12758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012760 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012762 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12763 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12764 else
12765 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766 break;
12767 case PyUnicode_2BYTE_KIND:
12768 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12769 break;
12770 case PyUnicode_4BYTE_KIND:
12771 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12772 break;
12773 default:
12774 assert(0);
12775 out = 0;
12776 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012777
12778 Py_DECREF(sep_obj);
12779 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012780 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012782
12783 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 onError:
12785 Py_DECREF(sep_obj);
12786 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012787 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012788 PyMem_Free(buf2);
12789 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012790}
12791
12792PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012793 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012794\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012795Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012796the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012797found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012798
12799static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012800unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012801{
Victor Stinner9310abb2011-10-05 00:59:23 +020012802 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012803}
12804
12805PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012806 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012808Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012809the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012810separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012811
12812static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012813unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012814{
Victor Stinner9310abb2011-10-05 00:59:23 +020012815 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012816}
12817
Alexander Belopolsky40018472011-02-26 01:02:56 +000012818PyObject *
12819PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012820{
12821 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012822
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012823 s = PyUnicode_FromObject(s);
12824 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012825 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 if (sep != NULL) {
12827 sep = PyUnicode_FromObject(sep);
12828 if (sep == NULL) {
12829 Py_DECREF(s);
12830 return NULL;
12831 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012832 }
12833
Victor Stinner9310abb2011-10-05 00:59:23 +020012834 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012835
12836 Py_DECREF(s);
12837 Py_XDECREF(sep);
12838 return result;
12839}
12840
12841PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012842 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012843\n\
12844Return a list of the words in S, using sep as the\n\
12845delimiter string, starting at the end of the string and\n\
12846working to the front. If maxsplit is given, at most maxsplit\n\
12847splits are done. If sep is not specified, any whitespace string\n\
12848is a separator.");
12849
12850static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012851unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012852{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012853 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012854 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012855 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012856
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012857 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12858 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012859 return NULL;
12860
12861 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012863 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012864 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012865 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012866 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012867}
12868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012869PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012870 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871\n\
12872Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012873Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012874is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875
12876static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012877unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012879 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012880 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012882 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12883 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884 return NULL;
12885
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012886 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887}
12888
12889static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012890PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012892 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893}
12894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012895PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012896 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897\n\
12898Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012899and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900
12901static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012902unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012904 if (PyUnicode_READY(self) == -1)
12905 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012906 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907}
12908
Larry Hastings61272b72014-01-07 12:41:53 -080012909/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012910
Larry Hastings31826802013-10-19 00:09:25 -070012911@staticmethod
12912str.maketrans as unicode_maketrans
12913
12914 x: object
12915
12916 y: unicode=NULL
12917
12918 z: unicode=NULL
12919
12920 /
12921
12922Return a translation table usable for str.translate().
12923
12924If there is only one argument, it must be a dictionary mapping Unicode
12925ordinals (integers) or characters to Unicode ordinals, strings or None.
12926Character keys will be then converted to ordinals.
12927If there are two arguments, they must be strings of equal length, and
12928in the resulting dictionary, each character in x will be mapped to the
12929character at the same position in y. If there is a third argument, it
12930must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012931[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012932
Larry Hastings31826802013-10-19 00:09:25 -070012933static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012934unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012935/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012936{
Georg Brandlceee0772007-11-27 23:48:05 +000012937 PyObject *new = NULL, *key, *value;
12938 Py_ssize_t i = 0;
12939 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012940
Georg Brandlceee0772007-11-27 23:48:05 +000012941 new = PyDict_New();
12942 if (!new)
12943 return NULL;
12944 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012945 int x_kind, y_kind, z_kind;
12946 void *x_data, *y_data, *z_data;
12947
Georg Brandlceee0772007-11-27 23:48:05 +000012948 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012949 if (!PyUnicode_Check(x)) {
12950 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12951 "be a string if there is a second argument");
12952 goto err;
12953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012955 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12956 "arguments must have equal length");
12957 goto err;
12958 }
12959 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 x_kind = PyUnicode_KIND(x);
12961 y_kind = PyUnicode_KIND(y);
12962 x_data = PyUnicode_DATA(x);
12963 y_data = PyUnicode_DATA(y);
12964 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12965 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012966 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012967 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012968 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012969 if (!value) {
12970 Py_DECREF(key);
12971 goto err;
12972 }
Georg Brandlceee0772007-11-27 23:48:05 +000012973 res = PyDict_SetItem(new, key, value);
12974 Py_DECREF(key);
12975 Py_DECREF(value);
12976 if (res < 0)
12977 goto err;
12978 }
12979 /* create entries for deleting chars in z */
12980 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981 z_kind = PyUnicode_KIND(z);
12982 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012983 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012985 if (!key)
12986 goto err;
12987 res = PyDict_SetItem(new, key, Py_None);
12988 Py_DECREF(key);
12989 if (res < 0)
12990 goto err;
12991 }
12992 }
12993 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 int kind;
12995 void *data;
12996
Georg Brandlceee0772007-11-27 23:48:05 +000012997 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012998 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012999 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13000 "to maketrans it must be a dict");
13001 goto err;
13002 }
13003 /* copy entries into the new dict, converting string keys to int keys */
13004 while (PyDict_Next(x, &i, &key, &value)) {
13005 if (PyUnicode_Check(key)) {
13006 /* convert string keys to integer keys */
13007 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013008 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013009 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13010 "table must be of length 1");
13011 goto err;
13012 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 kind = PyUnicode_KIND(key);
13014 data = PyUnicode_DATA(key);
13015 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013016 if (!newkey)
13017 goto err;
13018 res = PyDict_SetItem(new, newkey, value);
13019 Py_DECREF(newkey);
13020 if (res < 0)
13021 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013022 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013023 /* just keep integer keys */
13024 if (PyDict_SetItem(new, key, value) < 0)
13025 goto err;
13026 } else {
13027 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13028 "be strings or integers");
13029 goto err;
13030 }
13031 }
13032 }
13033 return new;
13034 err:
13035 Py_DECREF(new);
13036 return NULL;
13037}
13038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013039PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013040 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013041\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013042Return a copy of the string S in which each character has been mapped\n\
13043through the given translation table. The table must implement\n\
13044lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13045mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13046this operation raises LookupError, the character is left untouched.\n\
13047Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013048
13049static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013050unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013052 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013053}
13054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013055PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013056 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013058Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059
13060static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013061unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013063 if (PyUnicode_READY(self) == -1)
13064 return NULL;
13065 if (PyUnicode_IS_ASCII(self))
13066 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013067 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068}
13069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013070PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013071 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013072\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013073Pad a numeric string S with zeros on the left, to fill a field\n\
13074of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075
13076static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013077unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013079 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013080 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013081 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013082 int kind;
13083 void *data;
13084 Py_UCS4 chr;
13085
Martin v. Löwis18e16552006-02-15 17:27:45 +000013086 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087 return NULL;
13088
Benjamin Petersonbac79492012-01-14 13:34:47 -050013089 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013090 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091
Victor Stinnerc4b49542011-12-11 22:44:26 +010013092 if (PyUnicode_GET_LENGTH(self) >= width)
13093 return unicode_result_unchanged(self);
13094
13095 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096
13097 u = pad(self, fill, 0, '0');
13098
Walter Dörwald068325e2002-04-15 13:36:47 +000013099 if (u == NULL)
13100 return NULL;
13101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013102 kind = PyUnicode_KIND(u);
13103 data = PyUnicode_DATA(u);
13104 chr = PyUnicode_READ(kind, data, fill);
13105
13106 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013108 PyUnicode_WRITE(kind, data, 0, chr);
13109 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110 }
13111
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013112 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013113 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115
13116#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013117static PyObject *
13118unicode__decimal2ascii(PyObject *self)
13119{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013121}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122#endif
13123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013124PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013125 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013127Return True if S starts with the specified prefix, False otherwise.\n\
13128With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013129With optional end, stop comparing S at that position.\n\
13130prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131
13132static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013133unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013134 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013136 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013137 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013138 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013139 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013140 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141
Jesus Ceaac451502011-04-20 17:09:23 +020013142 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013143 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013144 if (PyTuple_Check(subobj)) {
13145 Py_ssize_t i;
13146 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013147 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013148 if (substring == NULL)
13149 return NULL;
13150 result = tailmatch(self, substring, start, end, -1);
13151 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013152 if (result == -1)
13153 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013154 if (result) {
13155 Py_RETURN_TRUE;
13156 }
13157 }
13158 /* nothing matched */
13159 Py_RETURN_FALSE;
13160 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013161 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013162 if (substring == NULL) {
13163 if (PyErr_ExceptionMatches(PyExc_TypeError))
13164 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13165 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013166 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013167 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013168 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013169 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013170 if (result == -1)
13171 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013172 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173}
13174
13175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013176PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013177 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013179Return True if S ends with the specified suffix, False otherwise.\n\
13180With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013181With optional end, stop comparing S at that position.\n\
13182suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
13184static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013185unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013186 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013188 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013189 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013190 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013191 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013192 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193
Jesus Ceaac451502011-04-20 17:09:23 +020013194 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013195 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013196 if (PyTuple_Check(subobj)) {
13197 Py_ssize_t i;
13198 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013199 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013201 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013203 result = tailmatch(self, substring, start, end, +1);
13204 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013205 if (result == -1)
13206 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013207 if (result) {
13208 Py_RETURN_TRUE;
13209 }
13210 }
13211 Py_RETURN_FALSE;
13212 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013213 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013214 if (substring == NULL) {
13215 if (PyErr_ExceptionMatches(PyExc_TypeError))
13216 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13217 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013218 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013219 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013220 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013221 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013222 if (result == -1)
13223 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013224 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225}
13226
Victor Stinner202fdca2012-05-07 12:47:02 +020013227Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013228_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013229{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013230 if (!writer->readonly)
13231 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13232 else {
13233 /* Copy-on-write mode: set buffer size to 0 so
13234 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13235 * next write. */
13236 writer->size = 0;
13237 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013238 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13239 writer->data = PyUnicode_DATA(writer->buffer);
13240 writer->kind = PyUnicode_KIND(writer->buffer);
13241}
13242
Victor Stinnerd3f08822012-05-29 12:57:52 +020013243void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013244_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013245{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013246 memset(writer, 0, sizeof(*writer));
13247#ifdef Py_DEBUG
13248 writer->kind = 5; /* invalid kind */
13249#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013250 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013251}
13252
Victor Stinnerd3f08822012-05-29 12:57:52 +020013253int
13254_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13255 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013256{
Victor Stinner6989ba02013-11-18 21:08:39 +010013257#ifdef MS_WINDOWS
13258 /* On Windows, overallocate by 50% is the best factor */
13259# define OVERALLOCATE_FACTOR 2
13260#else
13261 /* On Linux, overallocate by 25% is the best factor */
13262# define OVERALLOCATE_FACTOR 4
13263#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013264 Py_ssize_t newlen;
13265 PyObject *newbuffer;
13266
Victor Stinnerd3f08822012-05-29 12:57:52 +020013267 assert(length > 0);
13268
Victor Stinner202fdca2012-05-07 12:47:02 +020013269 if (length > PY_SSIZE_T_MAX - writer->pos) {
13270 PyErr_NoMemory();
13271 return -1;
13272 }
13273 newlen = writer->pos + length;
13274
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013275 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013276
Victor Stinnerd3f08822012-05-29 12:57:52 +020013277 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013278 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013279 if (writer->overallocate
13280 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13281 /* overallocate to limit the number of realloc() */
13282 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013283 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013284 if (newlen < writer->min_length)
13285 newlen = writer->min_length;
13286
Victor Stinnerd3f08822012-05-29 12:57:52 +020013287 writer->buffer = PyUnicode_New(newlen, maxchar);
13288 if (writer->buffer == NULL)
13289 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013290 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013291 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013292 if (writer->overallocate
13293 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13294 /* overallocate to limit the number of realloc() */
13295 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013296 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013297 if (newlen < writer->min_length)
13298 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013299
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013300 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013301 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013302 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013303 newbuffer = PyUnicode_New(newlen, maxchar);
13304 if (newbuffer == NULL)
13305 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013306 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13307 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013308 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013309 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013310 }
13311 else {
13312 newbuffer = resize_compact(writer->buffer, newlen);
13313 if (newbuffer == NULL)
13314 return -1;
13315 }
13316 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013317 }
13318 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013319 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013320 newbuffer = PyUnicode_New(writer->size, maxchar);
13321 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013322 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013323 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13324 writer->buffer, 0, writer->pos);
13325 Py_DECREF(writer->buffer);
13326 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013327 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013328 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013329 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013330
13331#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013332}
13333
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013334Py_LOCAL_INLINE(int)
13335_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013336{
13337 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13338 return -1;
13339 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13340 writer->pos++;
13341 return 0;
13342}
13343
13344int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013345_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13346{
13347 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13348}
13349
13350int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013351_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13352{
13353 Py_UCS4 maxchar;
13354 Py_ssize_t len;
13355
13356 if (PyUnicode_READY(str) == -1)
13357 return -1;
13358 len = PyUnicode_GET_LENGTH(str);
13359 if (len == 0)
13360 return 0;
13361 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13362 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013363 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013364 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013365 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013366 Py_INCREF(str);
13367 writer->buffer = str;
13368 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013369 writer->pos += len;
13370 return 0;
13371 }
13372 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13373 return -1;
13374 }
13375 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13376 str, 0, len);
13377 writer->pos += len;
13378 return 0;
13379}
13380
Victor Stinnere215d962012-10-06 23:03:36 +020013381int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013382_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13383 Py_ssize_t start, Py_ssize_t end)
13384{
13385 Py_UCS4 maxchar;
13386 Py_ssize_t len;
13387
13388 if (PyUnicode_READY(str) == -1)
13389 return -1;
13390
13391 assert(0 <= start);
13392 assert(end <= PyUnicode_GET_LENGTH(str));
13393 assert(start <= end);
13394
13395 if (end == 0)
13396 return 0;
13397
13398 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13399 return _PyUnicodeWriter_WriteStr(writer, str);
13400
13401 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13402 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13403 else
13404 maxchar = writer->maxchar;
13405 len = end - start;
13406
13407 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13408 return -1;
13409
13410 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13411 str, start, len);
13412 writer->pos += len;
13413 return 0;
13414}
13415
13416int
Victor Stinner4a587072013-11-19 12:54:53 +010013417_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13418 const char *ascii, Py_ssize_t len)
13419{
13420 if (len == -1)
13421 len = strlen(ascii);
13422
13423 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13424
13425 if (writer->buffer == NULL && !writer->overallocate) {
13426 PyObject *str;
13427
13428 str = _PyUnicode_FromASCII(ascii, len);
13429 if (str == NULL)
13430 return -1;
13431
13432 writer->readonly = 1;
13433 writer->buffer = str;
13434 _PyUnicodeWriter_Update(writer);
13435 writer->pos += len;
13436 return 0;
13437 }
13438
13439 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13440 return -1;
13441
13442 switch (writer->kind)
13443 {
13444 case PyUnicode_1BYTE_KIND:
13445 {
13446 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13447 Py_UCS1 *data = writer->data;
13448
13449 Py_MEMCPY(data + writer->pos, str, len);
13450 break;
13451 }
13452 case PyUnicode_2BYTE_KIND:
13453 {
13454 _PyUnicode_CONVERT_BYTES(
13455 Py_UCS1, Py_UCS2,
13456 ascii, ascii + len,
13457 (Py_UCS2 *)writer->data + writer->pos);
13458 break;
13459 }
13460 case PyUnicode_4BYTE_KIND:
13461 {
13462 _PyUnicode_CONVERT_BYTES(
13463 Py_UCS1, Py_UCS4,
13464 ascii, ascii + len,
13465 (Py_UCS4 *)writer->data + writer->pos);
13466 break;
13467 }
13468 default:
13469 assert(0);
13470 }
13471
13472 writer->pos += len;
13473 return 0;
13474}
13475
13476int
13477_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13478 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013479{
13480 Py_UCS4 maxchar;
13481
13482 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13483 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13484 return -1;
13485 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13486 writer->pos += len;
13487 return 0;
13488}
13489
Victor Stinnerd3f08822012-05-29 12:57:52 +020013490PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013491_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013492{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013493 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013494 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013495 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013496 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013497 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013498 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013499 str = writer->buffer;
13500 writer->buffer = NULL;
13501 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13502 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013503 }
13504 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13505 PyObject *newbuffer;
13506 newbuffer = resize_compact(writer->buffer, writer->pos);
13507 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013508 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013509 return NULL;
13510 }
13511 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013512 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013513 str = writer->buffer;
13514 writer->buffer = NULL;
13515 assert(_PyUnicode_CheckConsistency(str, 1));
13516 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013517}
13518
Victor Stinnerd3f08822012-05-29 12:57:52 +020013519void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013520_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013521{
13522 Py_CLEAR(writer->buffer);
13523}
13524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013525#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013526
13527PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013529\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013530Return a formatted version of S, using substitutions from args and kwargs.\n\
13531The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013532
Eric Smith27bbca62010-11-04 17:06:58 +000013533PyDoc_STRVAR(format_map__doc__,
13534 "S.format_map(mapping) -> str\n\
13535\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013536Return a formatted version of S, using substitutions from mapping.\n\
13537The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013538
Eric Smith4a7d76d2008-05-30 18:10:19 +000013539static PyObject *
13540unicode__format__(PyObject* self, PyObject* args)
13541{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013542 PyObject *format_spec;
13543 _PyUnicodeWriter writer;
13544 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013545
13546 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13547 return NULL;
13548
Victor Stinnerd3f08822012-05-29 12:57:52 +020013549 if (PyUnicode_READY(self) == -1)
13550 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013551 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013552 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13553 self, format_spec, 0,
13554 PyUnicode_GET_LENGTH(format_spec));
13555 if (ret == -1) {
13556 _PyUnicodeWriter_Dealloc(&writer);
13557 return NULL;
13558 }
13559 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013560}
13561
Eric Smith8c663262007-08-25 02:26:07 +000013562PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013564\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013565Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013566
13567static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013568unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570 Py_ssize_t size;
13571
13572 /* If it's a compact object, account for base structure +
13573 character data. */
13574 if (PyUnicode_IS_COMPACT_ASCII(v))
13575 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13576 else if (PyUnicode_IS_COMPACT(v))
13577 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013578 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013579 else {
13580 /* If it is a two-block object, account for base object, and
13581 for character block if present. */
13582 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013583 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013584 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013585 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013586 }
13587 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013588 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013589 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013590 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013591 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013592 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013593
13594 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013595}
13596
13597PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013599
13600static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013601unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013602{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013603 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013604 if (!copy)
13605 return NULL;
13606 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013607}
13608
Guido van Rossumd57fd912000-03-10 22:53:23 +000013609static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013610 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013611 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013612 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13613 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013614 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13615 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013616 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013617 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13618 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13619 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013620 {"expandtabs", (PyCFunction) unicode_expandtabs,
13621 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013622 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013623 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013624 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13625 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13626 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013627 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013628 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13629 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13630 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013631 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013632 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013633 {"splitlines", (PyCFunction) unicode_splitlines,
13634 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013635 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013636 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13637 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13638 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13639 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13640 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13641 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13642 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13643 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13644 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13645 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13646 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13647 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13648 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13649 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013650 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013651 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013652 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013653 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013654 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013655 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013656 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013657 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013658#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013659 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013660 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013661#endif
13662
Benjamin Peterson14339b62009-01-31 16:36:08 +000013663 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013664 {NULL, NULL}
13665};
13666
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013667static PyObject *
13668unicode_mod(PyObject *v, PyObject *w)
13669{
Brian Curtindfc80e32011-08-10 20:28:54 -050013670 if (!PyUnicode_Check(v))
13671 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013673}
13674
13675static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013676 0, /*nb_add*/
13677 0, /*nb_subtract*/
13678 0, /*nb_multiply*/
13679 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013680};
13681
Guido van Rossumd57fd912000-03-10 22:53:23 +000013682static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013683 (lenfunc) unicode_length, /* sq_length */
13684 PyUnicode_Concat, /* sq_concat */
13685 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13686 (ssizeargfunc) unicode_getitem, /* sq_item */
13687 0, /* sq_slice */
13688 0, /* sq_ass_item */
13689 0, /* sq_ass_slice */
13690 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013691};
13692
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013693static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013694unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013695{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013696 if (PyUnicode_READY(self) == -1)
13697 return NULL;
13698
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013699 if (PyIndex_Check(item)) {
13700 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013701 if (i == -1 && PyErr_Occurred())
13702 return NULL;
13703 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013704 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013705 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013706 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013707 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013708 PyObject *result;
13709 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013710 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013711 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013713 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013714 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013715 return NULL;
13716 }
13717
13718 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013719 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013720 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013721 slicelength == PyUnicode_GET_LENGTH(self)) {
13722 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013723 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013724 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013725 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013726 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013727 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013728 src_kind = PyUnicode_KIND(self);
13729 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013730 if (!PyUnicode_IS_ASCII(self)) {
13731 kind_limit = kind_maxchar_limit(src_kind);
13732 max_char = 0;
13733 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13734 ch = PyUnicode_READ(src_kind, src_data, cur);
13735 if (ch > max_char) {
13736 max_char = ch;
13737 if (max_char >= kind_limit)
13738 break;
13739 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013740 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013741 }
Victor Stinner55c99112011-10-13 01:17:06 +020013742 else
13743 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013744 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013745 if (result == NULL)
13746 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013747 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013748 dest_data = PyUnicode_DATA(result);
13749
13750 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013751 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13752 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013753 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013754 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013755 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013756 } else {
13757 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13758 return NULL;
13759 }
13760}
13761
13762static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013763 (lenfunc)unicode_length, /* mp_length */
13764 (binaryfunc)unicode_subscript, /* mp_subscript */
13765 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013766};
13767
Guido van Rossumd57fd912000-03-10 22:53:23 +000013768
Guido van Rossumd57fd912000-03-10 22:53:23 +000013769/* Helpers for PyUnicode_Format() */
13770
Victor Stinnera47082312012-10-04 02:19:54 +020013771struct unicode_formatter_t {
13772 PyObject *args;
13773 int args_owned;
13774 Py_ssize_t arglen, argidx;
13775 PyObject *dict;
13776
13777 enum PyUnicode_Kind fmtkind;
13778 Py_ssize_t fmtcnt, fmtpos;
13779 void *fmtdata;
13780 PyObject *fmtstr;
13781
13782 _PyUnicodeWriter writer;
13783};
13784
13785struct unicode_format_arg_t {
13786 Py_UCS4 ch;
13787 int flags;
13788 Py_ssize_t width;
13789 int prec;
13790 int sign;
13791};
13792
Guido van Rossumd57fd912000-03-10 22:53:23 +000013793static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013794unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013795{
Victor Stinnera47082312012-10-04 02:19:54 +020013796 Py_ssize_t argidx = ctx->argidx;
13797
13798 if (argidx < ctx->arglen) {
13799 ctx->argidx++;
13800 if (ctx->arglen < 0)
13801 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013802 else
Victor Stinnera47082312012-10-04 02:19:54 +020013803 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013804 }
13805 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013806 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013807 return NULL;
13808}
13809
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013810/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013811
Victor Stinnera47082312012-10-04 02:19:54 +020013812/* Format a float into the writer if the writer is not NULL, or into *p_output
13813 otherwise.
13814
13815 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013816static int
Victor Stinnera47082312012-10-04 02:19:54 +020013817formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13818 PyObject **p_output,
13819 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013820{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013821 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013822 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013823 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013824 int prec;
13825 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013826
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827 x = PyFloat_AsDouble(v);
13828 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013829 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013830
Victor Stinnera47082312012-10-04 02:19:54 +020013831 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013832 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013833 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013834
Victor Stinnera47082312012-10-04 02:19:54 +020013835 if (arg->flags & F_ALT)
13836 dtoa_flags = Py_DTSF_ALT;
13837 else
13838 dtoa_flags = 0;
13839 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013840 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013841 return -1;
13842 len = strlen(p);
13843 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013844 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013845 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013846 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013847 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013848 }
13849 else
13850 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013851 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013852 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013853}
13854
Victor Stinnerd0880d52012-04-27 23:40:13 +020013855/* formatlong() emulates the format codes d, u, o, x and X, and
13856 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13857 * Python's regular ints.
13858 * Return value: a new PyUnicodeObject*, or NULL if error.
13859 * The output string is of the form
13860 * "-"? ("0x" | "0X")? digit+
13861 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13862 * set in flags. The case of hex digits will be correct,
13863 * There will be at least prec digits, zero-filled on the left if
13864 * necessary to get that many.
13865 * val object to be converted
13866 * flags bitmask of format flags; only F_ALT is looked at
13867 * prec minimum number of digits; 0-fill on left if needed
13868 * type a character in [duoxX]; u acts the same as d
13869 *
13870 * CAUTION: o, x and X conversions on regular ints can never
13871 * produce a '-' sign, but can for Python's unbounded ints.
13872 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013873PyObject *
13874_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013875{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013876 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013877 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013878 Py_ssize_t i;
13879 int sign; /* 1 if '-', else 0 */
13880 int len; /* number of characters */
13881 Py_ssize_t llen;
13882 int numdigits; /* len == numnondigits + numdigits */
13883 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013884
Victor Stinnerd0880d52012-04-27 23:40:13 +020013885 /* Avoid exceeding SSIZE_T_MAX */
13886 if (prec > INT_MAX-3) {
13887 PyErr_SetString(PyExc_OverflowError,
13888 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013889 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013890 }
13891
13892 assert(PyLong_Check(val));
13893
13894 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013895 default:
13896 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013897 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013898 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013899 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013900 /* int and int subclasses should print numerically when a numeric */
13901 /* format code is used (see issue18780) */
13902 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013903 break;
13904 case 'o':
13905 numnondigits = 2;
13906 result = PyNumber_ToBase(val, 8);
13907 break;
13908 case 'x':
13909 case 'X':
13910 numnondigits = 2;
13911 result = PyNumber_ToBase(val, 16);
13912 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013913 }
13914 if (!result)
13915 return NULL;
13916
13917 assert(unicode_modifiable(result));
13918 assert(PyUnicode_IS_READY(result));
13919 assert(PyUnicode_IS_ASCII(result));
13920
13921 /* To modify the string in-place, there can only be one reference. */
13922 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013923 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013924 PyErr_BadInternalCall();
13925 return NULL;
13926 }
13927 buf = PyUnicode_DATA(result);
13928 llen = PyUnicode_GET_LENGTH(result);
13929 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013930 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013931 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013932 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013933 return NULL;
13934 }
13935 len = (int)llen;
13936 sign = buf[0] == '-';
13937 numnondigits += sign;
13938 numdigits = len - numnondigits;
13939 assert(numdigits > 0);
13940
13941 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013942 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013943 (type == 'o' || type == 'x' || type == 'X'))) {
13944 assert(buf[sign] == '0');
13945 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13946 buf[sign+1] == 'o');
13947 numnondigits -= 2;
13948 buf += 2;
13949 len -= 2;
13950 if (sign)
13951 buf[0] = '-';
13952 assert(len == numnondigits + numdigits);
13953 assert(numdigits > 0);
13954 }
13955
13956 /* Fill with leading zeroes to meet minimum width. */
13957 if (prec > numdigits) {
13958 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13959 numnondigits + prec);
13960 char *b1;
13961 if (!r1) {
13962 Py_DECREF(result);
13963 return NULL;
13964 }
13965 b1 = PyBytes_AS_STRING(r1);
13966 for (i = 0; i < numnondigits; ++i)
13967 *b1++ = *buf++;
13968 for (i = 0; i < prec - numdigits; i++)
13969 *b1++ = '0';
13970 for (i = 0; i < numdigits; i++)
13971 *b1++ = *buf++;
13972 *b1 = '\0';
13973 Py_DECREF(result);
13974 result = r1;
13975 buf = PyBytes_AS_STRING(result);
13976 len = numnondigits + prec;
13977 }
13978
13979 /* Fix up case for hex conversions. */
13980 if (type == 'X') {
13981 /* Need to convert all lower case letters to upper case.
13982 and need to convert 0x to 0X (and -0x to -0X). */
13983 for (i = 0; i < len; i++)
13984 if (buf[i] >= 'a' && buf[i] <= 'x')
13985 buf[i] -= 'a'-'A';
13986 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013987 if (!PyUnicode_Check(result)
13988 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013989 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013990 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013991 Py_DECREF(result);
13992 result = unicode;
13993 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013994 else if (len != PyUnicode_GET_LENGTH(result)) {
13995 if (PyUnicode_Resize(&result, len) < 0)
13996 Py_CLEAR(result);
13997 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013999}
14000
Ethan Furmandf3ed242014-01-05 06:50:30 -080014001/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014002 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014003 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014004 * -1 and raise an exception on error */
14005static int
Victor Stinnera47082312012-10-04 02:19:54 +020014006mainformatlong(PyObject *v,
14007 struct unicode_format_arg_t *arg,
14008 PyObject **p_output,
14009 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014010{
14011 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014012 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014013
14014 if (!PyNumber_Check(v))
14015 goto wrongtype;
14016
Ethan Furman9ab74802014-03-21 06:38:46 -070014017 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014018 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014019 if (type == 'o' || type == 'x' || type == 'X') {
14020 iobj = PyNumber_Index(v);
14021 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014022 if (PyErr_ExceptionMatches(PyExc_TypeError))
14023 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014024 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014025 }
14026 }
14027 else {
14028 iobj = PyNumber_Long(v);
14029 if (iobj == NULL ) {
14030 if (PyErr_ExceptionMatches(PyExc_TypeError))
14031 goto wrongtype;
14032 return -1;
14033 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014034 }
14035 assert(PyLong_Check(iobj));
14036 }
14037 else {
14038 iobj = v;
14039 Py_INCREF(iobj);
14040 }
14041
14042 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014043 && arg->width == -1 && arg->prec == -1
14044 && !(arg->flags & (F_SIGN | F_BLANK))
14045 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014046 {
14047 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014048 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014049 int base;
14050
Victor Stinnera47082312012-10-04 02:19:54 +020014051 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014052 {
14053 default:
14054 assert(0 && "'type' not in [diuoxX]");
14055 case 'd':
14056 case 'i':
14057 case 'u':
14058 base = 10;
14059 break;
14060 case 'o':
14061 base = 8;
14062 break;
14063 case 'x':
14064 case 'X':
14065 base = 16;
14066 break;
14067 }
14068
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014069 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14070 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014071 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014072 }
14073 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014074 return 1;
14075 }
14076
Ethan Furmanb95b5612015-01-23 20:05:18 -080014077 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014078 Py_DECREF(iobj);
14079 if (res == NULL)
14080 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014081 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014082 return 0;
14083
14084wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014085 switch(type)
14086 {
14087 case 'o':
14088 case 'x':
14089 case 'X':
14090 PyErr_Format(PyExc_TypeError,
14091 "%%%c format: an integer is required, "
14092 "not %.200s",
14093 type, Py_TYPE(v)->tp_name);
14094 break;
14095 default:
14096 PyErr_Format(PyExc_TypeError,
14097 "%%%c format: a number is required, "
14098 "not %.200s",
14099 type, Py_TYPE(v)->tp_name);
14100 break;
14101 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014102 return -1;
14103}
14104
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014105static Py_UCS4
14106formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014107{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014108 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014109 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014110 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014111 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014112 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014113 goto onError;
14114 }
14115 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014116 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014117 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014118 /* make sure number is a type of integer */
14119 if (!PyLong_Check(v)) {
14120 iobj = PyNumber_Index(v);
14121 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014122 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014123 }
14124 v = iobj;
14125 Py_DECREF(iobj);
14126 }
14127 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014128 x = PyLong_AsLong(v);
14129 if (x == -1 && PyErr_Occurred())
14130 goto onError;
14131
Victor Stinner8faf8212011-12-08 22:14:11 +010014132 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 PyErr_SetString(PyExc_OverflowError,
14134 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014135 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014136 }
14137
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014138 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014139 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014140
Benjamin Peterson29060642009-01-31 22:14:21 +000014141 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014142 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014143 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014144 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014145}
14146
Victor Stinnera47082312012-10-04 02:19:54 +020014147/* Parse options of an argument: flags, width, precision.
14148 Handle also "%(name)" syntax.
14149
14150 Return 0 if the argument has been formatted into arg->str.
14151 Return 1 if the argument has been written into ctx->writer,
14152 Raise an exception and return -1 on error. */
14153static int
14154unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14155 struct unicode_format_arg_t *arg)
14156{
14157#define FORMAT_READ(ctx) \
14158 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14159
14160 PyObject *v;
14161
Victor Stinnera47082312012-10-04 02:19:54 +020014162 if (arg->ch == '(') {
14163 /* Get argument value from a dictionary. Example: "%(name)s". */
14164 Py_ssize_t keystart;
14165 Py_ssize_t keylen;
14166 PyObject *key;
14167 int pcount = 1;
14168
14169 if (ctx->dict == NULL) {
14170 PyErr_SetString(PyExc_TypeError,
14171 "format requires a mapping");
14172 return -1;
14173 }
14174 ++ctx->fmtpos;
14175 --ctx->fmtcnt;
14176 keystart = ctx->fmtpos;
14177 /* Skip over balanced parentheses */
14178 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14179 arg->ch = FORMAT_READ(ctx);
14180 if (arg->ch == ')')
14181 --pcount;
14182 else if (arg->ch == '(')
14183 ++pcount;
14184 ctx->fmtpos++;
14185 }
14186 keylen = ctx->fmtpos - keystart - 1;
14187 if (ctx->fmtcnt < 0 || pcount > 0) {
14188 PyErr_SetString(PyExc_ValueError,
14189 "incomplete format key");
14190 return -1;
14191 }
14192 key = PyUnicode_Substring(ctx->fmtstr,
14193 keystart, keystart + keylen);
14194 if (key == NULL)
14195 return -1;
14196 if (ctx->args_owned) {
14197 Py_DECREF(ctx->args);
14198 ctx->args_owned = 0;
14199 }
14200 ctx->args = PyObject_GetItem(ctx->dict, key);
14201 Py_DECREF(key);
14202 if (ctx->args == NULL)
14203 return -1;
14204 ctx->args_owned = 1;
14205 ctx->arglen = -1;
14206 ctx->argidx = -2;
14207 }
14208
14209 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014210 while (--ctx->fmtcnt >= 0) {
14211 arg->ch = FORMAT_READ(ctx);
14212 ctx->fmtpos++;
14213 switch (arg->ch) {
14214 case '-': arg->flags |= F_LJUST; continue;
14215 case '+': arg->flags |= F_SIGN; continue;
14216 case ' ': arg->flags |= F_BLANK; continue;
14217 case '#': arg->flags |= F_ALT; continue;
14218 case '0': arg->flags |= F_ZERO; continue;
14219 }
14220 break;
14221 }
14222
14223 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014224 if (arg->ch == '*') {
14225 v = unicode_format_getnextarg(ctx);
14226 if (v == NULL)
14227 return -1;
14228 if (!PyLong_Check(v)) {
14229 PyErr_SetString(PyExc_TypeError,
14230 "* wants int");
14231 return -1;
14232 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014233 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014234 if (arg->width == -1 && PyErr_Occurred())
14235 return -1;
14236 if (arg->width < 0) {
14237 arg->flags |= F_LJUST;
14238 arg->width = -arg->width;
14239 }
14240 if (--ctx->fmtcnt >= 0) {
14241 arg->ch = FORMAT_READ(ctx);
14242 ctx->fmtpos++;
14243 }
14244 }
14245 else if (arg->ch >= '0' && arg->ch <= '9') {
14246 arg->width = arg->ch - '0';
14247 while (--ctx->fmtcnt >= 0) {
14248 arg->ch = FORMAT_READ(ctx);
14249 ctx->fmtpos++;
14250 if (arg->ch < '0' || arg->ch > '9')
14251 break;
14252 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14253 mixing signed and unsigned comparison. Since arg->ch is between
14254 '0' and '9', casting to int is safe. */
14255 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14256 PyErr_SetString(PyExc_ValueError,
14257 "width too big");
14258 return -1;
14259 }
14260 arg->width = arg->width*10 + (arg->ch - '0');
14261 }
14262 }
14263
14264 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014265 if (arg->ch == '.') {
14266 arg->prec = 0;
14267 if (--ctx->fmtcnt >= 0) {
14268 arg->ch = FORMAT_READ(ctx);
14269 ctx->fmtpos++;
14270 }
14271 if (arg->ch == '*') {
14272 v = unicode_format_getnextarg(ctx);
14273 if (v == NULL)
14274 return -1;
14275 if (!PyLong_Check(v)) {
14276 PyErr_SetString(PyExc_TypeError,
14277 "* wants int");
14278 return -1;
14279 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014280 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014281 if (arg->prec == -1 && PyErr_Occurred())
14282 return -1;
14283 if (arg->prec < 0)
14284 arg->prec = 0;
14285 if (--ctx->fmtcnt >= 0) {
14286 arg->ch = FORMAT_READ(ctx);
14287 ctx->fmtpos++;
14288 }
14289 }
14290 else if (arg->ch >= '0' && arg->ch <= '9') {
14291 arg->prec = arg->ch - '0';
14292 while (--ctx->fmtcnt >= 0) {
14293 arg->ch = FORMAT_READ(ctx);
14294 ctx->fmtpos++;
14295 if (arg->ch < '0' || arg->ch > '9')
14296 break;
14297 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14298 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014299 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014300 return -1;
14301 }
14302 arg->prec = arg->prec*10 + (arg->ch - '0');
14303 }
14304 }
14305 }
14306
14307 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14308 if (ctx->fmtcnt >= 0) {
14309 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14310 if (--ctx->fmtcnt >= 0) {
14311 arg->ch = FORMAT_READ(ctx);
14312 ctx->fmtpos++;
14313 }
14314 }
14315 }
14316 if (ctx->fmtcnt < 0) {
14317 PyErr_SetString(PyExc_ValueError,
14318 "incomplete format");
14319 return -1;
14320 }
14321 return 0;
14322
14323#undef FORMAT_READ
14324}
14325
14326/* Format one argument. Supported conversion specifiers:
14327
14328 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014329 - "i", "d", "u": int or float
14330 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014331 - "e", "E", "f", "F", "g", "G": float
14332 - "c": int or str (1 character)
14333
Victor Stinner8dbd4212012-12-04 09:30:24 +010014334 When possible, the output is written directly into the Unicode writer
14335 (ctx->writer). A string is created when padding is required.
14336
Victor Stinnera47082312012-10-04 02:19:54 +020014337 Return 0 if the argument has been formatted into *p_str,
14338 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014339 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014340static int
14341unicode_format_arg_format(struct unicode_formatter_t *ctx,
14342 struct unicode_format_arg_t *arg,
14343 PyObject **p_str)
14344{
14345 PyObject *v;
14346 _PyUnicodeWriter *writer = &ctx->writer;
14347
14348 if (ctx->fmtcnt == 0)
14349 ctx->writer.overallocate = 0;
14350
14351 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014352 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014353 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014354 return 1;
14355 }
14356
14357 v = unicode_format_getnextarg(ctx);
14358 if (v == NULL)
14359 return -1;
14360
Victor Stinnera47082312012-10-04 02:19:54 +020014361
14362 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014363 case 's':
14364 case 'r':
14365 case 'a':
14366 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14367 /* Fast path */
14368 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14369 return -1;
14370 return 1;
14371 }
14372
14373 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14374 *p_str = v;
14375 Py_INCREF(*p_str);
14376 }
14377 else {
14378 if (arg->ch == 's')
14379 *p_str = PyObject_Str(v);
14380 else if (arg->ch == 'r')
14381 *p_str = PyObject_Repr(v);
14382 else
14383 *p_str = PyObject_ASCII(v);
14384 }
14385 break;
14386
14387 case 'i':
14388 case 'd':
14389 case 'u':
14390 case 'o':
14391 case 'x':
14392 case 'X':
14393 {
14394 int ret = mainformatlong(v, arg, p_str, writer);
14395 if (ret != 0)
14396 return ret;
14397 arg->sign = 1;
14398 break;
14399 }
14400
14401 case 'e':
14402 case 'E':
14403 case 'f':
14404 case 'F':
14405 case 'g':
14406 case 'G':
14407 if (arg->width == -1 && arg->prec == -1
14408 && !(arg->flags & (F_SIGN | F_BLANK)))
14409 {
14410 /* Fast path */
14411 if (formatfloat(v, arg, NULL, writer) == -1)
14412 return -1;
14413 return 1;
14414 }
14415
14416 arg->sign = 1;
14417 if (formatfloat(v, arg, p_str, NULL) == -1)
14418 return -1;
14419 break;
14420
14421 case 'c':
14422 {
14423 Py_UCS4 ch = formatchar(v);
14424 if (ch == (Py_UCS4) -1)
14425 return -1;
14426 if (arg->width == -1 && arg->prec == -1) {
14427 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014428 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014429 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014430 return 1;
14431 }
14432 *p_str = PyUnicode_FromOrdinal(ch);
14433 break;
14434 }
14435
14436 default:
14437 PyErr_Format(PyExc_ValueError,
14438 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014439 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014440 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14441 (int)arg->ch,
14442 ctx->fmtpos - 1);
14443 return -1;
14444 }
14445 if (*p_str == NULL)
14446 return -1;
14447 assert (PyUnicode_Check(*p_str));
14448 return 0;
14449}
14450
14451static int
14452unicode_format_arg_output(struct unicode_formatter_t *ctx,
14453 struct unicode_format_arg_t *arg,
14454 PyObject *str)
14455{
14456 Py_ssize_t len;
14457 enum PyUnicode_Kind kind;
14458 void *pbuf;
14459 Py_ssize_t pindex;
14460 Py_UCS4 signchar;
14461 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014462 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014463 Py_ssize_t sublen;
14464 _PyUnicodeWriter *writer = &ctx->writer;
14465 Py_UCS4 fill;
14466
14467 fill = ' ';
14468 if (arg->sign && arg->flags & F_ZERO)
14469 fill = '0';
14470
14471 if (PyUnicode_READY(str) == -1)
14472 return -1;
14473
14474 len = PyUnicode_GET_LENGTH(str);
14475 if ((arg->width == -1 || arg->width <= len)
14476 && (arg->prec == -1 || arg->prec >= len)
14477 && !(arg->flags & (F_SIGN | F_BLANK)))
14478 {
14479 /* Fast path */
14480 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14481 return -1;
14482 return 0;
14483 }
14484
14485 /* Truncate the string for "s", "r" and "a" formats
14486 if the precision is set */
14487 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14488 if (arg->prec >= 0 && len > arg->prec)
14489 len = arg->prec;
14490 }
14491
14492 /* Adjust sign and width */
14493 kind = PyUnicode_KIND(str);
14494 pbuf = PyUnicode_DATA(str);
14495 pindex = 0;
14496 signchar = '\0';
14497 if (arg->sign) {
14498 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14499 if (ch == '-' || ch == '+') {
14500 signchar = ch;
14501 len--;
14502 pindex++;
14503 }
14504 else if (arg->flags & F_SIGN)
14505 signchar = '+';
14506 else if (arg->flags & F_BLANK)
14507 signchar = ' ';
14508 else
14509 arg->sign = 0;
14510 }
14511 if (arg->width < len)
14512 arg->width = len;
14513
14514 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014515 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014516 if (!(arg->flags & F_LJUST)) {
14517 if (arg->sign) {
14518 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014519 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014520 }
14521 else {
14522 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014523 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014524 }
14525 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014526 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14527 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014528 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014529 }
14530
Victor Stinnera47082312012-10-04 02:19:54 +020014531 buflen = arg->width;
14532 if (arg->sign && len == arg->width)
14533 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014534 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014535 return -1;
14536
14537 /* Write the sign if needed */
14538 if (arg->sign) {
14539 if (fill != ' ') {
14540 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14541 writer->pos += 1;
14542 }
14543 if (arg->width > len)
14544 arg->width--;
14545 }
14546
14547 /* Write the numeric prefix for "x", "X" and "o" formats
14548 if the alternate form is used.
14549 For example, write "0x" for the "%#x" format. */
14550 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14551 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14552 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14553 if (fill != ' ') {
14554 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14555 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14556 writer->pos += 2;
14557 pindex += 2;
14558 }
14559 arg->width -= 2;
14560 if (arg->width < 0)
14561 arg->width = 0;
14562 len -= 2;
14563 }
14564
14565 /* Pad left with the fill character if needed */
14566 if (arg->width > len && !(arg->flags & F_LJUST)) {
14567 sublen = arg->width - len;
14568 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14569 writer->pos += sublen;
14570 arg->width = len;
14571 }
14572
14573 /* If padding with spaces: write sign if needed and/or numeric prefix if
14574 the alternate form is used */
14575 if (fill == ' ') {
14576 if (arg->sign) {
14577 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14578 writer->pos += 1;
14579 }
14580 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14581 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14582 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14583 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14584 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14585 writer->pos += 2;
14586 pindex += 2;
14587 }
14588 }
14589
14590 /* Write characters */
14591 if (len) {
14592 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14593 str, pindex, len);
14594 writer->pos += len;
14595 }
14596
14597 /* Pad right with the fill character if needed */
14598 if (arg->width > len) {
14599 sublen = arg->width - len;
14600 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14601 writer->pos += sublen;
14602 }
14603 return 0;
14604}
14605
14606/* Helper of PyUnicode_Format(): format one arg.
14607 Return 0 on success, raise an exception and return -1 on error. */
14608static int
14609unicode_format_arg(struct unicode_formatter_t *ctx)
14610{
14611 struct unicode_format_arg_t arg;
14612 PyObject *str;
14613 int ret;
14614
Victor Stinner8dbd4212012-12-04 09:30:24 +010014615 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14616 arg.flags = 0;
14617 arg.width = -1;
14618 arg.prec = -1;
14619 arg.sign = 0;
14620 str = NULL;
14621
Victor Stinnera47082312012-10-04 02:19:54 +020014622 ret = unicode_format_arg_parse(ctx, &arg);
14623 if (ret == -1)
14624 return -1;
14625
14626 ret = unicode_format_arg_format(ctx, &arg, &str);
14627 if (ret == -1)
14628 return -1;
14629
14630 if (ret != 1) {
14631 ret = unicode_format_arg_output(ctx, &arg, str);
14632 Py_DECREF(str);
14633 if (ret == -1)
14634 return -1;
14635 }
14636
14637 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14638 PyErr_SetString(PyExc_TypeError,
14639 "not all arguments converted during string formatting");
14640 return -1;
14641 }
14642 return 0;
14643}
14644
Alexander Belopolsky40018472011-02-26 01:02:56 +000014645PyObject *
14646PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014647{
Victor Stinnera47082312012-10-04 02:19:54 +020014648 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014649
Guido van Rossumd57fd912000-03-10 22:53:23 +000014650 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014651 PyErr_BadInternalCall();
14652 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014653 }
Victor Stinnera47082312012-10-04 02:19:54 +020014654
14655 ctx.fmtstr = PyUnicode_FromObject(format);
14656 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014657 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014658 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14659 Py_DECREF(ctx.fmtstr);
14660 return NULL;
14661 }
14662 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14663 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14664 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14665 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014666
Victor Stinner8f674cc2013-04-17 23:02:17 +020014667 _PyUnicodeWriter_Init(&ctx.writer);
14668 ctx.writer.min_length = ctx.fmtcnt + 100;
14669 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014670
Guido van Rossumd57fd912000-03-10 22:53:23 +000014671 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014672 ctx.arglen = PyTuple_Size(args);
14673 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014674 }
14675 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014676 ctx.arglen = -1;
14677 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014678 }
Victor Stinnera47082312012-10-04 02:19:54 +020014679 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014680 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014681 ctx.dict = args;
14682 else
14683 ctx.dict = NULL;
14684 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014685
Victor Stinnera47082312012-10-04 02:19:54 +020014686 while (--ctx.fmtcnt >= 0) {
14687 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014688 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014689
14690 nonfmtpos = ctx.fmtpos++;
14691 while (ctx.fmtcnt >= 0 &&
14692 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14693 ctx.fmtpos++;
14694 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014695 }
Victor Stinnera47082312012-10-04 02:19:54 +020014696 if (ctx.fmtcnt < 0) {
14697 ctx.fmtpos--;
14698 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014699 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014700
Victor Stinnercfc4c132013-04-03 01:48:39 +020014701 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14702 nonfmtpos, ctx.fmtpos) < 0)
14703 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014704 }
14705 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014706 ctx.fmtpos++;
14707 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014708 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014709 }
14710 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014711
Victor Stinnera47082312012-10-04 02:19:54 +020014712 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014713 PyErr_SetString(PyExc_TypeError,
14714 "not all arguments converted during string formatting");
14715 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014716 }
14717
Victor Stinnera47082312012-10-04 02:19:54 +020014718 if (ctx.args_owned) {
14719 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014720 }
Victor Stinnera47082312012-10-04 02:19:54 +020014721 Py_DECREF(ctx.fmtstr);
14722 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014723
Benjamin Peterson29060642009-01-31 22:14:21 +000014724 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014725 Py_DECREF(ctx.fmtstr);
14726 _PyUnicodeWriter_Dealloc(&ctx.writer);
14727 if (ctx.args_owned) {
14728 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014729 }
14730 return NULL;
14731}
14732
Jeremy Hylton938ace62002-07-17 16:30:39 +000014733static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014734unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14735
Tim Peters6d6c1a32001-08-02 04:15:00 +000014736static PyObject *
14737unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14738{
Benjamin Peterson29060642009-01-31 22:14:21 +000014739 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014740 static char *kwlist[] = {"object", "encoding", "errors", 0};
14741 char *encoding = NULL;
14742 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014743
Benjamin Peterson14339b62009-01-31 16:36:08 +000014744 if (type != &PyUnicode_Type)
14745 return unicode_subtype_new(type, args, kwds);
14746 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014747 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014748 return NULL;
14749 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014750 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014751 if (encoding == NULL && errors == NULL)
14752 return PyObject_Str(x);
14753 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014754 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014755}
14756
Guido van Rossume023fe02001-08-30 03:12:59 +000014757static PyObject *
14758unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14759{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014760 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014761 Py_ssize_t length, char_size;
14762 int share_wstr, share_utf8;
14763 unsigned int kind;
14764 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014765
Benjamin Peterson14339b62009-01-31 16:36:08 +000014766 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014767
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014768 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014769 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014770 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014771 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014772 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014773 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014774 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014775 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014776
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014777 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014778 if (self == NULL) {
14779 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014780 return NULL;
14781 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014782 kind = PyUnicode_KIND(unicode);
14783 length = PyUnicode_GET_LENGTH(unicode);
14784
14785 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014786#ifdef Py_DEBUG
14787 _PyUnicode_HASH(self) = -1;
14788#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014789 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014790#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014791 _PyUnicode_STATE(self).interned = 0;
14792 _PyUnicode_STATE(self).kind = kind;
14793 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014794 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014795 _PyUnicode_STATE(self).ready = 1;
14796 _PyUnicode_WSTR(self) = NULL;
14797 _PyUnicode_UTF8_LENGTH(self) = 0;
14798 _PyUnicode_UTF8(self) = NULL;
14799 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014800 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014801
14802 share_utf8 = 0;
14803 share_wstr = 0;
14804 if (kind == PyUnicode_1BYTE_KIND) {
14805 char_size = 1;
14806 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14807 share_utf8 = 1;
14808 }
14809 else if (kind == PyUnicode_2BYTE_KIND) {
14810 char_size = 2;
14811 if (sizeof(wchar_t) == 2)
14812 share_wstr = 1;
14813 }
14814 else {
14815 assert(kind == PyUnicode_4BYTE_KIND);
14816 char_size = 4;
14817 if (sizeof(wchar_t) == 4)
14818 share_wstr = 1;
14819 }
14820
14821 /* Ensure we won't overflow the length. */
14822 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14823 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014824 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014825 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014826 data = PyObject_MALLOC((length + 1) * char_size);
14827 if (data == NULL) {
14828 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014829 goto onError;
14830 }
14831
Victor Stinnerc3c74152011-10-02 20:39:55 +020014832 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014833 if (share_utf8) {
14834 _PyUnicode_UTF8_LENGTH(self) = length;
14835 _PyUnicode_UTF8(self) = data;
14836 }
14837 if (share_wstr) {
14838 _PyUnicode_WSTR_LENGTH(self) = length;
14839 _PyUnicode_WSTR(self) = (wchar_t *)data;
14840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014841
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014842 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014843 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014844 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014845#ifdef Py_DEBUG
14846 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14847#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014848 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014849 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014850
14851onError:
14852 Py_DECREF(unicode);
14853 Py_DECREF(self);
14854 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014855}
14856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014857PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014858"str(object='') -> str\n\
14859str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014860\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014861Create a new string object from the given object. If encoding or\n\
14862errors is specified, then the object must expose a data buffer\n\
14863that will be decoded using the given encoding and error handler.\n\
14864Otherwise, returns the result of object.__str__() (if defined)\n\
14865or repr(object).\n\
14866encoding defaults to sys.getdefaultencoding().\n\
14867errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014868
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014869static PyObject *unicode_iter(PyObject *seq);
14870
Guido van Rossumd57fd912000-03-10 22:53:23 +000014871PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014872 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014873 "str", /* tp_name */
14874 sizeof(PyUnicodeObject), /* tp_size */
14875 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014876 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014877 (destructor)unicode_dealloc, /* tp_dealloc */
14878 0, /* tp_print */
14879 0, /* tp_getattr */
14880 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014881 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014882 unicode_repr, /* tp_repr */
14883 &unicode_as_number, /* tp_as_number */
14884 &unicode_as_sequence, /* tp_as_sequence */
14885 &unicode_as_mapping, /* tp_as_mapping */
14886 (hashfunc) unicode_hash, /* tp_hash*/
14887 0, /* tp_call*/
14888 (reprfunc) unicode_str, /* tp_str */
14889 PyObject_GenericGetAttr, /* tp_getattro */
14890 0, /* tp_setattro */
14891 0, /* tp_as_buffer */
14892 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014893 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014894 unicode_doc, /* tp_doc */
14895 0, /* tp_traverse */
14896 0, /* tp_clear */
14897 PyUnicode_RichCompare, /* tp_richcompare */
14898 0, /* tp_weaklistoffset */
14899 unicode_iter, /* tp_iter */
14900 0, /* tp_iternext */
14901 unicode_methods, /* tp_methods */
14902 0, /* tp_members */
14903 0, /* tp_getset */
14904 &PyBaseObject_Type, /* tp_base */
14905 0, /* tp_dict */
14906 0, /* tp_descr_get */
14907 0, /* tp_descr_set */
14908 0, /* tp_dictoffset */
14909 0, /* tp_init */
14910 0, /* tp_alloc */
14911 unicode_new, /* tp_new */
14912 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014913};
14914
14915/* Initialize the Unicode implementation */
14916
Victor Stinner3a50e702011-10-18 21:21:00 +020014917int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014918{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014919 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014920 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014921 0x000A, /* LINE FEED */
14922 0x000D, /* CARRIAGE RETURN */
14923 0x001C, /* FILE SEPARATOR */
14924 0x001D, /* GROUP SEPARATOR */
14925 0x001E, /* RECORD SEPARATOR */
14926 0x0085, /* NEXT LINE */
14927 0x2028, /* LINE SEPARATOR */
14928 0x2029, /* PARAGRAPH SEPARATOR */
14929 };
14930
Fred Drakee4315f52000-05-09 19:53:39 +000014931 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014932 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014933 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014934 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014935 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014936
Guido van Rossumcacfc072002-05-24 19:01:59 +000014937 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014938 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014939
14940 /* initialize the linebreak bloom filter */
14941 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014942 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014943 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014944
Christian Heimes26532f72013-07-20 14:57:16 +020014945 if (PyType_Ready(&EncodingMapType) < 0)
14946 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014947
Benjamin Petersonc4311282012-10-30 23:21:10 -040014948 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14949 Py_FatalError("Can't initialize field name iterator type");
14950
14951 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14952 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014953
Victor Stinner3a50e702011-10-18 21:21:00 +020014954 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014955}
14956
14957/* Finalize the Unicode implementation */
14958
Christian Heimesa156e092008-02-16 07:38:31 +000014959int
14960PyUnicode_ClearFreeList(void)
14961{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014962 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014963}
14964
Guido van Rossumd57fd912000-03-10 22:53:23 +000014965void
Thomas Wouters78890102000-07-22 19:25:51 +000014966_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014967{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014968 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014969
Serhiy Storchaka05997252013-01-26 12:14:02 +020014970 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014971
Serhiy Storchaka05997252013-01-26 12:14:02 +020014972 for (i = 0; i < 256; i++)
14973 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014974 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014975 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014976}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014977
Walter Dörwald16807132007-05-25 13:52:07 +000014978void
14979PyUnicode_InternInPlace(PyObject **p)
14980{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014981 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014982 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014983#ifdef Py_DEBUG
14984 assert(s != NULL);
14985 assert(_PyUnicode_CHECK(s));
14986#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014987 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014988 return;
14989#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014990 /* If it's a subclass, we don't really know what putting
14991 it in the interned dict might do. */
14992 if (!PyUnicode_CheckExact(s))
14993 return;
14994 if (PyUnicode_CHECK_INTERNED(s))
14995 return;
14996 if (interned == NULL) {
14997 interned = PyDict_New();
14998 if (interned == NULL) {
14999 PyErr_Clear(); /* Don't leave an exception */
15000 return;
15001 }
15002 }
15003 /* It might be that the GetItem call fails even
15004 though the key is present in the dictionary,
15005 namely when this happens during a stack overflow. */
15006 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015007 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015008 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015009
Victor Stinnerf0335102013-04-14 19:13:03 +020015010 if (t) {
15011 Py_INCREF(t);
15012 Py_DECREF(*p);
15013 *p = t;
15014 return;
15015 }
Walter Dörwald16807132007-05-25 13:52:07 +000015016
Benjamin Peterson14339b62009-01-31 16:36:08 +000015017 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015018 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015019 PyErr_Clear();
15020 PyThreadState_GET()->recursion_critical = 0;
15021 return;
15022 }
15023 PyThreadState_GET()->recursion_critical = 0;
15024 /* The two references in interned are not counted by refcnt.
15025 The deallocator will take care of this */
15026 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015027 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015028}
15029
15030void
15031PyUnicode_InternImmortal(PyObject **p)
15032{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015033 PyUnicode_InternInPlace(p);
15034 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015035 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 Py_INCREF(*p);
15037 }
Walter Dörwald16807132007-05-25 13:52:07 +000015038}
15039
15040PyObject *
15041PyUnicode_InternFromString(const char *cp)
15042{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015043 PyObject *s = PyUnicode_FromString(cp);
15044 if (s == NULL)
15045 return NULL;
15046 PyUnicode_InternInPlace(&s);
15047 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015048}
15049
Alexander Belopolsky40018472011-02-26 01:02:56 +000015050void
15051_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015052{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015053 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015054 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015055 Py_ssize_t i, n;
15056 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015057
Benjamin Peterson14339b62009-01-31 16:36:08 +000015058 if (interned == NULL || !PyDict_Check(interned))
15059 return;
15060 keys = PyDict_Keys(interned);
15061 if (keys == NULL || !PyList_Check(keys)) {
15062 PyErr_Clear();
15063 return;
15064 }
Walter Dörwald16807132007-05-25 13:52:07 +000015065
Benjamin Peterson14339b62009-01-31 16:36:08 +000015066 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15067 detector, interned unicode strings are not forcibly deallocated;
15068 rather, we give them their stolen references back, and then clear
15069 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015070
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 n = PyList_GET_SIZE(keys);
15072 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015073 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015074 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015075 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015076 if (PyUnicode_READY(s) == -1) {
15077 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015078 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015080 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015081 case SSTATE_NOT_INTERNED:
15082 /* XXX Shouldn't happen */
15083 break;
15084 case SSTATE_INTERNED_IMMORTAL:
15085 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015086 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 break;
15088 case SSTATE_INTERNED_MORTAL:
15089 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015090 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015091 break;
15092 default:
15093 Py_FatalError("Inconsistent interned string state.");
15094 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015095 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015096 }
15097 fprintf(stderr, "total size of all interned strings: "
15098 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15099 "mortal/immortal\n", mortal_size, immortal_size);
15100 Py_DECREF(keys);
15101 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015102 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015103}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015104
15105
15106/********************* Unicode Iterator **************************/
15107
15108typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015109 PyObject_HEAD
15110 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015111 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015112} unicodeiterobject;
15113
15114static void
15115unicodeiter_dealloc(unicodeiterobject *it)
15116{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015117 _PyObject_GC_UNTRACK(it);
15118 Py_XDECREF(it->it_seq);
15119 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015120}
15121
15122static int
15123unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15124{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015125 Py_VISIT(it->it_seq);
15126 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015127}
15128
15129static PyObject *
15130unicodeiter_next(unicodeiterobject *it)
15131{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015132 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015133
Benjamin Peterson14339b62009-01-31 16:36:08 +000015134 assert(it != NULL);
15135 seq = it->it_seq;
15136 if (seq == NULL)
15137 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015138 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015140 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15141 int kind = PyUnicode_KIND(seq);
15142 void *data = PyUnicode_DATA(seq);
15143 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15144 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 if (item != NULL)
15146 ++it->it_index;
15147 return item;
15148 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015149
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 Py_DECREF(seq);
15151 it->it_seq = NULL;
15152 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015153}
15154
15155static PyObject *
15156unicodeiter_len(unicodeiterobject *it)
15157{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015158 Py_ssize_t len = 0;
15159 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015160 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015162}
15163
15164PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15165
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015166static PyObject *
15167unicodeiter_reduce(unicodeiterobject *it)
15168{
15169 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015170 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015171 it->it_seq, it->it_index);
15172 } else {
15173 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15174 if (u == NULL)
15175 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015176 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015177 }
15178}
15179
15180PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15181
15182static PyObject *
15183unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15184{
15185 Py_ssize_t index = PyLong_AsSsize_t(state);
15186 if (index == -1 && PyErr_Occurred())
15187 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015188 if (it->it_seq != NULL) {
15189 if (index < 0)
15190 index = 0;
15191 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15192 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15193 it->it_index = index;
15194 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015195 Py_RETURN_NONE;
15196}
15197
15198PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15199
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015200static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015201 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015202 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015203 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15204 reduce_doc},
15205 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15206 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015208};
15209
15210PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015211 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15212 "str_iterator", /* tp_name */
15213 sizeof(unicodeiterobject), /* tp_basicsize */
15214 0, /* tp_itemsize */
15215 /* methods */
15216 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15217 0, /* tp_print */
15218 0, /* tp_getattr */
15219 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015220 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015221 0, /* tp_repr */
15222 0, /* tp_as_number */
15223 0, /* tp_as_sequence */
15224 0, /* tp_as_mapping */
15225 0, /* tp_hash */
15226 0, /* tp_call */
15227 0, /* tp_str */
15228 PyObject_GenericGetAttr, /* tp_getattro */
15229 0, /* tp_setattro */
15230 0, /* tp_as_buffer */
15231 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15232 0, /* tp_doc */
15233 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15234 0, /* tp_clear */
15235 0, /* tp_richcompare */
15236 0, /* tp_weaklistoffset */
15237 PyObject_SelfIter, /* tp_iter */
15238 (iternextfunc)unicodeiter_next, /* tp_iternext */
15239 unicodeiter_methods, /* tp_methods */
15240 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015241};
15242
15243static PyObject *
15244unicode_iter(PyObject *seq)
15245{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015247
Benjamin Peterson14339b62009-01-31 16:36:08 +000015248 if (!PyUnicode_Check(seq)) {
15249 PyErr_BadInternalCall();
15250 return NULL;
15251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015252 if (PyUnicode_READY(seq) == -1)
15253 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015254 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15255 if (it == NULL)
15256 return NULL;
15257 it->it_index = 0;
15258 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015259 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015260 _PyObject_GC_TRACK(it);
15261 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015262}
15263
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015264
15265size_t
15266Py_UNICODE_strlen(const Py_UNICODE *u)
15267{
15268 int res = 0;
15269 while(*u++)
15270 res++;
15271 return res;
15272}
15273
15274Py_UNICODE*
15275Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15276{
15277 Py_UNICODE *u = s1;
15278 while ((*u++ = *s2++));
15279 return s1;
15280}
15281
15282Py_UNICODE*
15283Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15284{
15285 Py_UNICODE *u = s1;
15286 while ((*u++ = *s2++))
15287 if (n-- == 0)
15288 break;
15289 return s1;
15290}
15291
15292Py_UNICODE*
15293Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15294{
15295 Py_UNICODE *u1 = s1;
15296 u1 += Py_UNICODE_strlen(u1);
15297 Py_UNICODE_strcpy(u1, s2);
15298 return s1;
15299}
15300
15301int
15302Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15303{
15304 while (*s1 && *s2 && *s1 == *s2)
15305 s1++, s2++;
15306 if (*s1 && *s2)
15307 return (*s1 < *s2) ? -1 : +1;
15308 if (*s1)
15309 return 1;
15310 if (*s2)
15311 return -1;
15312 return 0;
15313}
15314
15315int
15316Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15317{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015318 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015319 for (; n != 0; n--) {
15320 u1 = *s1;
15321 u2 = *s2;
15322 if (u1 != u2)
15323 return (u1 < u2) ? -1 : +1;
15324 if (u1 == '\0')
15325 return 0;
15326 s1++;
15327 s2++;
15328 }
15329 return 0;
15330}
15331
15332Py_UNICODE*
15333Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15334{
15335 const Py_UNICODE *p;
15336 for (p = s; *p; p++)
15337 if (*p == c)
15338 return (Py_UNICODE*)p;
15339 return NULL;
15340}
15341
15342Py_UNICODE*
15343Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15344{
15345 const Py_UNICODE *p;
15346 p = s + Py_UNICODE_strlen(s);
15347 while (p != s) {
15348 p--;
15349 if (*p == c)
15350 return (Py_UNICODE*)p;
15351 }
15352 return NULL;
15353}
Victor Stinner331ea922010-08-10 16:37:20 +000015354
Victor Stinner71133ff2010-09-01 23:43:53 +000015355Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015356PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015357{
Victor Stinner577db2c2011-10-11 22:12:48 +020015358 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015359 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015361 if (!PyUnicode_Check(unicode)) {
15362 PyErr_BadArgument();
15363 return NULL;
15364 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015365 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015366 if (u == NULL)
15367 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015368 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015369 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015370 PyErr_NoMemory();
15371 return NULL;
15372 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015373 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015374 size *= sizeof(Py_UNICODE);
15375 copy = PyMem_Malloc(size);
15376 if (copy == NULL) {
15377 PyErr_NoMemory();
15378 return NULL;
15379 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015380 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015381 return copy;
15382}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015383
Georg Brandl66c221e2010-10-14 07:04:07 +000015384/* A _string module, to export formatter_parser and formatter_field_name_split
15385 to the string.Formatter class implemented in Python. */
15386
15387static PyMethodDef _string_methods[] = {
15388 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15389 METH_O, PyDoc_STR("split the argument as a field name")},
15390 {"formatter_parser", (PyCFunction) formatter_parser,
15391 METH_O, PyDoc_STR("parse the argument as a format string")},
15392 {NULL, NULL}
15393};
15394
15395static struct PyModuleDef _string_module = {
15396 PyModuleDef_HEAD_INIT,
15397 "_string",
15398 PyDoc_STR("string helper module"),
15399 0,
15400 _string_methods,
15401 NULL,
15402 NULL,
15403 NULL,
15404 NULL
15405};
15406
15407PyMODINIT_FUNC
15408PyInit__string(void)
15409{
15410 return PyModule_Create(&_string_module);
15411}
15412
15413
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015414#ifdef __cplusplus
15415}
15416#endif