blob: d9c131cff9f87c120b3dd1a02fe5b1a17d7718d9 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Larry Hastings61272b72014-01-07 12:41:53 -080050/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080051class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080052[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080053/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080054
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055/* --- Globals ------------------------------------------------------------
56
Serhiy Storchaka05997252013-01-26 12:14:02 +020057NOTE: In the interpreter's initialization phase, some globals are currently
58 initialized dynamically as needed. In the process Unicode objects may
59 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000060
61*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64#ifdef __cplusplus
65extern "C" {
66#endif
67
Victor Stinner8faf8212011-12-08 22:14:11 +010068/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
69#define MAX_UNICODE 0x10ffff
70
Victor Stinner910337b2011-10-03 03:20:16 +020071#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020072# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020073#else
74# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
75#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020076
Victor Stinnere90fe6a2011-10-01 16:48:13 +020077#define _PyUnicode_UTF8(op) \
78 (((PyCompactUnicodeObject*)(op))->utf8)
79#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020080 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 assert(PyUnicode_IS_READY(op)), \
82 PyUnicode_IS_COMPACT_ASCII(op) ? \
83 ((char*)((PyASCIIObject*)(op) + 1)) : \
84 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020085#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020086 (((PyCompactUnicodeObject*)(op))->utf8_length)
87#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020088 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 assert(PyUnicode_IS_READY(op)), \
90 PyUnicode_IS_COMPACT_ASCII(op) ? \
91 ((PyASCIIObject*)(op))->length : \
92 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020093#define _PyUnicode_WSTR(op) \
94 (((PyASCIIObject*)(op))->wstr)
95#define _PyUnicode_WSTR_LENGTH(op) \
96 (((PyCompactUnicodeObject*)(op))->wstr_length)
97#define _PyUnicode_LENGTH(op) \
98 (((PyASCIIObject *)(op))->length)
99#define _PyUnicode_STATE(op) \
100 (((PyASCIIObject *)(op))->state)
101#define _PyUnicode_HASH(op) \
102 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200103#define _PyUnicode_KIND(op) \
104 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200105 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_GET_LENGTH(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_DATA_ANY(op) \
110 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200130 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200131 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200132 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
133
Victor Stinner03490912011-10-03 23:45:12 +0200134/* true if the Unicode object has an allocated wstr memory block
135 (not shared with other data) */
136#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200137 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100148 to_type *_to = (to_type *)(to); \
149 const from_type *_iter = (from_type *)(begin); \
150 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200153 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Walter Dörwald16807132007-05-25 13:52:07 +0000165/* This dictionary holds all interned unicode strings. Note that references
166 to strings in this dictionary are *not* counted in the string's ob_refcnt.
167 When the interned string reaches a refcnt of 0 the string deallocation
168 function will delete the reference from this dictionary.
169
170 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000171 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000172*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200173static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000174
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000175/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200176static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200177
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179 do { \
180 if (unicode_empty != NULL) \
181 Py_INCREF(unicode_empty); \
182 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183 unicode_empty = PyUnicode_New(0, 0); \
184 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200185 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
187 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191#define _Py_RETURN_UNICODE_EMPTY() \
192 do { \
193 _Py_INCREF_UNICODE_EMPTY(); \
194 return unicode_empty; \
195 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200197/* Forward declaration */
198Py_LOCAL_INLINE(int)
199_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
200
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200206static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100242static int unicode_modifiable(PyObject *unicode);
243
Victor Stinnerfe226c02011-10-03 03:52:20 +0200244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100246_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200247static PyObject *
248_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
249static PyObject *
250_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
251
252static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100255 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
257
Alexander Belopolsky40018472011-02-26 01:02:56 +0000258static void
259raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300260 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100261 PyObject *unicode,
262 Py_ssize_t startpos, Py_ssize_t endpos,
263 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Same for linebreaks */
266static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000268/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* 0x000B, * LINE TABULATION */
270/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x001C, * FILE SEPARATOR */
275/* 0x001D, * GROUP SEPARATOR */
276/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 1, 1, 1, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000282
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000291};
292
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300293/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
294 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000296PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000298#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 /* This is actually an illegal character, so it should
302 not be passed to unichr. */
303 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000304#endif
305}
306
Victor Stinner910337b2011-10-03 03:20:16 +0200307#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200308int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100309_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200310{
311 PyASCIIObject *ascii;
312 unsigned int kind;
313
314 assert(PyUnicode_Check(op));
315
316 ascii = (PyASCIIObject *)op;
317 kind = ascii->state.kind;
318
Victor Stinnera3b334d2011-10-03 13:53:37 +0200319 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200325 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200326
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 if (ascii->state.compact == 1) {
328 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(kind == PyUnicode_1BYTE_KIND
330 || kind == PyUnicode_2BYTE_KIND
331 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200333 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100335 }
336 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
338
339 data = unicode->data.any;
340 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->length == 0);
342 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100346 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200347 assert(ascii->wstr != NULL);
348 assert(data == NULL);
349 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200391 void *data;
392 Py_UCS4 ch;
393
394 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 for (i=0; i < ascii->length; i++)
396 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 if (ch > maxchar)
399 maxchar = ch;
400 }
401 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100402 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 255);
405 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 else
407 assert(maxchar < 128);
408 }
Victor Stinner77faf692011-11-20 18:56:05 +0100409 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 assert(maxchar <= 0xFFFF);
412 }
413 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200414 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100415 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100416 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200417 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200418 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100423static PyObject*
424unicode_result_wchar(PyObject *unicode)
425{
426#ifndef Py_DEBUG
427 Py_ssize_t len;
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 len = _PyUnicode_WSTR_LENGTH(unicode);
430 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200432 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 }
434
435 if (len == 1) {
436 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100437 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
439 Py_DECREF(unicode);
440 return latin1_char;
441 }
442 }
443
444 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200445 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 return NULL;
447 }
448#else
Victor Stinneraa771272012-10-04 02:32:58 +0200449 assert(Py_REFCNT(unicode) == 1);
450
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100451 /* don't make the result ready in debug mode to ensure that the caller
452 makes the string ready before using it */
453 assert(_PyUnicode_CheckConsistency(unicode, 1));
454#endif
455 return unicode;
456}
457
458static PyObject*
459unicode_result_ready(PyObject *unicode)
460{
461 Py_ssize_t length;
462
463 length = PyUnicode_GET_LENGTH(unicode);
464 if (length == 0) {
465 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200467 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 }
469 return unicode_empty;
470 }
471
472 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200473 void *data = PyUnicode_DATA(unicode);
474 int kind = PyUnicode_KIND(unicode);
475 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 if (ch < 256) {
477 PyObject *latin1_char = unicode_latin1[ch];
478 if (latin1_char != NULL) {
479 if (unicode != latin1_char) {
480 Py_INCREF(latin1_char);
481 Py_DECREF(unicode);
482 }
483 return latin1_char;
484 }
485 else {
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 Py_INCREF(unicode);
488 unicode_latin1[ch] = unicode;
489 return unicode;
490 }
491 }
492 }
493
494 assert(_PyUnicode_CheckConsistency(unicode, 1));
495 return unicode;
496}
497
498static PyObject*
499unicode_result(PyObject *unicode)
500{
501 assert(_PyUnicode_CHECK(unicode));
502 if (PyUnicode_IS_READY(unicode))
503 return unicode_result_ready(unicode);
504 else
505 return unicode_result_wchar(unicode);
506}
507
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508static PyObject*
509unicode_result_unchanged(PyObject *unicode)
510{
511 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500512 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100513 return NULL;
514 Py_INCREF(unicode);
515 return unicode;
516 }
517 else
518 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100519 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100520}
521
Victor Stinner3a50e702011-10-18 21:21:00 +0200522#ifdef HAVE_MBCS
523static OSVERSIONINFOEX winver;
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526/* --- Bloom Filters ----------------------------------------------------- */
527
528/* stuff to implement simple "bloom filters" for Unicode characters.
529 to keep things simple, we use a single bitmask, using the least 5
530 bits from each unicode characters as the bit index. */
531
532/* the linebreak mask is set up by Unicode_Init below */
533
Antoine Pitrouf068f942010-01-13 14:19:12 +0000534#if LONG_BIT >= 128
535#define BLOOM_WIDTH 128
536#elif LONG_BIT >= 64
537#define BLOOM_WIDTH 64
538#elif LONG_BIT >= 32
539#define BLOOM_WIDTH 32
540#else
541#error "LONG_BIT is smaller than 32"
542#endif
543
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544#define BLOOM_MASK unsigned long
545
Serhiy Storchaka05997252013-01-26 12:14:02 +0200546static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Antoine Pitrouf068f942010-01-13 14:19:12 +0000548#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Benjamin Peterson29060642009-01-31 22:14:21 +0000550#define BLOOM_LINEBREAK(ch) \
551 ((ch) < 128U ? ascii_linebreak[(ch)] : \
552 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
Alexander Belopolsky40018472011-02-26 01:02:56 +0000554Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556{
Victor Stinnera85af502013-04-09 21:53:54 +0200557#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
558 do { \
559 TYPE *data = (TYPE *)PTR; \
560 TYPE *end = data + LEN; \
561 Py_UCS4 ch; \
562 for (; data != end; data++) { \
563 ch = *data; \
564 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
565 } \
566 break; \
567 } while (0)
568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 /* calculate simple bloom-style bitmask for a given unicode string */
570
Antoine Pitrouf068f942010-01-13 14:19:12 +0000571 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200574 switch (kind) {
575 case PyUnicode_1BYTE_KIND:
576 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
577 break;
578 case PyUnicode_2BYTE_KIND:
579 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
580 break;
581 case PyUnicode_4BYTE_KIND:
582 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
583 break;
584 default:
585 assert(0);
586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200588
589#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590}
591
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200592/* Compilation of templated routines */
593
594#include "stringlib/asciilib.h"
595#include "stringlib/fastsearch.h"
596#include "stringlib/partition.h"
597#include "stringlib/split.h"
598#include "stringlib/count.h"
599#include "stringlib/find.h"
600#include "stringlib/find_max_char.h"
601#include "stringlib/localeutil.h"
602#include "stringlib/undef.h"
603
604#include "stringlib/ucs1lib.h"
605#include "stringlib/fastsearch.h"
606#include "stringlib/partition.h"
607#include "stringlib/split.h"
608#include "stringlib/count.h"
609#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300610#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200611#include "stringlib/find_max_char.h"
612#include "stringlib/localeutil.h"
613#include "stringlib/undef.h"
614
615#include "stringlib/ucs2lib.h"
616#include "stringlib/fastsearch.h"
617#include "stringlib/partition.h"
618#include "stringlib/split.h"
619#include "stringlib/count.h"
620#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300621#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200622#include "stringlib/find_max_char.h"
623#include "stringlib/localeutil.h"
624#include "stringlib/undef.h"
625
626#include "stringlib/ucs4lib.h"
627#include "stringlib/fastsearch.h"
628#include "stringlib/partition.h"
629#include "stringlib/split.h"
630#include "stringlib/count.h"
631#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300632#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200633#include "stringlib/find_max_char.h"
634#include "stringlib/localeutil.h"
635#include "stringlib/undef.h"
636
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637#include "stringlib/unicodedefs.h"
638#include "stringlib/fastsearch.h"
639#include "stringlib/count.h"
640#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100641#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* --- Unicode Object ----------------------------------------------------- */
644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200646fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
649 Py_ssize_t size, Py_UCS4 ch,
650 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200652 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
653
654 switch (kind) {
655 case PyUnicode_1BYTE_KIND:
656 {
657 Py_UCS1 ch1 = (Py_UCS1) ch;
658 if (ch1 == ch)
659 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
660 else
661 return -1;
662 }
663 case PyUnicode_2BYTE_KIND:
664 {
665 Py_UCS2 ch2 = (Py_UCS2) ch;
666 if (ch2 == ch)
667 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
668 else
669 return -1;
670 }
671 case PyUnicode_4BYTE_KIND:
672 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
673 default:
674 assert(0);
675 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677}
678
Victor Stinnerafffce42012-10-03 23:03:17 +0200679#ifdef Py_DEBUG
680/* Fill the data of an Unicode string with invalid characters to detect bugs
681 earlier.
682
683 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
684 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
685 invalid character in Unicode 6.0. */
686static void
687unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
688{
689 int kind = PyUnicode_KIND(unicode);
690 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
691 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
692 if (length <= old_length)
693 return;
694 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
695}
696#endif
697
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698static PyObject*
699resize_compact(PyObject *unicode, Py_ssize_t length)
700{
701 Py_ssize_t char_size;
702 Py_ssize_t struct_size;
703 Py_ssize_t new_size;
704 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100705 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200706#ifdef Py_DEBUG
707 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
708#endif
709
Victor Stinner79891572012-05-03 13:43:07 +0200710 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100712 assert(PyUnicode_IS_COMPACT(unicode));
713
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200714 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100715 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 struct_size = sizeof(PyASCIIObject);
717 else
718 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200719 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
722 PyErr_NoMemory();
723 return NULL;
724 }
725 new_size = (struct_size + (length + 1) * char_size);
726
Victor Stinner84def372011-12-11 20:04:56 +0100727 _Py_DEC_REFTOTAL;
728 _Py_ForgetReference(unicode);
729
730 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
731 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100732 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733 PyErr_NoMemory();
734 return NULL;
735 }
Victor Stinner84def372011-12-11 20:04:56 +0100736 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100738
Victor Stinnerfe226c02011-10-03 03:52:20 +0200739 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200740 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100742 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200743 _PyUnicode_WSTR_LENGTH(unicode) = length;
744 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100745 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
746 PyObject_DEL(_PyUnicode_WSTR(unicode));
747 _PyUnicode_WSTR(unicode) = NULL;
748 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200749#ifdef Py_DEBUG
750 unicode_fill_invalid(unicode, old_length);
751#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200752 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
753 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200754 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200755 return unicode;
756}
757
Alexander Belopolsky40018472011-02-26 01:02:56 +0000758static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200759resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000760{
Victor Stinner95663112011-10-04 01:03:50 +0200761 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100762 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000765
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 if (PyUnicode_IS_READY(unicode)) {
767 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200768 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200770#ifdef Py_DEBUG
771 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
772#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773
774 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200775 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200776 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
777 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200778
779 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
780 PyErr_NoMemory();
781 return -1;
782 }
783 new_size = (length + 1) * char_size;
784
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
786 {
787 PyObject_DEL(_PyUnicode_UTF8(unicode));
788 _PyUnicode_UTF8(unicode) = NULL;
789 _PyUnicode_UTF8_LENGTH(unicode) = 0;
790 }
791
Victor Stinnerfe226c02011-10-03 03:52:20 +0200792 data = (PyObject *)PyObject_REALLOC(data, new_size);
793 if (data == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200798 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200799 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 _PyUnicode_WSTR_LENGTH(unicode) = length;
801 }
802 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200803 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200804 _PyUnicode_UTF8_LENGTH(unicode) = length;
805 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806 _PyUnicode_LENGTH(unicode) = length;
807 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200808#ifdef Py_DEBUG
809 unicode_fill_invalid(unicode, old_length);
810#endif
Victor Stinner95663112011-10-04 01:03:50 +0200811 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200812 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200814 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200815 }
Victor Stinner95663112011-10-04 01:03:50 +0200816 assert(_PyUnicode_WSTR(unicode) != NULL);
817
818 /* check for integer overflow */
819 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
820 PyErr_NoMemory();
821 return -1;
822 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100823 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200824 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100825 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200826 if (!wstr) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 _PyUnicode_WSTR(unicode) = wstr;
831 _PyUnicode_WSTR(unicode)[length] = 0;
832 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200833 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000834 return 0;
835}
836
Victor Stinnerfe226c02011-10-03 03:52:20 +0200837static PyObject*
838resize_copy(PyObject *unicode, Py_ssize_t length)
839{
840 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100841 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100843
Benjamin Petersonbac79492012-01-14 13:34:47 -0500844 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100845 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200846
847 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
848 if (copy == NULL)
849 return NULL;
850
851 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200852 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200853 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200854 }
855 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200856 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100857
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200858 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200859 if (w == NULL)
860 return NULL;
861 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
862 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200863 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
864 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200865 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200866 }
867}
868
Guido van Rossumd57fd912000-03-10 22:53:23 +0000869/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000870 Ux0000 terminated; some code (e.g. new_identifier)
871 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000872
873 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000874 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875
876*/
877
Alexander Belopolsky40018472011-02-26 01:02:56 +0000878static PyUnicodeObject *
879_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200881 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200882 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885 if (length == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888 }
889
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000890 /* Ensure we won't overflow the size. */
891 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
892 return (PyUnicodeObject *)PyErr_NoMemory();
893 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894 if (length < 0) {
895 PyErr_SetString(PyExc_SystemError,
896 "Negative size passed to _PyUnicode_New");
897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000898 }
899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
901 if (unicode == NULL)
902 return NULL;
903 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100904
905 _PyUnicode_WSTR_LENGTH(unicode) = length;
906 _PyUnicode_HASH(unicode) = -1;
907 _PyUnicode_STATE(unicode).interned = 0;
908 _PyUnicode_STATE(unicode).kind = 0;
909 _PyUnicode_STATE(unicode).compact = 0;
910 _PyUnicode_STATE(unicode).ready = 0;
911 _PyUnicode_STATE(unicode).ascii = 0;
912 _PyUnicode_DATA_ANY(unicode) = NULL;
913 _PyUnicode_LENGTH(unicode) = 0;
914 _PyUnicode_UTF8(unicode) = NULL;
915 _PyUnicode_UTF8_LENGTH(unicode) = 0;
916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
918 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100919 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000920 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100921 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000922 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
Jeremy Hyltond8082792003-09-16 19:41:39 +0000924 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000925 * the caller fails before initializing str -- unicode_resize()
926 * reads str[0], and the Keep-Alive optimization can keep memory
927 * allocated for str alive across a call to unicode_dealloc(unicode).
928 * We don't want unicode_resize to read uninitialized memory in
929 * that case.
930 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 _PyUnicode_WSTR(unicode)[0] = 0;
932 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100933
Victor Stinner7931d9a2011-11-04 00:22:48 +0100934 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000935 return unicode;
936}
937
Victor Stinnerf42dc442011-10-02 23:33:16 +0200938static const char*
939unicode_kind_name(PyObject *unicode)
940{
Victor Stinner42dfd712011-10-03 14:41:45 +0200941 /* don't check consistency: unicode_kind_name() is called from
942 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 if (!PyUnicode_IS_COMPACT(unicode))
944 {
945 if (!PyUnicode_IS_READY(unicode))
946 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600947 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 {
949 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200951 return "legacy ascii";
952 else
953 return "legacy latin1";
954 case PyUnicode_2BYTE_KIND:
955 return "legacy UCS2";
956 case PyUnicode_4BYTE_KIND:
957 return "legacy UCS4";
958 default:
959 return "<legacy invalid kind>";
960 }
961 }
962 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600963 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200965 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200966 return "ascii";
967 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200972 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200973 default:
974 return "<invalid compact kind>";
975 }
976}
977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979/* Functions wrapping macros for use in debugger */
980char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200981 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982}
983
984void *_PyUnicode_compact_data(void *unicode) {
985 return _PyUnicode_COMPACT_DATA(unicode);
986}
987void *_PyUnicode_data(void *unicode){
988 printf("obj %p\n", unicode);
989 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
990 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
991 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
992 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
993 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
994 return PyUnicode_DATA(unicode);
995}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200996
997void
998_PyUnicode_Dump(PyObject *op)
999{
1000 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1002 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1003 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001004
Victor Stinnera849a4b2011-10-03 12:12:11 +02001005 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 {
1007 if (ascii->state.ascii)
1008 data = (ascii + 1);
1009 else
1010 data = (compact + 1);
1011 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001012 else
1013 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001014 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1015 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001016
Victor Stinnera849a4b2011-10-03 12:12:11 +02001017 if (ascii->wstr == data)
1018 printf("shared ");
1019 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001020
Victor Stinnera3b334d2011-10-03 13:53:37 +02001021 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001022 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001023 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1024 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001025 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1026 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001027 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001028 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001029}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030#endif
1031
1032PyObject *
1033PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1034{
1035 PyObject *obj;
1036 PyCompactUnicodeObject *unicode;
1037 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001038 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001039 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 Py_ssize_t char_size;
1041 Py_ssize_t struct_size;
1042
1043 /* Optimization for empty strings */
1044 if (size == 0 && unicode_empty != NULL) {
1045 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001046 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 }
1048
Victor Stinner9e9d6892011-10-04 01:02:02 +02001049 is_ascii = 0;
1050 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051 struct_size = sizeof(PyCompactUnicodeObject);
1052 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001053 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 char_size = 1;
1055 is_ascii = 1;
1056 struct_size = sizeof(PyASCIIObject);
1057 }
1058 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001059 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 char_size = 1;
1061 }
1062 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001063 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 char_size = 2;
1065 if (sizeof(wchar_t) == 2)
1066 is_sharing = 1;
1067 }
1068 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001069 if (maxchar > MAX_UNICODE) {
1070 PyErr_SetString(PyExc_SystemError,
1071 "invalid maximum character passed to PyUnicode_New");
1072 return NULL;
1073 }
Victor Stinner8f825062012-04-27 13:55:39 +02001074 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075 char_size = 4;
1076 if (sizeof(wchar_t) == 4)
1077 is_sharing = 1;
1078 }
1079
1080 /* Ensure we won't overflow the size. */
1081 if (size < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to PyUnicode_New");
1084 return NULL;
1085 }
1086 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1087 return PyErr_NoMemory();
1088
1089 /* Duplicated allocation code from _PyObject_New() instead of a call to
1090 * PyObject_New() so we are able to allocate space for the object and
1091 * it's data buffer.
1092 */
1093 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1094 if (obj == NULL)
1095 return PyErr_NoMemory();
1096 obj = PyObject_INIT(obj, &PyUnicode_Type);
1097 if (obj == NULL)
1098 return NULL;
1099
1100 unicode = (PyCompactUnicodeObject *)obj;
1101 if (is_ascii)
1102 data = ((PyASCIIObject*)obj) + 1;
1103 else
1104 data = unicode + 1;
1105 _PyUnicode_LENGTH(unicode) = size;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001108 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109 _PyUnicode_STATE(unicode).compact = 1;
1110 _PyUnicode_STATE(unicode).ready = 1;
1111 _PyUnicode_STATE(unicode).ascii = is_ascii;
1112 if (is_ascii) {
1113 ((char*)data)[size] = 0;
1114 _PyUnicode_WSTR(unicode) = NULL;
1115 }
Victor Stinner8f825062012-04-27 13:55:39 +02001116 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 ((char*)data)[size] = 0;
1118 _PyUnicode_WSTR(unicode) = NULL;
1119 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001121 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 else {
1124 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001125 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001126 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001127 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001128 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129 ((Py_UCS4*)data)[size] = 0;
1130 if (is_sharing) {
1131 _PyUnicode_WSTR_LENGTH(unicode) = size;
1132 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1133 }
1134 else {
1135 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1136 _PyUnicode_WSTR(unicode) = NULL;
1137 }
1138 }
Victor Stinner8f825062012-04-27 13:55:39 +02001139#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001140 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001141#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001142 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 return obj;
1144}
1145
1146#if SIZEOF_WCHAR_T == 2
1147/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1148 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001149 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
1151 This function assumes that unicode can hold one more code point than wstr
1152 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001153static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001154unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001155 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
1157 const wchar_t *iter;
1158 Py_UCS4 *ucs4_out;
1159
Victor Stinner910337b2011-10-03 03:20:16 +02001160 assert(unicode != NULL);
1161 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001162 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1163 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1164
1165 for (iter = begin; iter < end; ) {
1166 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1167 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001168 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1169 && (iter+1) < end
1170 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001171 {
Victor Stinner551ac952011-11-29 22:58:13 +01001172 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 iter += 2;
1174 }
1175 else {
1176 *ucs4_out++ = *iter;
1177 iter++;
1178 }
1179 }
1180 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1181 _PyUnicode_GET_LENGTH(unicode)));
1182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001183}
1184#endif
1185
Victor Stinnercd9950f2011-10-02 00:34:53 +02001186static int
Victor Stinner488fa492011-12-12 00:01:39 +01001187unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001188{
Victor Stinner488fa492011-12-12 00:01:39 +01001189 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001190 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001191 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001192 return -1;
1193 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001194 return 0;
1195}
1196
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001197static int
1198_copy_characters(PyObject *to, Py_ssize_t to_start,
1199 PyObject *from, Py_ssize_t from_start,
1200 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001202 unsigned int from_kind, to_kind;
1203 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204
Victor Stinneree4544c2012-05-09 22:24:08 +02001205 assert(0 <= how_many);
1206 assert(0 <= from_start);
1207 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001208 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001209 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001210 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211
Victor Stinnerd3f08822012-05-29 12:57:52 +02001212 assert(PyUnicode_Check(to));
1213 assert(PyUnicode_IS_READY(to));
1214 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1215
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001216 if (how_many == 0)
1217 return 0;
1218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001222 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223
Victor Stinnerf1852262012-06-16 16:38:26 +02001224#ifdef Py_DEBUG
1225 if (!check_maxchar
1226 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1227 {
1228 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1229 Py_UCS4 ch;
1230 Py_ssize_t i;
1231 for (i=0; i < how_many; i++) {
1232 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1233 assert(ch <= to_maxchar);
1234 }
1235 }
1236#endif
1237
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001238 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001239 if (check_maxchar
1240 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1241 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001242 /* Writing Latin-1 characters into an ASCII string requires to
1243 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001244 Py_UCS4 max_char;
1245 max_char = ucs1lib_find_max_char(from_data,
1246 (Py_UCS1*)from_data + how_many);
1247 if (max_char >= 128)
1248 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001249 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001250 Py_MEMCPY((char*)to_data + to_kind * to_start,
1251 (char*)from_data + from_kind * from_start,
1252 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001253 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001254 else if (from_kind == PyUnicode_1BYTE_KIND
1255 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001256 {
1257 _PyUnicode_CONVERT_BYTES(
1258 Py_UCS1, Py_UCS2,
1259 PyUnicode_1BYTE_DATA(from) + from_start,
1260 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1261 PyUnicode_2BYTE_DATA(to) + to_start
1262 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001263 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001264 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001265 && to_kind == PyUnicode_4BYTE_KIND)
1266 {
1267 _PyUnicode_CONVERT_BYTES(
1268 Py_UCS1, Py_UCS4,
1269 PyUnicode_1BYTE_DATA(from) + from_start,
1270 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1271 PyUnicode_4BYTE_DATA(to) + to_start
1272 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001273 }
1274 else if (from_kind == PyUnicode_2BYTE_KIND
1275 && to_kind == PyUnicode_4BYTE_KIND)
1276 {
1277 _PyUnicode_CONVERT_BYTES(
1278 Py_UCS2, Py_UCS4,
1279 PyUnicode_2BYTE_DATA(from) + from_start,
1280 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1281 PyUnicode_4BYTE_DATA(to) + to_start
1282 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001283 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001284 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001285 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1286
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001287 if (!check_maxchar) {
1288 if (from_kind == PyUnicode_2BYTE_KIND
1289 && to_kind == PyUnicode_1BYTE_KIND)
1290 {
1291 _PyUnicode_CONVERT_BYTES(
1292 Py_UCS2, Py_UCS1,
1293 PyUnicode_2BYTE_DATA(from) + from_start,
1294 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1295 PyUnicode_1BYTE_DATA(to) + to_start
1296 );
1297 }
1298 else if (from_kind == PyUnicode_4BYTE_KIND
1299 && to_kind == PyUnicode_1BYTE_KIND)
1300 {
1301 _PyUnicode_CONVERT_BYTES(
1302 Py_UCS4, Py_UCS1,
1303 PyUnicode_4BYTE_DATA(from) + from_start,
1304 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1305 PyUnicode_1BYTE_DATA(to) + to_start
1306 );
1307 }
1308 else if (from_kind == PyUnicode_4BYTE_KIND
1309 && to_kind == PyUnicode_2BYTE_KIND)
1310 {
1311 _PyUnicode_CONVERT_BYTES(
1312 Py_UCS4, Py_UCS2,
1313 PyUnicode_4BYTE_DATA(from) + from_start,
1314 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1315 PyUnicode_2BYTE_DATA(to) + to_start
1316 );
1317 }
1318 else {
1319 assert(0);
1320 return -1;
1321 }
1322 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001323 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001325 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001326 Py_ssize_t i;
1327
Victor Stinnera0702ab2011-09-29 14:14:38 +02001328 for (i=0; i < how_many; i++) {
1329 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001330 if (ch > to_maxchar)
1331 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001332 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1333 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001334 }
1335 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001336 return 0;
1337}
1338
Victor Stinnerd3f08822012-05-29 12:57:52 +02001339void
1340_PyUnicode_FastCopyCharacters(
1341 PyObject *to, Py_ssize_t to_start,
1342 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001343{
1344 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1345}
1346
1347Py_ssize_t
1348PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1349 PyObject *from, Py_ssize_t from_start,
1350 Py_ssize_t how_many)
1351{
1352 int err;
1353
1354 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1355 PyErr_BadInternalCall();
1356 return -1;
1357 }
1358
Benjamin Petersonbac79492012-01-14 13:34:47 -05001359 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001360 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001361 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001362 return -1;
1363
Victor Stinnerd3f08822012-05-29 12:57:52 +02001364 if (from_start < 0) {
1365 PyErr_SetString(PyExc_IndexError, "string index out of range");
1366 return -1;
1367 }
1368 if (to_start < 0) {
1369 PyErr_SetString(PyExc_IndexError, "string index out of range");
1370 return -1;
1371 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001372 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1373 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1374 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001375 "Cannot write %zi characters at %zi "
1376 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377 how_many, to_start, PyUnicode_GET_LENGTH(to));
1378 return -1;
1379 }
1380
1381 if (how_many == 0)
1382 return 0;
1383
Victor Stinner488fa492011-12-12 00:01:39 +01001384 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385 return -1;
1386
1387 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1388 if (err) {
1389 PyErr_Format(PyExc_SystemError,
1390 "Cannot copy %s characters "
1391 "into a string of %s characters",
1392 unicode_kind_name(from),
1393 unicode_kind_name(to));
1394 return -1;
1395 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001396 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397}
1398
Victor Stinner17222162011-09-28 22:15:37 +02001399/* Find the maximum code point and count the number of surrogate pairs so a
1400 correct string length can be computed before converting a string to UCS4.
1401 This function counts single surrogates as a character and not as a pair.
1402
1403 Return 0 on success, or -1 on error. */
1404static int
1405find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1406 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407{
1408 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001409 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerc53be962011-10-02 21:33:54 +02001411 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 *num_surrogates = 0;
1413 *maxchar = 0;
1414
1415 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001417 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1418 && (iter+1) < end
1419 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1420 {
1421 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1422 ++(*num_surrogates);
1423 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 }
1425 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001427 {
1428 ch = *iter;
1429 iter++;
1430 }
1431 if (ch > *maxchar) {
1432 *maxchar = ch;
1433 if (*maxchar > MAX_UNICODE) {
1434 PyErr_Format(PyExc_ValueError,
1435 "character U+%x is not in range [U+0000; U+10ffff]",
1436 ch);
1437 return -1;
1438 }
1439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
1441 return 0;
1442}
1443
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001444int
1445_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446{
1447 wchar_t *end;
1448 Py_UCS4 maxchar = 0;
1449 Py_ssize_t num_surrogates;
1450#if SIZEOF_WCHAR_T == 2
1451 Py_ssize_t length_wo_surrogates;
1452#endif
1453
Georg Brandl7597add2011-10-05 16:36:47 +02001454 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001455 strings were created using _PyObject_New() and where no canonical
1456 representation (the str field) has been set yet aka strings
1457 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001458 assert(_PyUnicode_CHECK(unicode));
1459 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001461 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001462 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001463 /* Actually, it should neither be interned nor be anything else: */
1464 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001467 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001468 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470
1471 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001472 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1473 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 PyErr_NoMemory();
1475 return -1;
1476 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001477 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 _PyUnicode_WSTR(unicode), end,
1479 PyUnicode_1BYTE_DATA(unicode));
1480 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1481 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1482 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1483 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001484 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001485 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001486 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 }
1488 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001489 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001490 _PyUnicode_UTF8(unicode) = NULL;
1491 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 }
1493 PyObject_FREE(_PyUnicode_WSTR(unicode));
1494 _PyUnicode_WSTR(unicode) = NULL;
1495 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1496 }
1497 /* In this case we might have to convert down from 4-byte native
1498 wchar_t to 2-byte unicode. */
1499 else if (maxchar < 65536) {
1500 assert(num_surrogates == 0 &&
1501 "FindMaxCharAndNumSurrogatePairs() messed up");
1502
Victor Stinner506f5922011-09-28 22:34:18 +02001503#if SIZEOF_WCHAR_T == 2
1504 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001505 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001506 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1507 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1508 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001509 _PyUnicode_UTF8(unicode) = NULL;
1510 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001511#else
1512 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001513 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001514 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001515 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001516 PyErr_NoMemory();
1517 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001518 }
Victor Stinner506f5922011-09-28 22:34:18 +02001519 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1520 _PyUnicode_WSTR(unicode), end,
1521 PyUnicode_2BYTE_DATA(unicode));
1522 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1523 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1524 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001525 _PyUnicode_UTF8(unicode) = NULL;
1526 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001527 PyObject_FREE(_PyUnicode_WSTR(unicode));
1528 _PyUnicode_WSTR(unicode) = NULL;
1529 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1530#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001531 }
1532 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1533 else {
1534#if SIZEOF_WCHAR_T == 2
1535 /* in case the native representation is 2-bytes, we need to allocate a
1536 new normalized 4-byte version. */
1537 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001538 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1539 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyErr_NoMemory();
1541 return -1;
1542 }
1543 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1544 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001545 _PyUnicode_UTF8(unicode) = NULL;
1546 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001547 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1548 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001549 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 PyObject_FREE(_PyUnicode_WSTR(unicode));
1551 _PyUnicode_WSTR(unicode) = NULL;
1552 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1553#else
1554 assert(num_surrogates == 0);
1555
Victor Stinnerc3c74152011-10-02 20:39:55 +02001556 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001558 _PyUnicode_UTF8(unicode) = NULL;
1559 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1561#endif
1562 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1563 }
1564 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 return 0;
1567}
1568
Alexander Belopolsky40018472011-02-26 01:02:56 +00001569static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001570unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571{
Walter Dörwald16807132007-05-25 13:52:07 +00001572 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 case SSTATE_NOT_INTERNED:
1574 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001575
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 case SSTATE_INTERNED_MORTAL:
1577 /* revive dead object temporarily for DelItem */
1578 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001579 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 Py_FatalError(
1581 "deletion of interned string failed");
1582 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001583
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 case SSTATE_INTERNED_IMMORTAL:
1585 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001586
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 default:
1588 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001589 }
1590
Victor Stinner03490912011-10-03 23:45:12 +02001591 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001593 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001594 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001595 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1596 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001598 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001599}
1600
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001601#ifdef Py_DEBUG
1602static int
1603unicode_is_singleton(PyObject *unicode)
1604{
1605 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1606 if (unicode == unicode_empty)
1607 return 1;
1608 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1609 {
1610 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1611 if (ch < 256 && unicode_latin1[ch] == unicode)
1612 return 1;
1613 }
1614 return 0;
1615}
1616#endif
1617
Alexander Belopolsky40018472011-02-26 01:02:56 +00001618static int
Victor Stinner488fa492011-12-12 00:01:39 +01001619unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001620{
Victor Stinner488fa492011-12-12 00:01:39 +01001621 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001622 if (Py_REFCNT(unicode) != 1)
1623 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001624 if (_PyUnicode_HASH(unicode) != -1)
1625 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 if (PyUnicode_CHECK_INTERNED(unicode))
1627 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001628 if (!PyUnicode_CheckExact(unicode))
1629 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001630#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001631 /* singleton refcount is greater than 1 */
1632 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001633#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634 return 1;
1635}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636
Victor Stinnerfe226c02011-10-03 03:52:20 +02001637static int
1638unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1639{
1640 PyObject *unicode;
1641 Py_ssize_t old_length;
1642
1643 assert(p_unicode != NULL);
1644 unicode = *p_unicode;
1645
1646 assert(unicode != NULL);
1647 assert(PyUnicode_Check(unicode));
1648 assert(0 <= length);
1649
Victor Stinner910337b2011-10-03 03:20:16 +02001650 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001651 old_length = PyUnicode_WSTR_LENGTH(unicode);
1652 else
1653 old_length = PyUnicode_GET_LENGTH(unicode);
1654 if (old_length == length)
1655 return 0;
1656
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001657 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001658 _Py_INCREF_UNICODE_EMPTY();
1659 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001660 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 Py_DECREF(*p_unicode);
1662 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001663 return 0;
1664 }
1665
Victor Stinner488fa492011-12-12 00:01:39 +01001666 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001667 PyObject *copy = resize_copy(unicode, length);
1668 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 Py_DECREF(*p_unicode);
1671 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001672 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673 }
1674
Victor Stinnerfe226c02011-10-03 03:52:20 +02001675 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001676 PyObject *new_unicode = resize_compact(unicode, length);
1677 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001679 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001680 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001681 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001682 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001683}
1684
Alexander Belopolsky40018472011-02-26 01:02:56 +00001685int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001687{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001688 PyObject *unicode;
1689 if (p_unicode == NULL) {
1690 PyErr_BadInternalCall();
1691 return -1;
1692 }
1693 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001694 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695 {
1696 PyErr_BadInternalCall();
1697 return -1;
1698 }
1699 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001700}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001701
Victor Stinnerc5166102012-02-22 13:55:02 +01001702/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001703
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001704 WARNING: The function doesn't copy the terminating null character and
1705 doesn't check the maximum character (may write a latin1 character in an
1706 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001707static void
1708unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1709 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001710{
1711 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1712 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001713 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001714
1715 switch (kind) {
1716 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001717 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001718#ifdef Py_DEBUG
1719 if (PyUnicode_IS_ASCII(unicode)) {
1720 Py_UCS4 maxchar = ucs1lib_find_max_char(
1721 (const Py_UCS1*)str,
1722 (const Py_UCS1*)str + len);
1723 assert(maxchar < 128);
1724 }
1725#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001726 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001727 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 }
1729 case PyUnicode_2BYTE_KIND: {
1730 Py_UCS2 *start = (Py_UCS2 *)data + index;
1731 Py_UCS2 *ucs2 = start;
1732 assert(index <= PyUnicode_GET_LENGTH(unicode));
1733
Victor Stinner184252a2012-06-16 02:57:41 +02001734 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 *ucs2 = (Py_UCS2)*str;
1736
1737 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001738 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 }
1740 default: {
1741 Py_UCS4 *start = (Py_UCS4 *)data + index;
1742 Py_UCS4 *ucs4 = start;
1743 assert(kind == PyUnicode_4BYTE_KIND);
1744 assert(index <= PyUnicode_GET_LENGTH(unicode));
1745
Victor Stinner184252a2012-06-16 02:57:41 +02001746 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001747 *ucs4 = (Py_UCS4)*str;
1748
1749 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 }
1751 }
1752}
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754static PyObject*
1755get_latin1_char(unsigned char ch)
1756{
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001759 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 if (!unicode)
1761 return NULL;
1762 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001763 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 unicode_latin1[ch] = unicode;
1765 }
1766 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001767 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768}
1769
Victor Stinner985a82a2014-01-03 12:53:47 +01001770static PyObject*
1771unicode_char(Py_UCS4 ch)
1772{
1773 PyObject *unicode;
1774
1775 assert(ch <= MAX_UNICODE);
1776
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001777 if (ch < 256)
1778 return get_latin1_char(ch);
1779
Victor Stinner985a82a2014-01-03 12:53:47 +01001780 unicode = PyUnicode_New(1, ch);
1781 if (unicode == NULL)
1782 return NULL;
1783 switch (PyUnicode_KIND(unicode)) {
1784 case PyUnicode_1BYTE_KIND:
1785 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1786 break;
1787 case PyUnicode_2BYTE_KIND:
1788 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1789 break;
1790 default:
1791 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1792 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1793 }
1794 assert(_PyUnicode_CheckConsistency(unicode, 1));
1795 return unicode;
1796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001800{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001801 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 Py_UCS4 maxchar = 0;
1803 Py_ssize_t num_surrogates;
1804
1805 if (u == NULL)
1806 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808 /* If the Unicode data is known at construction time, we can apply
1809 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001812 if (size == 0)
1813 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 /* Single character Unicode objects in the Latin-1 range are
1816 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001817 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 return get_latin1_char((unsigned char)*u);
1819
1820 /* If not empty and not single character, copy the Unicode data
1821 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001822 if (find_maxchar_surrogates(u, u + size,
1823 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 return NULL;
1825
Victor Stinner8faf8212011-12-08 22:14:11 +01001826 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001827 if (!unicode)
1828 return NULL;
1829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 switch (PyUnicode_KIND(unicode)) {
1831 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001832 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1834 break;
1835 case PyUnicode_2BYTE_KIND:
1836#if Py_UNICODE_SIZE == 2
1837 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1838#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001839 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1841#endif
1842 break;
1843 case PyUnicode_4BYTE_KIND:
1844#if SIZEOF_WCHAR_T == 2
1845 /* This is the only case which has to process surrogates, thus
1846 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001847 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848#else
1849 assert(num_surrogates == 0);
1850 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1851#endif
1852 break;
1853 default:
1854 assert(0 && "Impossible state");
1855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001856
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001857 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001858}
1859
Alexander Belopolsky40018472011-02-26 01:02:56 +00001860PyObject *
1861PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001862{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001863 if (size < 0) {
1864 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001866 return NULL;
1867 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001868 if (u != NULL)
1869 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1870 else
1871 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874PyObject *
1875PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001876{
1877 size_t size = strlen(u);
1878 if (size > PY_SSIZE_T_MAX) {
1879 PyErr_SetString(PyExc_OverflowError, "input too long");
1880 return NULL;
1881 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001882 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883}
1884
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001885PyObject *
1886_PyUnicode_FromId(_Py_Identifier *id)
1887{
1888 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001889 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1890 strlen(id->string),
1891 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001892 if (!id->object)
1893 return NULL;
1894 PyUnicode_InternInPlace(&id->object);
1895 assert(!id->next);
1896 id->next = static_strings;
1897 static_strings = id;
1898 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001899 return id->object;
1900}
1901
1902void
1903_PyUnicode_ClearStaticStrings()
1904{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001905 _Py_Identifier *tmp, *s = static_strings;
1906 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001907 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001908 tmp = s->next;
1909 s->next = NULL;
1910 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001911 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001913}
1914
Benjamin Peterson0df54292012-03-26 14:50:32 -04001915/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917PyObject*
1918_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001919{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001921 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001922 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001923#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001924 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001925#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001926 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001927 }
Victor Stinner785938e2011-12-11 20:09:03 +01001928 unicode = PyUnicode_New(size, 127);
1929 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001930 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001931 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1932 assert(_PyUnicode_CheckConsistency(unicode, 1));
1933 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001934}
1935
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001936static Py_UCS4
1937kind_maxchar_limit(unsigned int kind)
1938{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001939 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001940 case PyUnicode_1BYTE_KIND:
1941 return 0x80;
1942 case PyUnicode_2BYTE_KIND:
1943 return 0x100;
1944 case PyUnicode_4BYTE_KIND:
1945 return 0x10000;
1946 default:
1947 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001948 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001949 }
1950}
1951
Victor Stinnere6abb482012-05-02 01:15:40 +02001952Py_LOCAL_INLINE(Py_UCS4)
1953align_maxchar(Py_UCS4 maxchar)
1954{
1955 if (maxchar <= 127)
1956 return 127;
1957 else if (maxchar <= 255)
1958 return 255;
1959 else if (maxchar <= 65535)
1960 return 65535;
1961 else
1962 return MAX_UNICODE;
1963}
1964
Victor Stinner702c7342011-10-05 13:50:52 +02001965static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001966_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001970
Serhiy Storchaka678db842013-01-26 12:16:36 +02001971 if (size == 0)
1972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001974 if (size == 1)
1975 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001978 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 if (!res)
1980 return NULL;
1981 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001982 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001984}
1985
Victor Stinnere57b1c02011-09-28 22:20:48 +02001986static PyObject*
1987_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988{
1989 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001990 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001991
Serhiy Storchaka678db842013-01-26 12:16:36 +02001992 if (size == 0)
1993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001995 if (size == 1)
1996 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001998 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001999 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 if (!res)
2001 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002004 else {
2005 _PyUnicode_CONVERT_BYTES(
2006 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2007 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002008 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 return res;
2010}
2011
Victor Stinnere57b1c02011-09-28 22:20:48 +02002012static PyObject*
2013_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014{
2015 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002016 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017
Serhiy Storchaka678db842013-01-26 12:16:36 +02002018 if (size == 0)
2019 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002020 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002021 if (size == 1)
2022 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002024 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002025 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 if (!res)
2027 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002028 if (max_char < 256)
2029 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2030 PyUnicode_1BYTE_DATA(res));
2031 else if (max_char < 0x10000)
2032 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2033 PyUnicode_2BYTE_DATA(res));
2034 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002036 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 return res;
2038}
2039
2040PyObject*
2041PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2042{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002043 if (size < 0) {
2044 PyErr_SetString(PyExc_ValueError, "size must be positive");
2045 return NULL;
2046 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002047 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002049 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002051 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002053 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002055 PyErr_SetString(PyExc_SystemError, "invalid kind");
2056 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058}
2059
Victor Stinnerece58de2012-04-23 23:36:38 +02002060Py_UCS4
2061_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2062{
2063 enum PyUnicode_Kind kind;
2064 void *startptr, *endptr;
2065
2066 assert(PyUnicode_IS_READY(unicode));
2067 assert(0 <= start);
2068 assert(end <= PyUnicode_GET_LENGTH(unicode));
2069 assert(start <= end);
2070
2071 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2072 return PyUnicode_MAX_CHAR_VALUE(unicode);
2073
2074 if (start == end)
2075 return 127;
2076
Victor Stinner94d558b2012-04-27 22:26:58 +02002077 if (PyUnicode_IS_ASCII(unicode))
2078 return 127;
2079
Victor Stinnerece58de2012-04-23 23:36:38 +02002080 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002081 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002082 endptr = (char *)startptr + end * kind;
2083 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 switch(kind) {
2085 case PyUnicode_1BYTE_KIND:
2086 return ucs1lib_find_max_char(startptr, endptr);
2087 case PyUnicode_2BYTE_KIND:
2088 return ucs2lib_find_max_char(startptr, endptr);
2089 case PyUnicode_4BYTE_KIND:
2090 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002091 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002092 assert(0);
2093 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002094 }
2095}
2096
Victor Stinner25a4b292011-10-06 12:31:55 +02002097/* Ensure that a string uses the most efficient storage, if it is not the
2098 case: create a new string with of the right kind. Write NULL into *p_unicode
2099 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002100static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002101unicode_adjust_maxchar(PyObject **p_unicode)
2102{
2103 PyObject *unicode, *copy;
2104 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002105 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002106 unsigned int kind;
2107
2108 assert(p_unicode != NULL);
2109 unicode = *p_unicode;
2110 assert(PyUnicode_IS_READY(unicode));
2111 if (PyUnicode_IS_ASCII(unicode))
2112 return;
2113
2114 len = PyUnicode_GET_LENGTH(unicode);
2115 kind = PyUnicode_KIND(unicode);
2116 if (kind == PyUnicode_1BYTE_KIND) {
2117 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002118 max_char = ucs1lib_find_max_char(u, u + len);
2119 if (max_char >= 128)
2120 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002121 }
2122 else if (kind == PyUnicode_2BYTE_KIND) {
2123 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002124 max_char = ucs2lib_find_max_char(u, u + len);
2125 if (max_char >= 256)
2126 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 }
2128 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002129 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002131 max_char = ucs4lib_find_max_char(u, u + len);
2132 if (max_char >= 0x10000)
2133 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002135 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002136 if (copy != NULL)
2137 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 Py_DECREF(unicode);
2139 *p_unicode = copy;
2140}
2141
Victor Stinner034f6cf2011-09-30 02:26:44 +02002142PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002143_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002144{
Victor Stinner87af4f22011-11-21 23:03:47 +01002145 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002147
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148 if (!PyUnicode_Check(unicode)) {
2149 PyErr_BadInternalCall();
2150 return NULL;
2151 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002152 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002154
Victor Stinner87af4f22011-11-21 23:03:47 +01002155 length = PyUnicode_GET_LENGTH(unicode);
2156 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157 if (!copy)
2158 return NULL;
2159 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2160
Victor Stinner87af4f22011-11-21 23:03:47 +01002161 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2162 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002163 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002164 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002165}
2166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002167
Victor Stinnerbc603d12011-10-02 01:00:40 +02002168/* Widen Unicode objects to larger buffers. Don't write terminating null
2169 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170
2171void*
2172_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2173{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 Py_ssize_t len;
2175 void *result;
2176 unsigned int skind;
2177
Benjamin Petersonbac79492012-01-14 13:34:47 -05002178 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002179 return NULL;
2180
2181 len = PyUnicode_GET_LENGTH(s);
2182 skind = PyUnicode_KIND(s);
2183 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002184 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 return NULL;
2186 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002187 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002188 case PyUnicode_2BYTE_KIND:
2189 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2190 if (!result)
2191 return PyErr_NoMemory();
2192 assert(skind == PyUnicode_1BYTE_KIND);
2193 _PyUnicode_CONVERT_BYTES(
2194 Py_UCS1, Py_UCS2,
2195 PyUnicode_1BYTE_DATA(s),
2196 PyUnicode_1BYTE_DATA(s) + len,
2197 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 case PyUnicode_4BYTE_KIND:
2200 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2201 if (!result)
2202 return PyErr_NoMemory();
2203 if (skind == PyUnicode_2BYTE_KIND) {
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS2, Py_UCS4,
2206 PyUnicode_2BYTE_DATA(s),
2207 PyUnicode_2BYTE_DATA(s) + len,
2208 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 else {
2211 assert(skind == PyUnicode_1BYTE_KIND);
2212 _PyUnicode_CONVERT_BYTES(
2213 Py_UCS1, Py_UCS4,
2214 PyUnicode_1BYTE_DATA(s),
2215 PyUnicode_1BYTE_DATA(s) + len,
2216 result);
2217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 default:
2220 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 }
Victor Stinner01698042011-10-04 00:04:26 +02002222 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 return NULL;
2224}
2225
2226static Py_UCS4*
2227as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
2230 int kind;
2231 void *data;
2232 Py_ssize_t len, targetlen;
2233 if (PyUnicode_READY(string) == -1)
2234 return NULL;
2235 kind = PyUnicode_KIND(string);
2236 data = PyUnicode_DATA(string);
2237 len = PyUnicode_GET_LENGTH(string);
2238 targetlen = len;
2239 if (copy_null)
2240 targetlen++;
2241 if (!target) {
2242 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2247 if (!target) {
2248 PyErr_NoMemory();
2249 return NULL;
2250 }
2251 }
2252 else {
2253 if (targetsize < targetlen) {
2254 PyErr_Format(PyExc_SystemError,
2255 "string is longer than the buffer");
2256 if (copy_null && 0 < targetsize)
2257 target[0] = 0;
2258 return NULL;
2259 }
2260 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002261 if (kind == PyUnicode_1BYTE_KIND) {
2262 Py_UCS1 *start = (Py_UCS1 *) data;
2263 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002265 else if (kind == PyUnicode_2BYTE_KIND) {
2266 Py_UCS2 *start = (Py_UCS2 *) data;
2267 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2268 }
2269 else {
2270 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 if (copy_null)
2274 target[len] = 0;
2275 return target;
2276}
2277
2278Py_UCS4*
2279PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2280 int copy_null)
2281{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002282 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002283 PyErr_BadInternalCall();
2284 return NULL;
2285 }
2286 return as_ucs4(string, target, targetsize, copy_null);
2287}
2288
2289Py_UCS4*
2290PyUnicode_AsUCS4Copy(PyObject *string)
2291{
2292 return as_ucs4(string, NULL, 0, 1);
2293}
2294
2295#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002296
Alexander Belopolsky40018472011-02-26 01:02:56 +00002297PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002298PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002299{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002301 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002302 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002303 PyErr_BadInternalCall();
2304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002305 }
2306
Martin v. Löwis790465f2008-04-05 20:41:37 +00002307 if (size == -1) {
2308 size = wcslen(w);
2309 }
2310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002311 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002312}
2313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002314#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002315
Walter Dörwald346737f2007-05-31 10:44:43 +00002316static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002317makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002318 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002319{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002320 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002321 if (longflag)
2322 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002323 else if (longlongflag) {
2324 /* longlongflag should only ever be nonzero on machines with
2325 HAVE_LONG_LONG defined */
2326#ifdef HAVE_LONG_LONG
2327 char *f = PY_FORMAT_LONG_LONG;
2328 while (*f)
2329 *fmt++ = *f++;
2330#else
2331 /* we shouldn't ever get here */
2332 assert(0);
2333 *fmt++ = 'l';
2334#endif
2335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002336 else if (size_tflag) {
2337 char *f = PY_FORMAT_SIZE_T;
2338 while (*f)
2339 *fmt++ = *f++;
2340 }
2341 *fmt++ = c;
2342 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002343}
2344
Victor Stinner15a11362012-10-06 23:48:20 +02002345/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002346 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2347 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2348#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002349
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002350static int
2351unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2352 Py_ssize_t width, Py_ssize_t precision)
2353{
2354 Py_ssize_t length, fill, arglen;
2355 Py_UCS4 maxchar;
2356
2357 if (PyUnicode_READY(str) == -1)
2358 return -1;
2359
2360 length = PyUnicode_GET_LENGTH(str);
2361 if ((precision == -1 || precision >= length)
2362 && width <= length)
2363 return _PyUnicodeWriter_WriteStr(writer, str);
2364
2365 if (precision != -1)
2366 length = Py_MIN(precision, length);
2367
2368 arglen = Py_MAX(length, width);
2369 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2370 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2371 else
2372 maxchar = writer->maxchar;
2373
2374 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2375 return -1;
2376
2377 if (width > length) {
2378 fill = width - length;
2379 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2380 return -1;
2381 writer->pos += fill;
2382 }
2383
2384 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2385 str, 0, length);
2386 writer->pos += length;
2387 return 0;
2388}
2389
2390static int
2391unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2392 Py_ssize_t width, Py_ssize_t precision)
2393{
2394 /* UTF-8 */
2395 Py_ssize_t length;
2396 PyObject *unicode;
2397 int res;
2398
2399 length = strlen(str);
2400 if (precision != -1)
2401 length = Py_MIN(length, precision);
2402 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2403 if (unicode == NULL)
2404 return -1;
2405
2406 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2407 Py_DECREF(unicode);
2408 return res;
2409}
2410
Victor Stinner96865452011-03-01 23:44:09 +00002411static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002412unicode_fromformat_arg(_PyUnicodeWriter *writer,
2413 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002414{
Victor Stinnere215d962012-10-06 23:03:36 +02002415 const char *p;
2416 Py_ssize_t len;
2417 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002418 Py_ssize_t width;
2419 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002420 int longflag;
2421 int longlongflag;
2422 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002423 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002424
2425 p = f;
2426 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002427 zeropad = 0;
2428 if (*f == '0') {
2429 zeropad = 1;
2430 f++;
2431 }
Victor Stinner96865452011-03-01 23:44:09 +00002432
2433 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002434 width = -1;
2435 if (Py_ISDIGIT((unsigned)*f)) {
2436 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002437 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002438 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002440 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002441 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002442 return NULL;
2443 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002444 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002445 f++;
2446 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002447 }
2448 precision = -1;
2449 if (*f == '.') {
2450 f++;
2451 if (Py_ISDIGIT((unsigned)*f)) {
2452 precision = (*f - '0');
2453 f++;
2454 while (Py_ISDIGIT((unsigned)*f)) {
2455 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2456 PyErr_SetString(PyExc_ValueError,
2457 "precision too big");
2458 return NULL;
2459 }
2460 precision = (precision * 10) + (*f - '0');
2461 f++;
2462 }
2463 }
Victor Stinner96865452011-03-01 23:44:09 +00002464 if (*f == '%') {
2465 /* "%.3%s" => f points to "3" */
2466 f--;
2467 }
2468 }
2469 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002470 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002471 f--;
2472 }
Victor Stinner96865452011-03-01 23:44:09 +00002473
2474 /* Handle %ld, %lu, %lld and %llu. */
2475 longflag = 0;
2476 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002477 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002478 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002479 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002480 longflag = 1;
2481 ++f;
2482 }
2483#ifdef HAVE_LONG_LONG
2484 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002485 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002486 longlongflag = 1;
2487 f += 2;
2488 }
2489#endif
2490 }
2491 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002492 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002493 size_tflag = 1;
2494 ++f;
2495 }
Victor Stinnere215d962012-10-06 23:03:36 +02002496
2497 if (f[1] == '\0')
2498 writer->overallocate = 0;
2499
2500 switch (*f) {
2501 case 'c':
2502 {
2503 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002504 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002505 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002506 "character argument not in range(0x110000)");
2507 return NULL;
2508 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002509 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002510 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002511 break;
2512 }
2513
2514 case 'i':
2515 case 'd':
2516 case 'u':
2517 case 'x':
2518 {
2519 /* used by sprintf */
2520 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002521 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002522 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002523
2524 if (*f == 'u') {
2525 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2526
2527 if (longflag)
2528 len = sprintf(buffer, fmt,
2529 va_arg(*vargs, unsigned long));
2530#ifdef HAVE_LONG_LONG
2531 else if (longlongflag)
2532 len = sprintf(buffer, fmt,
2533 va_arg(*vargs, unsigned PY_LONG_LONG));
2534#endif
2535 else if (size_tflag)
2536 len = sprintf(buffer, fmt,
2537 va_arg(*vargs, size_t));
2538 else
2539 len = sprintf(buffer, fmt,
2540 va_arg(*vargs, unsigned int));
2541 }
2542 else if (*f == 'x') {
2543 makefmt(fmt, 0, 0, 0, 'x');
2544 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2545 }
2546 else {
2547 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2548
2549 if (longflag)
2550 len = sprintf(buffer, fmt,
2551 va_arg(*vargs, long));
2552#ifdef HAVE_LONG_LONG
2553 else if (longlongflag)
2554 len = sprintf(buffer, fmt,
2555 va_arg(*vargs, PY_LONG_LONG));
2556#endif
2557 else if (size_tflag)
2558 len = sprintf(buffer, fmt,
2559 va_arg(*vargs, Py_ssize_t));
2560 else
2561 len = sprintf(buffer, fmt,
2562 va_arg(*vargs, int));
2563 }
2564 assert(len >= 0);
2565
Victor Stinnere215d962012-10-06 23:03:36 +02002566 if (precision < len)
2567 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002568
2569 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002570 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2571 return NULL;
2572
Victor Stinnere215d962012-10-06 23:03:36 +02002573 if (width > precision) {
2574 Py_UCS4 fillchar;
2575 fill = width - precision;
2576 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002577 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2578 return NULL;
2579 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002580 }
Victor Stinner15a11362012-10-06 23:48:20 +02002581 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002582 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002583 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2584 return NULL;
2585 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002586 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002587
Victor Stinner4a587072013-11-19 12:54:53 +01002588 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2589 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002590 break;
2591 }
2592
2593 case 'p':
2594 {
2595 char number[MAX_LONG_LONG_CHARS];
2596
2597 len = sprintf(number, "%p", va_arg(*vargs, void*));
2598 assert(len >= 0);
2599
2600 /* %p is ill-defined: ensure leading 0x. */
2601 if (number[1] == 'X')
2602 number[1] = 'x';
2603 else if (number[1] != 'x') {
2604 memmove(number + 2, number,
2605 strlen(number) + 1);
2606 number[0] = '0';
2607 number[1] = 'x';
2608 len += 2;
2609 }
2610
Victor Stinner4a587072013-11-19 12:54:53 +01002611 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002612 return NULL;
2613 break;
2614 }
2615
2616 case 's':
2617 {
2618 /* UTF-8 */
2619 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002620 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002621 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002622 break;
2623 }
2624
2625 case 'U':
2626 {
2627 PyObject *obj = va_arg(*vargs, PyObject *);
2628 assert(obj && _PyUnicode_CHECK(obj));
2629
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002630 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002631 return NULL;
2632 break;
2633 }
2634
2635 case 'V':
2636 {
2637 PyObject *obj = va_arg(*vargs, PyObject *);
2638 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002639 if (obj) {
2640 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002642 return NULL;
2643 }
2644 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002645 assert(str != NULL);
2646 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002647 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002648 }
2649 break;
2650 }
2651
2652 case 'S':
2653 {
2654 PyObject *obj = va_arg(*vargs, PyObject *);
2655 PyObject *str;
2656 assert(obj);
2657 str = PyObject_Str(obj);
2658 if (!str)
2659 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002660 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002661 Py_DECREF(str);
2662 return NULL;
2663 }
2664 Py_DECREF(str);
2665 break;
2666 }
2667
2668 case 'R':
2669 {
2670 PyObject *obj = va_arg(*vargs, PyObject *);
2671 PyObject *repr;
2672 assert(obj);
2673 repr = PyObject_Repr(obj);
2674 if (!repr)
2675 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002676 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002677 Py_DECREF(repr);
2678 return NULL;
2679 }
2680 Py_DECREF(repr);
2681 break;
2682 }
2683
2684 case 'A':
2685 {
2686 PyObject *obj = va_arg(*vargs, PyObject *);
2687 PyObject *ascii;
2688 assert(obj);
2689 ascii = PyObject_ASCII(obj);
2690 if (!ascii)
2691 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002692 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 Py_DECREF(ascii);
2694 return NULL;
2695 }
2696 Py_DECREF(ascii);
2697 break;
2698 }
2699
2700 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002701 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002702 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002703 break;
2704
2705 default:
2706 /* if we stumble upon an unknown formatting code, copy the rest
2707 of the format string to the output string. (we cannot just
2708 skip the code, since there's no way to know what's in the
2709 argument list) */
2710 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002711 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002712 return NULL;
2713 f = p+len;
2714 return f;
2715 }
2716
2717 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002718 return f;
2719}
2720
Walter Dörwaldd2034312007-05-18 16:29:38 +00002721PyObject *
2722PyUnicode_FromFormatV(const char *format, va_list vargs)
2723{
Victor Stinnere215d962012-10-06 23:03:36 +02002724 va_list vargs2;
2725 const char *f;
2726 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002727
Victor Stinner8f674cc2013-04-17 23:02:17 +02002728 _PyUnicodeWriter_Init(&writer);
2729 writer.min_length = strlen(format) + 100;
2730 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002731
2732 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2733 Copy it to be able to pass a reference to a subfunction. */
2734 Py_VA_COPY(vargs2, vargs);
2735
2736 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002737 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002738 f = unicode_fromformat_arg(&writer, f, &vargs2);
2739 if (f == NULL)
2740 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002743 const char *p;
2744 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002745
Victor Stinnere215d962012-10-06 23:03:36 +02002746 p = f;
2747 do
2748 {
2749 if ((unsigned char)*p > 127) {
2750 PyErr_Format(PyExc_ValueError,
2751 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2752 "string, got a non-ASCII byte: 0x%02x",
2753 (unsigned char)*p);
2754 return NULL;
2755 }
2756 p++;
2757 }
2758 while (*p != '\0' && *p != '%');
2759 len = p - f;
2760
2761 if (*p == '\0')
2762 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002763
2764 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002765 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002766
2767 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 }
Victor Stinnere215d962012-10-06 23:03:36 +02002770 return _PyUnicodeWriter_Finish(&writer);
2771
2772 fail:
2773 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002774 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002775}
2776
Walter Dörwaldd2034312007-05-18 16:29:38 +00002777PyObject *
2778PyUnicode_FromFormat(const char *format, ...)
2779{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 PyObject* ret;
2781 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782
2783#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002784 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002785#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002786 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002787#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002788 ret = PyUnicode_FromFormatV(format, vargs);
2789 va_end(vargs);
2790 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002791}
2792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793#ifdef HAVE_WCHAR_H
2794
Victor Stinner5593d8a2010-10-02 11:11:27 +00002795/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2796 convert a Unicode object to a wide character string.
2797
Victor Stinnerd88d9832011-09-06 02:00:05 +02002798 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 character) required to convert the unicode object. Ignore size argument.
2800
Victor Stinnerd88d9832011-09-06 02:00:05 +02002801 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002802 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002803 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002804static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002805unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002806 wchar_t *w,
2807 Py_ssize_t size)
2808{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002809 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 const wchar_t *wstr;
2811
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002812 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 if (wstr == NULL)
2814 return -1;
2815
Victor Stinner5593d8a2010-10-02 11:11:27 +00002816 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002817 if (size > res)
2818 size = res + 1;
2819 else
2820 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002822 return res;
2823 }
2824 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002826}
2827
2828Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002829PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002830 wchar_t *w,
2831 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832{
2833 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002834 PyErr_BadInternalCall();
2835 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002836 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002837 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002838}
2839
Victor Stinner137c34c2010-09-29 10:25:54 +00002840wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002841PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002842 Py_ssize_t *size)
2843{
2844 wchar_t* buffer;
2845 Py_ssize_t buflen;
2846
2847 if (unicode == NULL) {
2848 PyErr_BadInternalCall();
2849 return NULL;
2850 }
2851
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002852 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002853 if (buflen == -1)
2854 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002855 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002856 PyErr_NoMemory();
2857 return NULL;
2858 }
2859
Victor Stinner137c34c2010-09-29 10:25:54 +00002860 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2861 if (buffer == NULL) {
2862 PyErr_NoMemory();
2863 return NULL;
2864 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002865 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002866 if (buflen == -1) {
2867 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002869 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002870 if (size != NULL)
2871 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002872 return buffer;
2873}
2874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002875#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002879{
Victor Stinner8faf8212011-12-08 22:14:11 +01002880 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 PyErr_SetString(PyExc_ValueError,
2882 "chr() arg not in range(0x110000)");
2883 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002884 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002885
Victor Stinner985a82a2014-01-03 12:53:47 +01002886 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002887}
2888
Alexander Belopolsky40018472011-02-26 01:02:56 +00002889PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002890PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002892 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002893 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002895 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002896 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002897 Py_INCREF(obj);
2898 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002899 }
2900 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002901 /* For a Unicode subtype that's not a Unicode object,
2902 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002903 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002904 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002905 PyErr_Format(PyExc_TypeError,
2906 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002907 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002908 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002909}
2910
Alexander Belopolsky40018472011-02-26 01:02:56 +00002911PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002912PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002913 const char *encoding,
2914 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002915{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002916 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002917 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002918
Guido van Rossumd57fd912000-03-10 22:53:23 +00002919 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 PyErr_BadInternalCall();
2921 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002923
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002924 /* Decoding bytes objects is the most common case and should be fast */
2925 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002926 if (PyBytes_GET_SIZE(obj) == 0)
2927 _Py_RETURN_UNICODE_EMPTY();
2928 v = PyUnicode_Decode(
2929 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2930 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002931 return v;
2932 }
2933
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002934 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002935 PyErr_SetString(PyExc_TypeError,
2936 "decoding str is not supported");
2937 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002939
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002940 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2941 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2942 PyErr_Format(PyExc_TypeError,
2943 "coercing to str: need bytes, bytearray "
2944 "or buffer-like object, %.80s found",
2945 Py_TYPE(obj)->tp_name);
2946 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002947 }
Tim Petersced69f82003-09-16 20:30:58 +00002948
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002949 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002950 PyBuffer_Release(&buffer);
2951 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002953
Serhiy Storchaka05997252013-01-26 12:14:02 +02002954 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002955 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002956 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957}
2958
Victor Stinner600d3be2010-06-10 12:00:55 +00002959/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002960 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2961 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002962int
2963_Py_normalize_encoding(const char *encoding,
2964 char *lower,
2965 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002967 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002968 char *l;
2969 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002970
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002971 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002972 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002973 if (lower_len < 6)
2974 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002975 strcpy(lower, "utf-8");
2976 return 1;
2977 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002978 e = encoding;
2979 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002980 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002981 while (*e) {
2982 if (l == l_end)
2983 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002984 if (Py_ISUPPER(*e)) {
2985 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002986 }
2987 else if (*e == '_') {
2988 *l++ = '-';
2989 e++;
2990 }
2991 else {
2992 *l++ = *e++;
2993 }
2994 }
2995 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002996 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002997}
2998
Alexander Belopolsky40018472011-02-26 01:02:56 +00002999PyObject *
3000PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003001 Py_ssize_t size,
3002 const char *encoding,
3003 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003004{
3005 PyObject *buffer = NULL, *unicode;
3006 Py_buffer info;
3007 char lower[11]; /* Enough for any encoding shortcut */
3008
Fred Drakee4315f52000-05-09 19:53:39 +00003009 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003010 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003011 if ((strcmp(lower, "utf-8") == 0) ||
3012 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003013 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003014 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003015 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003016 (strcmp(lower, "iso-8859-1") == 0) ||
3017 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003018 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003019#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003020 else if (strcmp(lower, "mbcs") == 0)
3021 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003022#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003023 else if (strcmp(lower, "ascii") == 0)
3024 return PyUnicode_DecodeASCII(s, size, errors);
3025 else if (strcmp(lower, "utf-16") == 0)
3026 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3027 else if (strcmp(lower, "utf-32") == 0)
3028 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030
3031 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003032 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003033 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003034 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003035 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003036 if (buffer == NULL)
3037 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003038 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003039 if (unicode == NULL)
3040 goto onError;
3041 if (!PyUnicode_Check(unicode)) {
3042 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003043 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3044 "use codecs.decode() to decode to arbitrary types",
3045 encoding,
3046 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003047 Py_DECREF(unicode);
3048 goto onError;
3049 }
3050 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003051 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003052
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003054 Py_XDECREF(buffer);
3055 return NULL;
3056}
3057
Alexander Belopolsky40018472011-02-26 01:02:56 +00003058PyObject *
3059PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003060 const char *encoding,
3061 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003062{
3063 PyObject *v;
3064
3065 if (!PyUnicode_Check(unicode)) {
3066 PyErr_BadArgument();
3067 goto onError;
3068 }
3069
3070 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003072
3073 /* Decode via the codec registry */
3074 v = PyCodec_Decode(unicode, encoding, errors);
3075 if (v == NULL)
3076 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003077 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003078
Benjamin Peterson29060642009-01-31 22:14:21 +00003079 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003080 return NULL;
3081}
3082
Alexander Belopolsky40018472011-02-26 01:02:56 +00003083PyObject *
3084PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003085 const char *encoding,
3086 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003087{
3088 PyObject *v;
3089
3090 if (!PyUnicode_Check(unicode)) {
3091 PyErr_BadArgument();
3092 goto onError;
3093 }
3094
3095 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003096 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003097
3098 /* Decode via the codec registry */
3099 v = PyCodec_Decode(unicode, encoding, errors);
3100 if (v == NULL)
3101 goto onError;
3102 if (!PyUnicode_Check(v)) {
3103 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003104 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3105 "use codecs.decode() to decode to arbitrary types",
3106 encoding,
3107 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003108 Py_DECREF(v);
3109 goto onError;
3110 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003111 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003112
Benjamin Peterson29060642009-01-31 22:14:21 +00003113 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003114 return NULL;
3115}
3116
Alexander Belopolsky40018472011-02-26 01:02:56 +00003117PyObject *
3118PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003119 Py_ssize_t size,
3120 const char *encoding,
3121 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003122{
3123 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003124
Guido van Rossumd57fd912000-03-10 22:53:23 +00003125 unicode = PyUnicode_FromUnicode(s, size);
3126 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003128 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3129 Py_DECREF(unicode);
3130 return v;
3131}
3132
Alexander Belopolsky40018472011-02-26 01:02:56 +00003133PyObject *
3134PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003135 const char *encoding,
3136 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003137{
3138 PyObject *v;
3139
3140 if (!PyUnicode_Check(unicode)) {
3141 PyErr_BadArgument();
3142 goto onError;
3143 }
3144
3145 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003147
3148 /* Encode via the codec registry */
3149 v = PyCodec_Encode(unicode, encoding, errors);
3150 if (v == NULL)
3151 goto onError;
3152 return v;
3153
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003155 return NULL;
3156}
3157
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003158static size_t
3159wcstombs_errorpos(const wchar_t *wstr)
3160{
3161 size_t len;
3162#if SIZEOF_WCHAR_T == 2
3163 wchar_t buf[3];
3164#else
3165 wchar_t buf[2];
3166#endif
3167 char outbuf[MB_LEN_MAX];
3168 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003169
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003170#if SIZEOF_WCHAR_T == 2
3171 buf[2] = 0;
3172#else
3173 buf[1] = 0;
3174#endif
3175 start = wstr;
3176 while (*wstr != L'\0')
3177 {
3178 previous = wstr;
3179#if SIZEOF_WCHAR_T == 2
3180 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3181 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3182 {
3183 buf[0] = wstr[0];
3184 buf[1] = wstr[1];
3185 wstr += 2;
3186 }
3187 else {
3188 buf[0] = *wstr;
3189 buf[1] = 0;
3190 wstr++;
3191 }
3192#else
3193 buf[0] = *wstr;
3194 wstr++;
3195#endif
3196 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003197 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003199 }
3200
3201 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003202 return 0;
3203}
3204
Victor Stinner1b579672011-12-17 05:47:23 +01003205static int
3206locale_error_handler(const char *errors, int *surrogateescape)
3207{
3208 if (errors == NULL) {
3209 *surrogateescape = 0;
3210 return 0;
3211 }
3212
3213 if (strcmp(errors, "strict") == 0) {
3214 *surrogateescape = 0;
3215 return 0;
3216 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003217 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003218 *surrogateescape = 1;
3219 return 0;
3220 }
3221 PyErr_Format(PyExc_ValueError,
3222 "only 'strict' and 'surrogateescape' error handlers "
3223 "are supported, not '%s'",
3224 errors);
3225 return -1;
3226}
3227
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003228PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003229PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003230{
3231 Py_ssize_t wlen, wlen2;
3232 wchar_t *wstr;
3233 PyObject *bytes = NULL;
3234 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003235 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236 PyObject *exc;
3237 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003238 int surrogateescape;
3239
3240 if (locale_error_handler(errors, &surrogateescape) < 0)
3241 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003242
3243 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3244 if (wstr == NULL)
3245 return NULL;
3246
3247 wlen2 = wcslen(wstr);
3248 if (wlen2 != wlen) {
3249 PyMem_Free(wstr);
3250 PyErr_SetString(PyExc_TypeError, "embedded null character");
3251 return NULL;
3252 }
3253
3254 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003255 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003256 char *str;
3257
3258 str = _Py_wchar2char(wstr, &error_pos);
3259 if (str == NULL) {
3260 if (error_pos == (size_t)-1) {
3261 PyErr_NoMemory();
3262 PyMem_Free(wstr);
3263 return NULL;
3264 }
3265 else {
3266 goto encode_error;
3267 }
3268 }
3269 PyMem_Free(wstr);
3270
3271 bytes = PyBytes_FromString(str);
3272 PyMem_Free(str);
3273 }
3274 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003275 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276 size_t len, len2;
3277
3278 len = wcstombs(NULL, wstr, 0);
3279 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003280 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003281 goto encode_error;
3282 }
3283
3284 bytes = PyBytes_FromStringAndSize(NULL, len);
3285 if (bytes == NULL) {
3286 PyMem_Free(wstr);
3287 return NULL;
3288 }
3289
3290 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3291 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003292 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 goto encode_error;
3294 }
3295 PyMem_Free(wstr);
3296 }
3297 return bytes;
3298
3299encode_error:
3300 errmsg = strerror(errno);
3301 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003302
3303 if (error_pos == (size_t)-1)
3304 error_pos = wcstombs_errorpos(wstr);
3305
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306 PyMem_Free(wstr);
3307 Py_XDECREF(bytes);
3308
Victor Stinner2f197072011-12-17 07:08:30 +01003309 if (errmsg != NULL) {
3310 size_t errlen;
3311 wstr = _Py_char2wchar(errmsg, &errlen);
3312 if (wstr != NULL) {
3313 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003314 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003315 } else
3316 errmsg = NULL;
3317 }
3318 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003319 reason = PyUnicode_FromString(
3320 "wcstombs() encountered an unencodable "
3321 "wide character");
3322 if (reason == NULL)
3323 return NULL;
3324
3325 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3326 "locale", unicode,
3327 (Py_ssize_t)error_pos,
3328 (Py_ssize_t)(error_pos+1),
3329 reason);
3330 Py_DECREF(reason);
3331 if (exc != NULL) {
3332 PyCodec_StrictErrors(exc);
3333 Py_XDECREF(exc);
3334 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003335 return NULL;
3336}
3337
Victor Stinnerad158722010-10-27 00:25:46 +00003338PyObject *
3339PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003340{
Victor Stinner99b95382011-07-04 14:23:54 +02003341#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003342 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003343#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003344 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003345#else
Victor Stinner793b5312011-04-27 00:24:21 +02003346 PyInterpreterState *interp = PyThreadState_GET()->interp;
3347 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3348 cannot use it to encode and decode filenames before it is loaded. Load
3349 the Python codec requires to encode at least its own filename. Use the C
3350 version of the locale codec until the codec registry is initialized and
3351 the Python codec is loaded.
3352
3353 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3354 cannot only rely on it: check also interp->fscodec_initialized for
3355 subinterpreters. */
3356 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003357 return PyUnicode_AsEncodedString(unicode,
3358 Py_FileSystemDefaultEncoding,
3359 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003360 }
3361 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003362 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003363 }
Victor Stinnerad158722010-10-27 00:25:46 +00003364#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003365}
3366
Alexander Belopolsky40018472011-02-26 01:02:56 +00003367PyObject *
3368PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003369 const char *encoding,
3370 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003371{
3372 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003373 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003374
Guido van Rossumd57fd912000-03-10 22:53:23 +00003375 if (!PyUnicode_Check(unicode)) {
3376 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003378 }
Fred Drakee4315f52000-05-09 19:53:39 +00003379
Fred Drakee4315f52000-05-09 19:53:39 +00003380 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003381 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003382 if ((strcmp(lower, "utf-8") == 0) ||
3383 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003384 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003385 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003387 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003389 }
Victor Stinner37296e82010-06-10 13:36:23 +00003390 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003391 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003392 (strcmp(lower, "iso-8859-1") == 0) ||
3393 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003395#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003396 else if (strcmp(lower, "mbcs") == 0)
3397 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003398#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003399 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003400 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003402
3403 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003404 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003405 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003406 return NULL;
3407
3408 /* The normal path */
3409 if (PyBytes_Check(v))
3410 return v;
3411
3412 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003414 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003415 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003416
3417 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003418 "encoder %s returned bytearray instead of bytes; "
3419 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003420 encoding);
3421 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003422 Py_DECREF(v);
3423 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003425
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003426 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3427 Py_DECREF(v);
3428 return b;
3429 }
3430
3431 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003432 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3433 "use codecs.encode() to encode to arbitrary types",
3434 encoding,
3435 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003436 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003437 return NULL;
3438}
3439
Alexander Belopolsky40018472011-02-26 01:02:56 +00003440PyObject *
3441PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003442 const char *encoding,
3443 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003444{
3445 PyObject *v;
3446
3447 if (!PyUnicode_Check(unicode)) {
3448 PyErr_BadArgument();
3449 goto onError;
3450 }
3451
3452 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003453 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003454
3455 /* Encode via the codec registry */
3456 v = PyCodec_Encode(unicode, encoding, errors);
3457 if (v == NULL)
3458 goto onError;
3459 if (!PyUnicode_Check(v)) {
3460 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003461 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3462 "use codecs.encode() to encode to arbitrary types",
3463 encoding,
3464 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003465 Py_DECREF(v);
3466 goto onError;
3467 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003469
Benjamin Peterson29060642009-01-31 22:14:21 +00003470 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003471 return NULL;
3472}
3473
Victor Stinner2f197072011-12-17 07:08:30 +01003474static size_t
3475mbstowcs_errorpos(const char *str, size_t len)
3476{
3477#ifdef HAVE_MBRTOWC
3478 const char *start = str;
3479 mbstate_t mbs;
3480 size_t converted;
3481 wchar_t ch;
3482
3483 memset(&mbs, 0, sizeof mbs);
3484 while (len)
3485 {
3486 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3487 if (converted == 0)
3488 /* Reached end of string */
3489 break;
3490 if (converted == (size_t)-1 || converted == (size_t)-2) {
3491 /* Conversion error or incomplete character */
3492 return str - start;
3493 }
3494 else {
3495 str += converted;
3496 len -= converted;
3497 }
3498 }
3499 /* failed to find the undecodable byte sequence */
3500 return 0;
3501#endif
3502 return 0;
3503}
3504
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003505PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003507 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003508{
3509 wchar_t smallbuf[256];
3510 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3511 wchar_t *wstr;
3512 size_t wlen, wlen2;
3513 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003514 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003515 size_t error_pos;
3516 char *errmsg;
3517 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003518
3519 if (locale_error_handler(errors, &surrogateescape) < 0)
3520 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003521
3522 if (str[len] != '\0' || len != strlen(str)) {
3523 PyErr_SetString(PyExc_TypeError, "embedded null character");
3524 return NULL;
3525 }
3526
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003527 if (surrogateescape) {
3528 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003529 wstr = _Py_char2wchar(str, &wlen);
3530 if (wstr == NULL) {
3531 if (wlen == (size_t)-1)
3532 PyErr_NoMemory();
3533 else
3534 PyErr_SetFromErrno(PyExc_OSError);
3535 return NULL;
3536 }
3537
3538 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003539 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003540 }
3541 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003542 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003543#ifndef HAVE_BROKEN_MBSTOWCS
3544 wlen = mbstowcs(NULL, str, 0);
3545#else
3546 wlen = len;
3547#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003548 if (wlen == (size_t)-1)
3549 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003550 if (wlen+1 <= smallbuf_len) {
3551 wstr = smallbuf;
3552 }
3553 else {
3554 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3555 return PyErr_NoMemory();
3556
3557 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3558 if (!wstr)
3559 return PyErr_NoMemory();
3560 }
3561
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003562 wlen2 = mbstowcs(wstr, str, wlen+1);
3563 if (wlen2 == (size_t)-1) {
3564 if (wstr != smallbuf)
3565 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003566 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003567 }
3568#ifdef HAVE_BROKEN_MBSTOWCS
3569 assert(wlen2 == wlen);
3570#endif
3571 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3572 if (wstr != smallbuf)
3573 PyMem_Free(wstr);
3574 }
3575 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003576
3577decode_error:
3578 errmsg = strerror(errno);
3579 assert(errmsg != NULL);
3580
3581 error_pos = mbstowcs_errorpos(str, len);
3582 if (errmsg != NULL) {
3583 size_t errlen;
3584 wstr = _Py_char2wchar(errmsg, &errlen);
3585 if (wstr != NULL) {
3586 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003587 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003588 } else
3589 errmsg = NULL;
3590 }
3591 if (errmsg == NULL)
3592 reason = PyUnicode_FromString(
3593 "mbstowcs() encountered an invalid multibyte sequence");
3594 if (reason == NULL)
3595 return NULL;
3596
3597 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3598 "locale", str, len,
3599 (Py_ssize_t)error_pos,
3600 (Py_ssize_t)(error_pos+1),
3601 reason);
3602 Py_DECREF(reason);
3603 if (exc != NULL) {
3604 PyCodec_StrictErrors(exc);
3605 Py_XDECREF(exc);
3606 }
3607 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003608}
3609
3610PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003611PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003612{
3613 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003614 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003615}
3616
3617
3618PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003619PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003621 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3622}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003623
Christian Heimes5894ba72007-11-04 11:43:14 +00003624PyObject*
3625PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3626{
Victor Stinner99b95382011-07-04 14:23:54 +02003627#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003628 return PyUnicode_DecodeMBCS(s, size, NULL);
3629#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003630 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003631#else
Victor Stinner793b5312011-04-27 00:24:21 +02003632 PyInterpreterState *interp = PyThreadState_GET()->interp;
3633 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3634 cannot use it to encode and decode filenames before it is loaded. Load
3635 the Python codec requires to encode at least its own filename. Use the C
3636 version of the locale codec until the codec registry is initialized and
3637 the Python codec is loaded.
3638
3639 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3640 cannot only rely on it: check also interp->fscodec_initialized for
3641 subinterpreters. */
3642 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003643 return PyUnicode_Decode(s, size,
3644 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003645 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003646 }
3647 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003648 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003649 }
Victor Stinnerad158722010-10-27 00:25:46 +00003650#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003651}
3652
Martin v. Löwis011e8422009-05-05 04:43:17 +00003653
3654int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003655_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003656{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003657 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003658
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003659 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003660 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003661 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3662 PyUnicode_GET_LENGTH(str), '\0', 1);
3663 if (pos == -1)
3664 return 0;
3665 else
3666 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003667}
3668
Antoine Pitrou13348842012-01-29 18:36:34 +01003669int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003670PyUnicode_FSConverter(PyObject* arg, void* addr)
3671{
3672 PyObject *output = NULL;
3673 Py_ssize_t size;
3674 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 if (arg == NULL) {
3676 Py_DECREF(*(PyObject**)addr);
3677 return 1;
3678 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003679 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003680 output = arg;
3681 Py_INCREF(output);
3682 }
3683 else {
3684 arg = PyUnicode_FromObject(arg);
3685 if (!arg)
3686 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003687 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003688 Py_DECREF(arg);
3689 if (!output)
3690 return 0;
3691 if (!PyBytes_Check(output)) {
3692 Py_DECREF(output);
3693 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3694 return 0;
3695 }
3696 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003697 size = PyBytes_GET_SIZE(output);
3698 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003699 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003700 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003701 Py_DECREF(output);
3702 return 0;
3703 }
3704 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003705 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003706}
3707
3708
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003709int
3710PyUnicode_FSDecoder(PyObject* arg, void* addr)
3711{
3712 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003713 if (arg == NULL) {
3714 Py_DECREF(*(PyObject**)addr);
3715 return 1;
3716 }
3717 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003718 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003720 output = arg;
3721 Py_INCREF(output);
3722 }
3723 else {
3724 arg = PyBytes_FromObject(arg);
3725 if (!arg)
3726 return 0;
3727 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3728 PyBytes_GET_SIZE(arg));
3729 Py_DECREF(arg);
3730 if (!output)
3731 return 0;
3732 if (!PyUnicode_Check(output)) {
3733 Py_DECREF(output);
3734 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3735 return 0;
3736 }
3737 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003738 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003739 Py_DECREF(output);
3740 return 0;
3741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003743 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003744 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3745 Py_DECREF(output);
3746 return 0;
3747 }
3748 *(PyObject**)addr = output;
3749 return Py_CLEANUP_SUPPORTED;
3750}
3751
3752
Martin v. Löwis5b222132007-06-10 09:51:05 +00003753char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003754PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003755{
Christian Heimesf3863112007-11-22 07:46:41 +00003756 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003757
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003758 if (!PyUnicode_Check(unicode)) {
3759 PyErr_BadArgument();
3760 return NULL;
3761 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003762 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003763 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003765 if (PyUnicode_UTF8(unicode) == NULL) {
3766 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3768 if (bytes == NULL)
3769 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003770 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3771 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003772 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773 Py_DECREF(bytes);
3774 return NULL;
3775 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3777 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3778 PyBytes_AS_STRING(bytes),
3779 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780 Py_DECREF(bytes);
3781 }
3782
3783 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003784 *psize = PyUnicode_UTF8_LENGTH(unicode);
3785 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003786}
3787
3788char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003790{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3792}
3793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003794Py_UNICODE *
3795PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003797 const unsigned char *one_byte;
3798#if SIZEOF_WCHAR_T == 4
3799 const Py_UCS2 *two_bytes;
3800#else
3801 const Py_UCS4 *four_bytes;
3802 const Py_UCS4 *ucs4_end;
3803 Py_ssize_t num_surrogates;
3804#endif
3805 wchar_t *w;
3806 wchar_t *wchar_end;
3807
3808 if (!PyUnicode_Check(unicode)) {
3809 PyErr_BadArgument();
3810 return NULL;
3811 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003812 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 assert(_PyUnicode_KIND(unicode) != 0);
3815 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003817 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003819 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3820 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003821 num_surrogates = 0;
3822
3823 for (; four_bytes < ucs4_end; ++four_bytes) {
3824 if (*four_bytes > 0xFFFF)
3825 ++num_surrogates;
3826 }
3827
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003828 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3829 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3830 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003831 PyErr_NoMemory();
3832 return NULL;
3833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003835
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003836 w = _PyUnicode_WSTR(unicode);
3837 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3838 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3840 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003841 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003843 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3844 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 }
3846 else
3847 *w = *four_bytes;
3848
3849 if (w > wchar_end) {
3850 assert(0 && "Miscalculated string end");
3851 }
3852 }
3853 *w = 0;
3854#else
3855 /* sizeof(wchar_t) == 4 */
3856 Py_FatalError("Impossible unicode object state, wstr and str "
3857 "should share memory already.");
3858 return NULL;
3859#endif
3860 }
3861 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003862 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3863 (_PyUnicode_LENGTH(unicode) + 1));
3864 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 PyErr_NoMemory();
3866 return NULL;
3867 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003868 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3869 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3870 w = _PyUnicode_WSTR(unicode);
3871 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3874 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 for (; w < wchar_end; ++one_byte, ++w)
3876 *w = *one_byte;
3877 /* null-terminate the wstr */
3878 *w = 0;
3879 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003880 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003883 for (; w < wchar_end; ++two_bytes, ++w)
3884 *w = *two_bytes;
3885 /* null-terminate the wstr */
3886 *w = 0;
3887#else
3888 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003889 PyObject_FREE(_PyUnicode_WSTR(unicode));
3890 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003891 Py_FatalError("Impossible unicode object state, wstr "
3892 "and str should share memory already.");
3893 return NULL;
3894#endif
3895 }
3896 else {
3897 assert(0 && "This should never happen.");
3898 }
3899 }
3900 }
3901 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003902 *size = PyUnicode_WSTR_LENGTH(unicode);
3903 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003904}
3905
Alexander Belopolsky40018472011-02-26 01:02:56 +00003906Py_UNICODE *
3907PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003910}
3911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912
Alexander Belopolsky40018472011-02-26 01:02:56 +00003913Py_ssize_t
3914PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003915{
3916 if (!PyUnicode_Check(unicode)) {
3917 PyErr_BadArgument();
3918 goto onError;
3919 }
3920 return PyUnicode_GET_SIZE(unicode);
3921
Benjamin Peterson29060642009-01-31 22:14:21 +00003922 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003923 return -1;
3924}
3925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926Py_ssize_t
3927PyUnicode_GetLength(PyObject *unicode)
3928{
Victor Stinner07621332012-06-16 04:53:46 +02003929 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 PyErr_BadArgument();
3931 return -1;
3932 }
Victor Stinner07621332012-06-16 04:53:46 +02003933 if (PyUnicode_READY(unicode) == -1)
3934 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935 return PyUnicode_GET_LENGTH(unicode);
3936}
3937
3938Py_UCS4
3939PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3940{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003941 void *data;
3942 int kind;
3943
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003944 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3945 PyErr_BadArgument();
3946 return (Py_UCS4)-1;
3947 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003948 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003949 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950 return (Py_UCS4)-1;
3951 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003952 data = PyUnicode_DATA(unicode);
3953 kind = PyUnicode_KIND(unicode);
3954 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955}
3956
3957int
3958PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3959{
3960 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003961 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962 return -1;
3963 }
Victor Stinner488fa492011-12-12 00:01:39 +01003964 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003965 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003966 PyErr_SetString(PyExc_IndexError, "string index out of range");
3967 return -1;
3968 }
Victor Stinner488fa492011-12-12 00:01:39 +01003969 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003970 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003971 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3972 PyErr_SetString(PyExc_ValueError, "character out of range");
3973 return -1;
3974 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3976 index, ch);
3977 return 0;
3978}
3979
Alexander Belopolsky40018472011-02-26 01:02:56 +00003980const char *
3981PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003982{
Victor Stinner42cb4622010-09-01 19:39:01 +00003983 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003984}
3985
Victor Stinner554f3f02010-06-16 23:33:54 +00003986/* create or adjust a UnicodeDecodeError */
3987static void
3988make_decode_exception(PyObject **exceptionObject,
3989 const char *encoding,
3990 const char *input, Py_ssize_t length,
3991 Py_ssize_t startpos, Py_ssize_t endpos,
3992 const char *reason)
3993{
3994 if (*exceptionObject == NULL) {
3995 *exceptionObject = PyUnicodeDecodeError_Create(
3996 encoding, input, length, startpos, endpos, reason);
3997 }
3998 else {
3999 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4000 goto onError;
4001 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4002 goto onError;
4003 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4004 goto onError;
4005 }
4006 return;
4007
4008onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004009 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004010}
4011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013/* error handling callback helper:
4014 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004015 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 and adjust various state variables.
4017 return 0 on success, -1 on error
4018*/
4019
Alexander Belopolsky40018472011-02-26 01:02:56 +00004020static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004021unicode_decode_call_errorhandler_wchar(
4022 const char *errors, PyObject **errorHandler,
4023 const char *encoding, const char *reason,
4024 const char **input, const char **inend, Py_ssize_t *startinpos,
4025 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4026 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004028 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029
4030 PyObject *restuple = NULL;
4031 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004032 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004033 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004034 Py_ssize_t requiredsize;
4035 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004036 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004037 wchar_t *repwstr;
4038 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004040 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4041 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004042
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004043 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 *errorHandler = PyCodec_LookupError(errors);
4045 if (*errorHandler == NULL)
4046 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004047 }
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049 make_decode_exception(exceptionObject,
4050 encoding,
4051 *input, *inend - *input,
4052 *startinpos, *endinpos,
4053 reason);
4054 if (*exceptionObject == NULL)
4055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056
4057 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4058 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004061 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004062 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 }
4064 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004066
4067 /* Copy back the bytes variables, which might have been modified by the
4068 callback */
4069 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4070 if (!inputobj)
4071 goto onError;
4072 if (!PyBytes_Check(inputobj)) {
4073 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4074 }
4075 *input = PyBytes_AS_STRING(inputobj);
4076 insize = PyBytes_GET_SIZE(inputobj);
4077 *inend = *input + insize;
4078 /* we can DECREF safely, as the exception has another reference,
4079 so the object won't go away. */
4080 Py_DECREF(inputobj);
4081
4082 if (newpos<0)
4083 newpos = insize+newpos;
4084 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004085 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 goto onError;
4087 }
4088
4089 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4090 if (repwstr == NULL)
4091 goto onError;
4092 /* need more space? (at least enough for what we
4093 have+the replacement+the rest of the string (starting
4094 at the new input position), so we won't have to check space
4095 when there are no errors in the rest of the string) */
4096 requiredsize = *outpos + repwlen + insize-newpos;
4097 if (requiredsize > outsize) {
4098 if (requiredsize < 2*outsize)
4099 requiredsize = 2*outsize;
4100 if (unicode_resize(output, requiredsize) < 0)
4101 goto onError;
4102 }
4103 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4104 *outpos += repwlen;
4105
4106 *endinpos = newpos;
4107 *inptr = *input + newpos;
4108
4109 /* we made it! */
4110 Py_XDECREF(restuple);
4111 return 0;
4112
4113 onError:
4114 Py_XDECREF(restuple);
4115 return -1;
4116}
4117#endif /* HAVE_MBCS */
4118
4119static int
4120unicode_decode_call_errorhandler_writer(
4121 const char *errors, PyObject **errorHandler,
4122 const char *encoding, const char *reason,
4123 const char **input, const char **inend, Py_ssize_t *startinpos,
4124 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4125 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4126{
4127 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4128
4129 PyObject *restuple = NULL;
4130 PyObject *repunicode = NULL;
4131 Py_ssize_t insize;
4132 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004133 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004134 PyObject *inputobj = NULL;
4135
4136 if (*errorHandler == NULL) {
4137 *errorHandler = PyCodec_LookupError(errors);
4138 if (*errorHandler == NULL)
4139 goto onError;
4140 }
4141
4142 make_decode_exception(exceptionObject,
4143 encoding,
4144 *input, *inend - *input,
4145 *startinpos, *endinpos,
4146 reason);
4147 if (*exceptionObject == NULL)
4148 goto onError;
4149
4150 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4151 if (restuple == NULL)
4152 goto onError;
4153 if (!PyTuple_Check(restuple)) {
4154 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4155 goto onError;
4156 }
4157 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004158 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004159
4160 /* Copy back the bytes variables, which might have been modified by the
4161 callback */
4162 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4163 if (!inputobj)
4164 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004165 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004166 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004168 *input = PyBytes_AS_STRING(inputobj);
4169 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004170 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004171 /* we can DECREF safely, as the exception has another reference,
4172 so the object won't go away. */
4173 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004174
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004175 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004176 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004177 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004178 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004179 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004180 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004181
Victor Stinner8f674cc2013-04-17 23:02:17 +02004182 if (PyUnicode_READY(repunicode) < 0)
4183 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004184 replen = PyUnicode_GET_LENGTH(repunicode);
4185 writer->min_length += replen;
4186 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004187 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004189 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004191 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004192 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004193
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004194 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004195 Py_XDECREF(restuple);
4196 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004197
Benjamin Peterson29060642009-01-31 22:14:21 +00004198 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004200 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201}
4202
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004203/* --- UTF-7 Codec -------------------------------------------------------- */
4204
Antoine Pitrou244651a2009-05-04 18:56:13 +00004205/* See RFC2152 for details. We encode conservatively and decode liberally. */
4206
4207/* Three simple macros defining base-64. */
4208
4209/* Is c a base-64 character? */
4210
4211#define IS_BASE64(c) \
4212 (((c) >= 'A' && (c) <= 'Z') || \
4213 ((c) >= 'a' && (c) <= 'z') || \
4214 ((c) >= '0' && (c) <= '9') || \
4215 (c) == '+' || (c) == '/')
4216
4217/* given that c is a base-64 character, what is its base-64 value? */
4218
4219#define FROM_BASE64(c) \
4220 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4221 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4222 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4223 (c) == '+' ? 62 : 63)
4224
4225/* What is the base-64 character of the bottom 6 bits of n? */
4226
4227#define TO_BASE64(n) \
4228 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4229
4230/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4231 * decoded as itself. We are permissive on decoding; the only ASCII
4232 * byte not decoding to itself is the + which begins a base64
4233 * string. */
4234
4235#define DECODE_DIRECT(c) \
4236 ((c) <= 127 && (c) != '+')
4237
4238/* The UTF-7 encoder treats ASCII characters differently according to
4239 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4240 * the above). See RFC2152. This array identifies these different
4241 * sets:
4242 * 0 : "Set D"
4243 * alphanumeric and '(),-./:?
4244 * 1 : "Set O"
4245 * !"#$%&*;<=>@[]^_`{|}
4246 * 2 : "whitespace"
4247 * ht nl cr sp
4248 * 3 : special (must be base64 encoded)
4249 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4250 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004251
Tim Petersced69f82003-09-16 20:30:58 +00004252static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253char utf7_category[128] = {
4254/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4255 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4256/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4257 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4258/* sp ! " # $ % & ' ( ) * + , - . / */
4259 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4260/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4261 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4262/* @ A B C D E F G H I J K L M N O */
4263 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4264/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4265 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4266/* ` a b c d e f g h i j k l m n o */
4267 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4268/* p q r s t u v w x y z { | } ~ del */
4269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004270};
4271
Antoine Pitrou244651a2009-05-04 18:56:13 +00004272/* ENCODE_DIRECT: this character should be encoded as itself. The
4273 * answer depends on whether we are encoding set O as itself, and also
4274 * on whether we are encoding whitespace as itself. RFC2152 makes it
4275 * clear that the answers to these questions vary between
4276 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004277
Antoine Pitrou244651a2009-05-04 18:56:13 +00004278#define ENCODE_DIRECT(c, directO, directWS) \
4279 ((c) < 128 && (c) > 0 && \
4280 ((utf7_category[(c)] == 0) || \
4281 (directWS && (utf7_category[(c)] == 2)) || \
4282 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283
Alexander Belopolsky40018472011-02-26 01:02:56 +00004284PyObject *
4285PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004286 Py_ssize_t size,
4287 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004288{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4290}
4291
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292/* The decoder. The only state we preserve is our read position,
4293 * i.e. how many characters we have consumed. So if we end in the
4294 * middle of a shift sequence we have to back off the read position
4295 * and the output to the beginning of the sequence, otherwise we lose
4296 * all the shift state (seen bits, number of bits seen, high
4297 * surrogate). */
4298
Alexander Belopolsky40018472011-02-26 01:02:56 +00004299PyObject *
4300PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004301 Py_ssize_t size,
4302 const char *errors,
4303 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004304{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004305 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t startinpos;
4307 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004310 const char *errmsg = "";
4311 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004312 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313 unsigned int base64bits = 0;
4314 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004315 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 PyObject *errorHandler = NULL;
4317 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004319 if (size == 0) {
4320 if (consumed)
4321 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004322 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004323 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004326 _PyUnicodeWriter_Init(&writer);
4327 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328
4329 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 e = s + size;
4331
4332 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004335 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 if (inShift) { /* in a base-64 section */
4338 if (IS_BASE64(ch)) { /* consume a base-64 character */
4339 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4340 base64bits += 6;
4341 s++;
4342 if (base64bits >= 16) {
4343 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004344 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 base64bits -= 16;
4346 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004347 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 if (surrogate) {
4349 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004350 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4351 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004352 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004353 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004355 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 }
4357 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004358 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004359 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004360 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 }
4362 }
Victor Stinner551ac952011-11-29 22:58:13 +01004363 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 /* first surrogate */
4365 surrogate = outCh;
4366 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004368 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 }
4372 }
4373 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004374 inShift = 0;
4375 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004377 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004378 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004379 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 if (base64bits > 0) { /* left-over bits */
4382 if (base64bits >= 6) {
4383 /* We've seen at least one base-64 character */
4384 errmsg = "partial character in shift sequence";
4385 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004387 else {
4388 /* Some bits remain; they should be zero */
4389 if (base64buffer != 0) {
4390 errmsg = "non-zero padding bits in shift sequence";
4391 goto utf7Error;
4392 }
4393 }
4394 }
4395 if (ch != '-') {
4396 /* '-' is absorbed; other terminating
4397 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004398 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004399 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
4402 }
4403 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004404 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004405 s++; /* consume '+' */
4406 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004408 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004410 }
4411 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004412 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004413 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004415 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
4417 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004419 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004420 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004422 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 else {
4424 startinpos = s-starts;
4425 s++;
4426 errmsg = "unexpected special character";
4427 goto utf7Error;
4428 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 errors, &errorHandler,
4434 "utf7", errmsg,
4435 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* end of string */
4441
4442 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4443 /* if we're in an inconsistent state, that's an error */
4444 if (surrogate ||
4445 (base64bits >= 6) ||
4446 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004447 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004448 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 errors, &errorHandler,
4450 "utf7", "unterminated shift sequence",
4451 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004452 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 goto onError;
4454 if (s < e)
4455 goto restart;
4456 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458
4459 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004460 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004462 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004463 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004464 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004465 writer.kind, writer.data, shiftOutStart);
4466 Py_XDECREF(errorHandler);
4467 Py_XDECREF(exc);
4468 _PyUnicodeWriter_Dealloc(&writer);
4469 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004470 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004471 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 }
4473 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004474 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004476 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004478 Py_XDECREF(errorHandler);
4479 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004480 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481
Benjamin Peterson29060642009-01-31 22:14:21 +00004482 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004483 Py_XDECREF(errorHandler);
4484 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004485 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486 return NULL;
4487}
4488
4489
Alexander Belopolsky40018472011-02-26 01:02:56 +00004490PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491_PyUnicode_EncodeUTF7(PyObject *str,
4492 int base64SetO,
4493 int base64WhiteSpace,
4494 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004496 int kind;
4497 void *data;
4498 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004499 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004501 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502 unsigned int base64bits = 0;
4503 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504 char * out;
4505 char * start;
4506
Benjamin Petersonbac79492012-01-14 13:34:47 -05004507 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004508 return NULL;
4509 kind = PyUnicode_KIND(str);
4510 data = PyUnicode_DATA(str);
4511 len = PyUnicode_GET_LENGTH(str);
4512
4513 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004514 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004517 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004518 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004519 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520 if (v == NULL)
4521 return NULL;
4522
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004523 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004524 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004525 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 if (inShift) {
4528 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4529 /* shifting out */
4530 if (base64bits) { /* output remaining bits */
4531 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4532 base64buffer = 0;
4533 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534 }
4535 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536 /* Characters not in the BASE64 set implicitly unshift the sequence
4537 so no '-' is required, except if the character is itself a '-' */
4538 if (IS_BASE64(ch) || ch == '-') {
4539 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004541 *out++ = (char) ch;
4542 }
4543 else {
4544 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004545 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 else { /* not in a shift sequence */
4548 if (ch == '+') {
4549 *out++ = '+';
4550 *out++ = '-';
4551 }
4552 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4553 *out++ = (char) ch;
4554 }
4555 else {
4556 *out++ = '+';
4557 inShift = 1;
4558 goto encode_char;
4559 }
4560 }
4561 continue;
4562encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004563 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004564 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 /* code first surrogate */
4567 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004568 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004569 while (base64bits >= 6) {
4570 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4571 base64bits -= 6;
4572 }
4573 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004574 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 base64bits += 16;
4577 base64buffer = (base64buffer << 16) | ch;
4578 while (base64bits >= 6) {
4579 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4580 base64bits -= 6;
4581 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004582 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 if (base64bits)
4584 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4585 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004586 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004587 if (_PyBytes_Resize(&v, out - start) < 0)
4588 return NULL;
4589 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004590}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004591PyObject *
4592PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4593 Py_ssize_t size,
4594 int base64SetO,
4595 int base64WhiteSpace,
4596 const char *errors)
4597{
4598 PyObject *result;
4599 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4600 if (tmp == NULL)
4601 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004602 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004603 base64WhiteSpace, errors);
4604 Py_DECREF(tmp);
4605 return result;
4606}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004607
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608#undef IS_BASE64
4609#undef FROM_BASE64
4610#undef TO_BASE64
4611#undef DECODE_DIRECT
4612#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004613
Guido van Rossumd57fd912000-03-10 22:53:23 +00004614/* --- UTF-8 Codec -------------------------------------------------------- */
4615
Alexander Belopolsky40018472011-02-26 01:02:56 +00004616PyObject *
4617PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004618 Py_ssize_t size,
4619 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004620{
Walter Dörwald69652032004-09-07 20:24:22 +00004621 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4622}
4623
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004624#include "stringlib/asciilib.h"
4625#include "stringlib/codecs.h"
4626#include "stringlib/undef.h"
4627
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004628#include "stringlib/ucs1lib.h"
4629#include "stringlib/codecs.h"
4630#include "stringlib/undef.h"
4631
4632#include "stringlib/ucs2lib.h"
4633#include "stringlib/codecs.h"
4634#include "stringlib/undef.h"
4635
4636#include "stringlib/ucs4lib.h"
4637#include "stringlib/codecs.h"
4638#include "stringlib/undef.h"
4639
Antoine Pitrouab868312009-01-10 15:40:25 +00004640/* Mask to quickly check whether a C 'long' contains a
4641 non-ASCII, UTF8-encoded char. */
4642#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004643# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004644#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004645# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004646#else
4647# error C 'long' size should be either 4 or 8!
4648#endif
4649
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004650static Py_ssize_t
4651ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004652{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004653 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004654 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004656 /*
4657 * Issue #17237: m68k is a bit different from most architectures in
4658 * that objects do not use "natural alignment" - for example, int and
4659 * long are only aligned at 2-byte boundaries. Therefore the assert()
4660 * won't work; also, tests have shown that skipping the "optimised
4661 * version" will even speed up m68k.
4662 */
4663#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004665 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4666 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 /* Fast path, see in STRINGLIB(utf8_decode) for
4668 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004669 /* Help allocation */
4670 const char *_p = p;
4671 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672 while (_p < aligned_end) {
4673 unsigned long value = *(const unsigned long *) _p;
4674 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004675 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 *((unsigned long *)q) = value;
4677 _p += SIZEOF_LONG;
4678 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004679 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 p = _p;
4681 while (p < end) {
4682 if ((unsigned char)*p & 0x80)
4683 break;
4684 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004686 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004689#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004690 while (p < end) {
4691 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4692 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004693 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004694 /* Help allocation */
4695 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696 while (_p < aligned_end) {
4697 unsigned long value = *(unsigned long *) _p;
4698 if (value & ASCII_CHAR_MASK)
4699 break;
4700 _p += SIZEOF_LONG;
4701 }
4702 p = _p;
4703 if (_p == end)
4704 break;
4705 }
4706 if ((unsigned char)*p & 0x80)
4707 break;
4708 ++p;
4709 }
4710 memcpy(dest, start, p - start);
4711 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004712}
Antoine Pitrouab868312009-01-10 15:40:25 +00004713
Victor Stinner785938e2011-12-11 20:09:03 +01004714PyObject *
4715PyUnicode_DecodeUTF8Stateful(const char *s,
4716 Py_ssize_t size,
4717 const char *errors,
4718 Py_ssize_t *consumed)
4719{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004720 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004721 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004722 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004723
4724 Py_ssize_t startinpos;
4725 Py_ssize_t endinpos;
4726 const char *errmsg = "";
4727 PyObject *errorHandler = NULL;
4728 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004729
4730 if (size == 0) {
4731 if (consumed)
4732 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004733 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004734 }
4735
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004736 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4737 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004738 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004739 *consumed = 1;
4740 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004741 }
4742
Victor Stinner8f674cc2013-04-17 23:02:17 +02004743 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004744 writer.min_length = size;
4745 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004746 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004747
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004748 writer.pos = ascii_decode(s, end, writer.data);
4749 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 while (s < end) {
4751 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004752 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 if (PyUnicode_IS_ASCII(writer.buffer))
4755 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004756 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004757 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004759 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004760 } else {
4761 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 }
4764
4765 switch (ch) {
4766 case 0:
4767 if (s == end || consumed)
4768 goto End;
4769 errmsg = "unexpected end of data";
4770 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004771 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 break;
4773 case 1:
4774 errmsg = "invalid start byte";
4775 startinpos = s - starts;
4776 endinpos = startinpos + 1;
4777 break;
4778 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004779 case 3:
4780 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004781 errmsg = "invalid continuation byte";
4782 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004783 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784 break;
4785 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004786 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004787 goto onError;
4788 continue;
4789 }
4790
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004791 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 errors, &errorHandler,
4793 "utf-8", errmsg,
4794 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004795 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004797 }
4798
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 if (consumed)
4801 *consumed = s - starts;
4802
4803 Py_XDECREF(errorHandler);
4804 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004805 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806
4807onError:
4808 Py_XDECREF(errorHandler);
4809 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004810 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004812}
4813
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004814#ifdef __APPLE__
4815
4816/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004817 used to decode the command line arguments on Mac OS X.
4818
4819 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004820 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004821
4822wchar_t*
4823_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4824{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826 wchar_t *unicode;
4827 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004828
4829 /* Note: size will always be longer than the resulting Unicode
4830 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004831 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004833 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 if (!unicode)
4835 return NULL;
4836
4837 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004841 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004844#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 if (ch > 0xFF) {
4848#if SIZEOF_WCHAR_T == 4
4849 assert(0);
4850#else
4851 assert(Py_UNICODE_IS_SURROGATE(ch));
4852 /* compute and append the two surrogates: */
4853 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4854 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4855#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004856 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004857 else {
4858 if (!ch && s == e)
4859 break;
4860 /* surrogateescape */
4861 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4862 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004863 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 return unicode;
4866}
4867
4868#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004870/* Primary internal function which creates utf8 encoded bytes objects.
4871
4872 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004873 and allocate exactly as much space needed at the end. Else allocate the
4874 maximum possible needed (4 result bytes per Unicode character), and return
4875 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004876*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004877PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004878_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879{
Victor Stinner6099a032011-12-18 14:22:26 +01004880 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881 void *data;
4882 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884 if (!PyUnicode_Check(unicode)) {
4885 PyErr_BadArgument();
4886 return NULL;
4887 }
4888
4889 if (PyUnicode_READY(unicode) == -1)
4890 return NULL;
4891
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004892 if (PyUnicode_UTF8(unicode))
4893 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4894 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004895
4896 kind = PyUnicode_KIND(unicode);
4897 data = PyUnicode_DATA(unicode);
4898 size = PyUnicode_GET_LENGTH(unicode);
4899
Benjamin Petersonead6b532011-12-20 17:23:42 -06004900 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004901 default:
4902 assert(0);
4903 case PyUnicode_1BYTE_KIND:
4904 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4905 assert(!PyUnicode_IS_ASCII(unicode));
4906 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4907 case PyUnicode_2BYTE_KIND:
4908 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4909 case PyUnicode_4BYTE_KIND:
4910 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004911 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004912}
4913
Alexander Belopolsky40018472011-02-26 01:02:56 +00004914PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004915PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4916 Py_ssize_t size,
4917 const char *errors)
4918{
4919 PyObject *v, *unicode;
4920
4921 unicode = PyUnicode_FromUnicode(s, size);
4922 if (unicode == NULL)
4923 return NULL;
4924 v = _PyUnicode_AsUTF8String(unicode, errors);
4925 Py_DECREF(unicode);
4926 return v;
4927}
4928
4929PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004930PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004931{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004932 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933}
4934
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935/* --- UTF-32 Codec ------------------------------------------------------- */
4936
4937PyObject *
4938PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004939 Py_ssize_t size,
4940 const char *errors,
4941 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942{
4943 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4944}
4945
4946PyObject *
4947PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004948 Py_ssize_t size,
4949 const char *errors,
4950 int *byteorder,
4951 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004952{
4953 const char *starts = s;
4954 Py_ssize_t startinpos;
4955 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004956 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004957 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004958 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004959 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961 PyObject *errorHandler = NULL;
4962 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004963
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964 q = (unsigned char *)s;
4965 e = q + size;
4966
4967 if (byteorder)
4968 bo = *byteorder;
4969
4970 /* Check for BOM marks (U+FEFF) in the input and adjust current
4971 byte order setting accordingly. In native mode, the leading BOM
4972 mark is skipped, in all other modes, it is copied to the output
4973 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004974 if (bo == 0 && size >= 4) {
4975 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4976 if (bom == 0x0000FEFF) {
4977 bo = -1;
4978 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004979 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004980 else if (bom == 0xFFFE0000) {
4981 bo = 1;
4982 q += 4;
4983 }
4984 if (byteorder)
4985 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986 }
4987
Victor Stinnere64322e2012-10-30 23:12:47 +01004988 if (q == e) {
4989 if (consumed)
4990 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004991 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992 }
4993
Victor Stinnere64322e2012-10-30 23:12:47 +01004994#ifdef WORDS_BIGENDIAN
4995 le = bo < 0;
4996#else
4997 le = bo <= 0;
4998#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004999 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005000
Victor Stinner8f674cc2013-04-17 23:02:17 +02005001 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005002 writer.min_length = (e - q + 3) / 4;
5003 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005004 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005005
Victor Stinnere64322e2012-10-30 23:12:47 +01005006 while (1) {
5007 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005009
Victor Stinnere64322e2012-10-30 23:12:47 +01005010 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005011 enum PyUnicode_Kind kind = writer.kind;
5012 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005013 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005014 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005015 if (le) {
5016 do {
5017 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5018 if (ch > maxch)
5019 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005020 if (kind != PyUnicode_1BYTE_KIND &&
5021 Py_UNICODE_IS_SURROGATE(ch))
5022 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005023 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 q += 4;
5025 } while (q <= last);
5026 }
5027 else {
5028 do {
5029 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5030 if (ch > maxch)
5031 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005032 if (kind != PyUnicode_1BYTE_KIND &&
5033 Py_UNICODE_IS_SURROGATE(ch))
5034 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005036 q += 4;
5037 } while (q <= last);
5038 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005039 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005040 }
5041
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005042 if (Py_UNICODE_IS_SURROGATE(ch)) {
5043 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5044 startinpos = ((const char *)q) - starts;
5045 endinpos = startinpos + 4;
5046 }
5047 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005050 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005052 startinpos = ((const char *)q) - starts;
5053 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005054 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005055 else {
5056 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005057 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005058 goto onError;
5059 q += 4;
5060 continue;
5061 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005063 startinpos = ((const char *)q) - starts;
5064 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005066
5067 /* The remaining input chars are ignored if the callback
5068 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005069 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005070 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005071 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005073 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005074 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 }
5076
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080 Py_XDECREF(errorHandler);
5081 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005082 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005085 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 Py_XDECREF(errorHandler);
5087 Py_XDECREF(exc);
5088 return NULL;
5089}
5090
5091PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005092_PyUnicode_EncodeUTF32(PyObject *str,
5093 const char *errors,
5094 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005096 int kind;
5097 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005099 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005100 unsigned char *p;
5101 Py_ssize_t nsize, i;
5102 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005103#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005106 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005108 const char *encoding;
5109 PyObject *errorHandler = NULL;
5110 PyObject *exc = NULL;
5111 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112
Serhiy Storchaka30793282014-01-04 22:44:01 +02005113#define STORECHAR(CH) \
5114 do { \
5115 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5116 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5117 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5118 p[iorder[0]] = (CH) & 0xff; \
5119 p += 4; \
5120 } while(0)
5121
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005122 if (!PyUnicode_Check(str)) {
5123 PyErr_BadArgument();
5124 return NULL;
5125 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005126 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005127 return NULL;
5128 kind = PyUnicode_KIND(str);
5129 data = PyUnicode_DATA(str);
5130 len = PyUnicode_GET_LENGTH(str);
5131
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005132 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005133 if (nsize > PY_SSIZE_T_MAX / 4)
5134 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005135 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136 if (v == NULL)
5137 return NULL;
5138
Serhiy Storchaka30793282014-01-04 22:44:01 +02005139 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005140 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005142 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005143 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144
Serhiy Storchaka30793282014-01-04 22:44:01 +02005145 if (byteorder == -1) {
5146 /* force LE */
5147 iorder[0] = 0;
5148 iorder[1] = 1;
5149 iorder[2] = 2;
5150 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005151 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005152 }
5153 else if (byteorder == 1) {
5154 /* force BE */
5155 iorder[0] = 3;
5156 iorder[1] = 2;
5157 iorder[2] = 1;
5158 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005159 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005160 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005161 else
5162 encoding = "utf-32";
5163
5164 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005165 for (i = 0; i < len; i++)
5166 STORECHAR(PyUnicode_READ(kind, data, i));
5167 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005168 }
5169
Serhiy Storchaka30793282014-01-04 22:44:01 +02005170 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005171 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005172 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5173 i++;
5174 assert(ch <= MAX_UNICODE);
5175 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5176 STORECHAR(ch);
5177 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005178 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005179
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005180 rep = unicode_encode_call_errorhandler(
5181 errors, &errorHandler,
5182 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005183 str, &exc, i-1, i, &i);
5184
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005185 if (!rep)
5186 goto error;
5187
5188 if (PyBytes_Check(rep)) {
5189 repsize = PyBytes_GET_SIZE(rep);
5190 if (repsize & 3) {
5191 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005192 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 "surrogates not allowed");
5194 goto error;
5195 }
5196 moreunits = repsize / 4;
5197 }
5198 else {
5199 assert(PyUnicode_Check(rep));
5200 if (PyUnicode_READY(rep) < 0)
5201 goto error;
5202 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5203 if (!PyUnicode_IS_ASCII(rep)) {
5204 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005205 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005206 "surrogates not allowed");
5207 goto error;
5208 }
5209 }
5210
5211 /* four bytes are reserved for each surrogate */
5212 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005213 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005214 Py_ssize_t morebytes = 4 * (moreunits - 1);
5215 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5216 /* integer overflow */
5217 PyErr_NoMemory();
5218 goto error;
5219 }
5220 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5221 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005222 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005223 }
5224
5225 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005226 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5227 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005228 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005229 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005230 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005231 repdata = PyUnicode_1BYTE_DATA(rep);
5232 while (repsize--) {
5233 Py_UCS4 ch = *repdata++;
5234 STORECHAR(ch);
5235 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005236 }
5237
5238 Py_CLEAR(rep);
5239 }
5240
5241 /* Cut back to size actually needed. This is necessary for, for example,
5242 encoding of a string containing isolated surrogates and the 'ignore'
5243 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005244 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005245 if (nsize != PyBytes_GET_SIZE(v))
5246 _PyBytes_Resize(&v, nsize);
5247 Py_XDECREF(errorHandler);
5248 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005249 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005250 error:
5251 Py_XDECREF(rep);
5252 Py_XDECREF(errorHandler);
5253 Py_XDECREF(exc);
5254 Py_XDECREF(v);
5255 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005256#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257}
5258
Alexander Belopolsky40018472011-02-26 01:02:56 +00005259PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005260PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5261 Py_ssize_t size,
5262 const char *errors,
5263 int byteorder)
5264{
5265 PyObject *result;
5266 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5267 if (tmp == NULL)
5268 return NULL;
5269 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5270 Py_DECREF(tmp);
5271 return result;
5272}
5273
5274PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005275PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
Victor Stinnerb960b342011-11-20 19:12:52 +01005277 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005278}
5279
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280/* --- UTF-16 Codec ------------------------------------------------------- */
5281
Tim Peters772747b2001-08-09 22:21:55 +00005282PyObject *
5283PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005284 Py_ssize_t size,
5285 const char *errors,
5286 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005287{
Walter Dörwald69652032004-09-07 20:24:22 +00005288 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5289}
5290
5291PyObject *
5292PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005293 Py_ssize_t size,
5294 const char *errors,
5295 int *byteorder,
5296 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005297{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005298 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005299 Py_ssize_t startinpos;
5300 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005302 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005303 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005304 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005305 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005306 PyObject *errorHandler = NULL;
5307 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005308 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005309
Tim Peters772747b2001-08-09 22:21:55 +00005310 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005311 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005312
5313 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005314 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005315
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005316 /* Check for BOM marks (U+FEFF) in the input and adjust current
5317 byte order setting accordingly. In native mode, the leading BOM
5318 mark is skipped, in all other modes, it is copied to the output
5319 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005320 if (bo == 0 && size >= 2) {
5321 const Py_UCS4 bom = (q[1] << 8) | q[0];
5322 if (bom == 0xFEFF) {
5323 q += 2;
5324 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 else if (bom == 0xFFFE) {
5327 q += 2;
5328 bo = 1;
5329 }
5330 if (byteorder)
5331 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005332 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005333
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 if (q == e) {
5335 if (consumed)
5336 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005337 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005338 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005339
Christian Heimes743e0cd2012-10-17 23:52:17 +02005340#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005341 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005342 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005343#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005344 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005345 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005346#endif
Tim Peters772747b2001-08-09 22:21:55 +00005347
Antoine Pitrou63065d72012-05-15 23:48:04 +02005348 /* Note: size will always be longer than the resulting Unicode
5349 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005350 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005351 writer.min_length = (e - q + 1) / 2;
5352 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005354
Antoine Pitrou63065d72012-05-15 23:48:04 +02005355 while (1) {
5356 Py_UCS4 ch = 0;
5357 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005358 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005359 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005360 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005361 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 native_ordering);
5364 else
5365 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 native_ordering);
5368 } else if (kind == PyUnicode_2BYTE_KIND) {
5369 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005370 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 native_ordering);
5372 } else {
5373 assert(kind == PyUnicode_4BYTE_KIND);
5374 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005375 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005376 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005377 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005378 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005379
Antoine Pitrou63065d72012-05-15 23:48:04 +02005380 switch (ch)
5381 {
5382 case 0:
5383 /* remaining byte at the end? (size should be even) */
5384 if (q == e || consumed)
5385 goto End;
5386 errmsg = "truncated data";
5387 startinpos = ((const char *)q) - starts;
5388 endinpos = ((const char *)e) - starts;
5389 break;
5390 /* The remaining input chars are ignored if the callback
5391 chooses to skip the input */
5392 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005393 q -= 2;
5394 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005395 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005396 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005397 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005398 endinpos = ((const char *)e) - starts;
5399 break;
5400 case 2:
5401 errmsg = "illegal encoding";
5402 startinpos = ((const char *)q) - 2 - starts;
5403 endinpos = startinpos + 2;
5404 break;
5405 case 3:
5406 errmsg = "illegal UTF-16 surrogate";
5407 startinpos = ((const char *)q) - 4 - starts;
5408 endinpos = startinpos + 2;
5409 break;
5410 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005411 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005412 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 continue;
5414 }
5415
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005416 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005417 errors,
5418 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005419 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005420 &starts,
5421 (const char **)&e,
5422 &startinpos,
5423 &endinpos,
5424 &exc,
5425 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005426 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005427 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 }
5429
Antoine Pitrou63065d72012-05-15 23:48:04 +02005430End:
Walter Dörwald69652032004-09-07 20:24:22 +00005431 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005433
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 Py_XDECREF(errorHandler);
5435 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005436 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005439 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005440 Py_XDECREF(errorHandler);
5441 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442 return NULL;
5443}
5444
Tim Peters772747b2001-08-09 22:21:55 +00005445PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005446_PyUnicode_EncodeUTF16(PyObject *str,
5447 const char *errors,
5448 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005449{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005450 enum PyUnicode_Kind kind;
5451 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005452 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005453 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005454 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005455 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005456#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005457 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005458#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005460#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005461 const char *encoding;
5462 Py_ssize_t nsize, pos;
5463 PyObject *errorHandler = NULL;
5464 PyObject *exc = NULL;
5465 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005466
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005467 if (!PyUnicode_Check(str)) {
5468 PyErr_BadArgument();
5469 return NULL;
5470 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005471 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005472 return NULL;
5473 kind = PyUnicode_KIND(str);
5474 data = PyUnicode_DATA(str);
5475 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005476
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005477 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005478 if (kind == PyUnicode_4BYTE_KIND) {
5479 const Py_UCS4 *in = (const Py_UCS4 *)data;
5480 const Py_UCS4 *end = in + len;
5481 while (in < end)
5482 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005483 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005484 }
5485 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005486 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 nsize = len + pairs + (byteorder == 0);
5488 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489 if (v == NULL)
5490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005492 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005493 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005494 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005496 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005497 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005498 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005499
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005500 if (kind == PyUnicode_1BYTE_KIND) {
5501 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5502 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005503 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005504
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005505 if (byteorder < 0)
5506 encoding = "utf-16-le";
5507 else if (byteorder > 0)
5508 encoding = "utf-16-be";
5509 else
5510 encoding = "utf-16";
5511
5512 pos = 0;
5513 while (pos < len) {
5514 Py_ssize_t repsize, moreunits;
5515
5516 if (kind == PyUnicode_2BYTE_KIND) {
5517 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5518 &out, native_ordering);
5519 }
5520 else {
5521 assert(kind == PyUnicode_4BYTE_KIND);
5522 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5523 &out, native_ordering);
5524 }
5525 if (pos == len)
5526 break;
5527
5528 rep = unicode_encode_call_errorhandler(
5529 errors, &errorHandler,
5530 encoding, "surrogates not allowed",
5531 str, &exc, pos, pos + 1, &pos);
5532 if (!rep)
5533 goto error;
5534
5535 if (PyBytes_Check(rep)) {
5536 repsize = PyBytes_GET_SIZE(rep);
5537 if (repsize & 1) {
5538 raise_encode_exception(&exc, encoding,
5539 str, pos - 1, pos,
5540 "surrogates not allowed");
5541 goto error;
5542 }
5543 moreunits = repsize / 2;
5544 }
5545 else {
5546 assert(PyUnicode_Check(rep));
5547 if (PyUnicode_READY(rep) < 0)
5548 goto error;
5549 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5550 if (!PyUnicode_IS_ASCII(rep)) {
5551 raise_encode_exception(&exc, encoding,
5552 str, pos - 1, pos,
5553 "surrogates not allowed");
5554 goto error;
5555 }
5556 }
5557
5558 /* two bytes are reserved for each surrogate */
5559 if (moreunits > 1) {
5560 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5561 Py_ssize_t morebytes = 2 * (moreunits - 1);
5562 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5563 /* integer overflow */
5564 PyErr_NoMemory();
5565 goto error;
5566 }
5567 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5568 goto error;
5569 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5570 }
5571
5572 if (PyBytes_Check(rep)) {
5573 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5574 out += moreunits;
5575 } else /* rep is unicode */ {
5576 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5577 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5578 &out, native_ordering);
5579 }
5580
5581 Py_CLEAR(rep);
5582 }
5583
5584 /* Cut back to size actually needed. This is necessary for, for example,
5585 encoding of a string containing isolated surrogates and the 'ignore' handler
5586 is used. */
5587 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5588 if (nsize != PyBytes_GET_SIZE(v))
5589 _PyBytes_Resize(&v, nsize);
5590 Py_XDECREF(errorHandler);
5591 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005592 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005593 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005594 error:
5595 Py_XDECREF(rep);
5596 Py_XDECREF(errorHandler);
5597 Py_XDECREF(exc);
5598 Py_XDECREF(v);
5599 return NULL;
5600#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601}
5602
Alexander Belopolsky40018472011-02-26 01:02:56 +00005603PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005604PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5605 Py_ssize_t size,
5606 const char *errors,
5607 int byteorder)
5608{
5609 PyObject *result;
5610 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5611 if (tmp == NULL)
5612 return NULL;
5613 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5614 Py_DECREF(tmp);
5615 return result;
5616}
5617
5618PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005619PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005621 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622}
5623
5624/* --- Unicode Escape Codec ----------------------------------------------- */
5625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005626/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5627 if all the escapes in the string make it still a valid ASCII string.
5628 Returns -1 if any escapes were found which cause the string to
5629 pop out of ASCII range. Otherwise returns the length of the
5630 required buffer to hold the string.
5631 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005632static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005633length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5634{
5635 const unsigned char *p = (const unsigned char *)s;
5636 const unsigned char *end = p + size;
5637 Py_ssize_t length = 0;
5638
5639 if (size < 0)
5640 return -1;
5641
5642 for (; p < end; ++p) {
5643 if (*p > 127) {
5644 /* Non-ASCII */
5645 return -1;
5646 }
5647 else if (*p != '\\') {
5648 /* Normal character */
5649 ++length;
5650 }
5651 else {
5652 /* Backslash-escape, check next char */
5653 ++p;
5654 /* Escape sequence reaches till end of string or
5655 non-ASCII follow-up. */
5656 if (p >= end || *p > 127)
5657 return -1;
5658 switch (*p) {
5659 case '\n':
5660 /* backslash + \n result in zero characters */
5661 break;
5662 case '\\': case '\'': case '\"':
5663 case 'b': case 'f': case 't':
5664 case 'n': case 'r': case 'v': case 'a':
5665 ++length;
5666 break;
5667 case '0': case '1': case '2': case '3':
5668 case '4': case '5': case '6': case '7':
5669 case 'x': case 'u': case 'U': case 'N':
5670 /* these do not guarantee ASCII characters */
5671 return -1;
5672 default:
5673 /* count the backslash + the other character */
5674 length += 2;
5675 }
5676 }
5677 }
5678 return length;
5679}
5680
Fredrik Lundh06d12682001-01-24 07:59:11 +00005681static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005682
Alexander Belopolsky40018472011-02-26 01:02:56 +00005683PyObject *
5684PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005685 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005686 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005688 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005689 Py_ssize_t startinpos;
5690 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005693 char* message;
5694 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005695 PyObject *errorHandler = NULL;
5696 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005697 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005698
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005699 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005700 if (len == 0)
5701 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005702
5703 /* After length_of_escaped_ascii_string() there are two alternatives,
5704 either the string is pure ASCII with named escapes like \n, etc.
5705 and we determined it's exact size (common case)
5706 or it contains \x, \u, ... escape sequences. then we create a
5707 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005708 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005709 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005710 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711 }
5712 else {
5713 /* Escaped strings will always be longer than the resulting
5714 Unicode string, so we start with size here and then reduce the
5715 length after conversion to the true value.
5716 (but if the error callback returns a long replacement string
5717 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005718 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005719 }
5720
Guido van Rossumd57fd912000-03-10 22:53:23 +00005721 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005722 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005724
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 while (s < end) {
5726 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005727 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005728 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729
5730 /* Non-escape characters are interpreted as Unicode ordinals */
5731 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005732 x = (unsigned char)*s;
5733 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005734 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005735 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 continue;
5737 }
5738
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005739 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 /* \ - Escapes */
5741 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005742 c = *s++;
5743 if (s > end)
5744 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005745
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005746 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005749#define WRITECHAR(ch) \
5750 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005751 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005752 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005753 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005754
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005756 case '\\': WRITECHAR('\\'); break;
5757 case '\'': WRITECHAR('\''); break;
5758 case '\"': WRITECHAR('\"'); break;
5759 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005761 case 'f': WRITECHAR('\014'); break;
5762 case 't': WRITECHAR('\t'); break;
5763 case 'n': WRITECHAR('\n'); break;
5764 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005765 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005766 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005768 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005769
Benjamin Peterson29060642009-01-31 22:14:21 +00005770 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771 case '0': case '1': case '2': case '3':
5772 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005773 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005774 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005775 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005776 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005777 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005779 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 break;
5781
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 /* hex escapes */
5783 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005785 digits = 2;
5786 message = "truncated \\xXX escape";
5787 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005788
Benjamin Peterson29060642009-01-31 22:14:21 +00005789 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005791 digits = 4;
5792 message = "truncated \\uXXXX escape";
5793 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794
Benjamin Peterson29060642009-01-31 22:14:21 +00005795 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005796 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 digits = 8;
5798 message = "truncated \\UXXXXXXXX escape";
5799 hexescape:
5800 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005801 if (end - s < digits) {
5802 /* count only hex digits */
5803 for (; s < end; ++s) {
5804 c = (unsigned char)*s;
5805 if (!Py_ISXDIGIT(c))
5806 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005807 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005808 goto error;
5809 }
5810 for (; digits--; ++s) {
5811 c = (unsigned char)*s;
5812 if (!Py_ISXDIGIT(c))
5813 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005814 chr = (chr<<4) & ~0xF;
5815 if (c >= '0' && c <= '9')
5816 chr += c - '0';
5817 else if (c >= 'a' && c <= 'f')
5818 chr += 10 + c - 'a';
5819 else
5820 chr += 10 + c - 'A';
5821 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005822 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005823 /* _decoding_error will have already written into the
5824 target buffer. */
5825 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005826 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005827 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005828 message = "illegal Unicode character";
5829 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005831 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005832 break;
5833
Benjamin Peterson29060642009-01-31 22:14:21 +00005834 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005835 case 'N':
5836 message = "malformed \\N character escape";
5837 if (ucnhash_CAPI == NULL) {
5838 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005839 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5840 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005841 if (ucnhash_CAPI == NULL)
5842 goto ucnhashError;
5843 }
5844 if (*s == '{') {
5845 const char *start = s+1;
5846 /* look for the closing brace */
5847 while (*s != '}' && s < end)
5848 s++;
5849 if (s > start && s < end && *s == '}') {
5850 /* found a name. look it up in the unicode database */
5851 message = "unknown Unicode character name";
5852 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005853 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005854 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005855 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005856 goto store;
5857 }
5858 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005859 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860
5861 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005862 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 message = "\\ at end of string";
5864 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005865 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005866 }
5867 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005868 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005869 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005871 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005873 continue;
5874
5875 error:
5876 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005877 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005878 errors, &errorHandler,
5879 "unicodeescape", message,
5880 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005881 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005882 goto onError;
5883 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005885#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005887 Py_XDECREF(errorHandler);
5888 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005889 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005890
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005892 PyErr_SetString(
5893 PyExc_UnicodeError,
5894 "\\N escapes not supported (can't load unicodedata module)"
5895 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005896 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005897 Py_XDECREF(errorHandler);
5898 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005899 return NULL;
5900
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005902 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005903 Py_XDECREF(errorHandler);
5904 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 return NULL;
5906}
5907
5908/* Return a Unicode-Escape string version of the Unicode object.
5909
5910 If quotes is true, the string is enclosed in u"" or u'' quotes as
5911 appropriate.
5912
5913*/
5914
Alexander Belopolsky40018472011-02-26 01:02:56 +00005915PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005918 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005919 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 int kind;
5922 void *data;
5923 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924
Ezio Melottie7f90372012-10-05 03:33:31 +03005925 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005926 escape.
5927
Ezio Melottie7f90372012-10-05 03:33:31 +03005928 For UCS1 strings it's '\xxx', 4 bytes per source character.
5929 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5930 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005931 */
5932
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005933 if (!PyUnicode_Check(unicode)) {
5934 PyErr_BadArgument();
5935 return NULL;
5936 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005937 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005938 return NULL;
5939 len = PyUnicode_GET_LENGTH(unicode);
5940 kind = PyUnicode_KIND(unicode);
5941 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005942 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005943 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5944 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5945 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5946 }
5947
5948 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005949 return PyBytes_FromStringAndSize(NULL, 0);
5950
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005953
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005954 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005955 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005956 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958 if (repr == NULL)
5959 return NULL;
5960
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005961 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005963 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005964 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005965
Walter Dörwald79e913e2007-05-12 11:08:06 +00005966 /* Escape backslashes */
5967 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 *p++ = '\\';
5969 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005970 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005971 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005972
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005973 /* Map 21-bit characters to '\U00xxxxxx' */
5974 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005975 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005976 *p++ = '\\';
5977 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005978 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5979 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5980 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5981 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5982 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5983 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5984 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5985 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005987 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005988
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005990 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991 *p++ = '\\';
5992 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005993 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5994 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5995 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5996 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005998
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005999 /* Map special whitespace to '\t', \n', '\r' */
6000 else if (ch == '\t') {
6001 *p++ = '\\';
6002 *p++ = 't';
6003 }
6004 else if (ch == '\n') {
6005 *p++ = '\\';
6006 *p++ = 'n';
6007 }
6008 else if (ch == '\r') {
6009 *p++ = '\\';
6010 *p++ = 'r';
6011 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006012
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006013 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006014 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006016 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006017 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6018 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006019 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006020
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021 /* Copy everything else as-is */
6022 else
6023 *p++ = (char) ch;
6024 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006026 assert(p - PyBytes_AS_STRING(repr) > 0);
6027 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6028 return NULL;
6029 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030}
6031
Alexander Belopolsky40018472011-02-26 01:02:56 +00006032PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006033PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6034 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 PyObject *result;
6037 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6038 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006040 result = PyUnicode_AsUnicodeEscapeString(tmp);
6041 Py_DECREF(tmp);
6042 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043}
6044
6045/* --- Raw Unicode Escape Codec ------------------------------------------- */
6046
Alexander Belopolsky40018472011-02-26 01:02:56 +00006047PyObject *
6048PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006049 Py_ssize_t size,
6050 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006052 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006053 Py_ssize_t startinpos;
6054 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006055 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056 const char *end;
6057 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006058 PyObject *errorHandler = NULL;
6059 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006060
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006061 if (size == 0)
6062 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006063
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 /* Escaped strings will always be longer than the resulting
6065 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006066 length after conversion to the true value. (But decoding error
6067 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006068 _PyUnicodeWriter_Init(&writer);
6069 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006070
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071 end = s + size;
6072 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 unsigned char c;
6074 Py_UCS4 x;
6075 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006076 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 /* Non-escape characters are interpreted as Unicode ordinals */
6079 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006080 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006081 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006082 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006084 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 startinpos = s-starts;
6086
6087 /* \u-escapes are only interpreted iff the number of leading
6088 backslashes if odd */
6089 bs = s;
6090 for (;s < end;) {
6091 if (*s != '\\')
6092 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006093 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006094 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006095 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006096 }
6097 if (((s - bs) & 1) == 0 ||
6098 s >= end ||
6099 (*s != 'u' && *s != 'U')) {
6100 continue;
6101 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006102 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 count = *s=='u' ? 4 : 8;
6104 s++;
6105
6106 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 for (x = 0, i = 0; i < count; ++i, ++s) {
6108 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006109 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006111 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 errors, &errorHandler,
6113 "rawunicodeescape", "truncated \\uXXXX",
6114 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006115 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 goto onError;
6117 goto nextByte;
6118 }
6119 x = (x<<4) & ~0xF;
6120 if (c >= '0' && c <= '9')
6121 x += c - '0';
6122 else if (c >= 'a' && c <= 'f')
6123 x += 10 + c - 'a';
6124 else
6125 x += 10 + c - 'A';
6126 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006127 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006128 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006129 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006130 }
6131 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006132 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006133 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006134 errors, &errorHandler,
6135 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006136 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006137 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006139 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 nextByte:
6141 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006142 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006143 Py_XDECREF(errorHandler);
6144 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006145 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006146
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006148 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006149 Py_XDECREF(errorHandler);
6150 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 return NULL;
6152}
6153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154
Alexander Belopolsky40018472011-02-26 01:02:56 +00006155PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006158 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 char *p;
6160 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006161 Py_ssize_t expandsize, pos;
6162 int kind;
6163 void *data;
6164 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166 if (!PyUnicode_Check(unicode)) {
6167 PyErr_BadArgument();
6168 return NULL;
6169 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006170 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 return NULL;
6172 kind = PyUnicode_KIND(unicode);
6173 data = PyUnicode_DATA(unicode);
6174 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006175 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6176 bytes, and 1 byte characters 4. */
6177 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006178
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006181
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006182 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183 if (repr == NULL)
6184 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006185 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006186 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006188 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 for (pos = 0; pos < len; pos++) {
6190 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 /* Map 32-bit characters to '\Uxxxxxxxx' */
6192 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006193 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006194 *p++ = '\\';
6195 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006196 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6197 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6198 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6199 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6200 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6201 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6202 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6203 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006204 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207 *p++ = '\\';
6208 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006209 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6211 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6212 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006214 /* Copy everything else as-is */
6215 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 *p++ = (char) ch;
6217 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006218
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219 assert(p > q);
6220 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006221 return NULL;
6222 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006223}
6224
Alexander Belopolsky40018472011-02-26 01:02:56 +00006225PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6227 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229 PyObject *result;
6230 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6231 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006232 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006233 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6234 Py_DECREF(tmp);
6235 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236}
6237
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006238/* --- Unicode Internal Codec ------------------------------------------- */
6239
Alexander Belopolsky40018472011-02-26 01:02:56 +00006240PyObject *
6241_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006242 Py_ssize_t size,
6243 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006244{
6245 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006246 Py_ssize_t startinpos;
6247 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006248 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006249 const char *end;
6250 const char *reason;
6251 PyObject *errorHandler = NULL;
6252 PyObject *exc = NULL;
6253
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006254 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006255 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006256 1))
6257 return NULL;
6258
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006259 if (size == 0)
6260 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006261
Victor Stinner8f674cc2013-04-17 23:02:17 +02006262 _PyUnicodeWriter_Init(&writer);
6263 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6264 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006266 }
6267 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006268
Victor Stinner8f674cc2013-04-17 23:02:17 +02006269 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006271 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006272 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006273 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006274 endinpos = end-starts;
6275 reason = "truncated input";
6276 goto error;
6277 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006278 /* We copy the raw representation one byte at a time because the
6279 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006280 ((char *) &uch)[0] = s[0];
6281 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006282#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006283 ((char *) &uch)[2] = s[2];
6284 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006285#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006286 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006287#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006288 /* We have to sanity check the raw data, otherwise doom looms for
6289 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006290 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006291 endinpos = s - starts + Py_UNICODE_SIZE;
6292 reason = "illegal code point (> 0x10FFFF)";
6293 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006294 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006296 s += Py_UNICODE_SIZE;
6297#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006298 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006299 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006300 Py_UNICODE uch2;
6301 ((char *) &uch2)[0] = s[0];
6302 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006303 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006304 {
Victor Stinner551ac952011-11-29 22:58:13 +01006305 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006306 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006307 }
6308 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006309#endif
6310
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006311 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006313 continue;
6314
6315 error:
6316 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006317 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006318 errors, &errorHandler,
6319 "unicode_internal", reason,
6320 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006321 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006322 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323 }
6324
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006325 Py_XDECREF(errorHandler);
6326 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006327 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328
Benjamin Peterson29060642009-01-31 22:14:21 +00006329 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006330 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331 Py_XDECREF(errorHandler);
6332 Py_XDECREF(exc);
6333 return NULL;
6334}
6335
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336/* --- Latin-1 Codec ------------------------------------------------------ */
6337
Alexander Belopolsky40018472011-02-26 01:02:56 +00006338PyObject *
6339PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006340 Py_ssize_t size,
6341 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006344 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345}
6346
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006347/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006348static void
6349make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006350 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006351 PyObject *unicode,
6352 Py_ssize_t startpos, Py_ssize_t endpos,
6353 const char *reason)
6354{
6355 if (*exceptionObject == NULL) {
6356 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006357 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006358 encoding, unicode, startpos, endpos, reason);
6359 }
6360 else {
6361 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6362 goto onError;
6363 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6364 goto onError;
6365 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6366 goto onError;
6367 return;
6368 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006369 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006370 }
6371}
6372
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006374static void
6375raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006376 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006377 PyObject *unicode,
6378 Py_ssize_t startpos, Py_ssize_t endpos,
6379 const char *reason)
6380{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006381 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006382 encoding, unicode, startpos, endpos, reason);
6383 if (*exceptionObject != NULL)
6384 PyCodec_StrictErrors(*exceptionObject);
6385}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386
6387/* error handling callback helper:
6388 build arguments, call the callback and check the arguments,
6389 put the result into newpos and return the replacement string, which
6390 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391static PyObject *
6392unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006393 PyObject **errorHandler,
6394 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006395 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006396 Py_ssize_t startpos, Py_ssize_t endpos,
6397 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006399 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006400 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006401 PyObject *restuple;
6402 PyObject *resunicode;
6403
6404 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408 }
6409
Benjamin Petersonbac79492012-01-14 13:34:47 -05006410 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 return NULL;
6412 len = PyUnicode_GET_LENGTH(unicode);
6413
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006414 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418
6419 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006421 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006424 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 Py_DECREF(restuple);
6426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006428 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 &resunicode, newpos)) {
6430 Py_DECREF(restuple);
6431 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006433 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6434 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6435 Py_DECREF(restuple);
6436 return NULL;
6437 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 *newpos = len + *newpos;
6440 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006441 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006442 Py_DECREF(restuple);
6443 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006444 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 Py_INCREF(resunicode);
6446 Py_DECREF(restuple);
6447 return resunicode;
6448}
6449
Alexander Belopolsky40018472011-02-26 01:02:56 +00006450static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006452 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006453 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 /* input state */
6456 Py_ssize_t pos=0, size;
6457 int kind;
6458 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459 /* output object */
6460 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461 /* pointer into the output */
6462 char *str;
6463 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006464 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006465 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6466 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 PyObject *errorHandler = NULL;
6468 PyObject *exc = NULL;
6469 /* the following variable is used for caching string comparisons
6470 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6471 int known_errorHandler = -1;
6472
Benjamin Petersonbac79492012-01-14 13:34:47 -05006473 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 return NULL;
6475 size = PyUnicode_GET_LENGTH(unicode);
6476 kind = PyUnicode_KIND(unicode);
6477 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478 /* allocate enough for a simple encoding without
6479 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006480 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006481 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006482 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006484 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006485 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 ressize = size;
6487
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006488 while (pos < size) {
6489 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490
Benjamin Peterson29060642009-01-31 22:14:21 +00006491 /* can we encode this? */
6492 if (c<limit) {
6493 /* no overflow check, because we know that the space is enough */
6494 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006496 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 Py_ssize_t requiredsize;
6499 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006500 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 Py_ssize_t collstart = pos;
6503 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 ++collend;
6507 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6508 if (known_errorHandler==-1) {
6509 if ((errors==NULL) || (!strcmp(errors, "strict")))
6510 known_errorHandler = 1;
6511 else if (!strcmp(errors, "replace"))
6512 known_errorHandler = 2;
6513 else if (!strcmp(errors, "ignore"))
6514 known_errorHandler = 3;
6515 else if (!strcmp(errors, "xmlcharrefreplace"))
6516 known_errorHandler = 4;
6517 else
6518 known_errorHandler = 0;
6519 }
6520 switch (known_errorHandler) {
6521 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006522 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 goto onError;
6524 case 2: /* replace */
6525 while (collstart++<collend)
6526 *str++ = '?'; /* fall through */
6527 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006528 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 break;
6530 case 4: /* xmlcharrefreplace */
6531 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006532 /* determine replacement size */
6533 for (i = collstart, repsize = 0; i < collend; ++i) {
6534 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6535 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006537 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006547 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006548 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006550 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006552 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 if (requiredsize > ressize) {
6554 if (requiredsize<2*ressize)
6555 requiredsize = 2*ressize;
6556 if (_PyBytes_Resize(&res, requiredsize))
6557 goto onError;
6558 str = PyBytes_AS_STRING(res) + respos;
6559 ressize = requiredsize;
6560 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006561 /* generate replacement */
6562 for (i = collstart; i < collend; ++i) {
6563 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006565 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 break;
6567 default:
6568 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006569 encoding, reason, unicode, &exc,
6570 collstart, collend, &newpos);
6571 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006572 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006574 if (PyBytes_Check(repunicode)) {
6575 /* Directly copy bytes result to output. */
6576 repsize = PyBytes_Size(repunicode);
6577 if (repsize > 1) {
6578 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006579 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006580 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6581 Py_DECREF(repunicode);
6582 goto onError;
6583 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006584 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006585 ressize += repsize-1;
6586 }
6587 memcpy(str, PyBytes_AsString(repunicode), repsize);
6588 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006589 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006590 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006591 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006592 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 /* need more space? (at least enough for what we
6594 have+the replacement+the rest of the string, so
6595 we won't have to check space for encodable characters) */
6596 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006597 repsize = PyUnicode_GET_LENGTH(repunicode);
6598 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 if (requiredsize > ressize) {
6600 if (requiredsize<2*ressize)
6601 requiredsize = 2*ressize;
6602 if (_PyBytes_Resize(&res, requiredsize)) {
6603 Py_DECREF(repunicode);
6604 goto onError;
6605 }
6606 str = PyBytes_AS_STRING(res) + respos;
6607 ressize = requiredsize;
6608 }
6609 /* check if there is anything unencodable in the replacement
6610 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 for (i = 0; repsize-->0; ++i, ++str) {
6612 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006614 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006615 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006616 Py_DECREF(repunicode);
6617 goto onError;
6618 }
6619 *str = (char)c;
6620 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006622 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006624 }
6625 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006626 /* Resize if we allocated to much */
6627 size = str - PyBytes_AS_STRING(res);
6628 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006629 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006630 if (_PyBytes_Resize(&res, size) < 0)
6631 goto onError;
6632 }
6633
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 Py_XDECREF(errorHandler);
6635 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006636 return res;
6637
6638 onError:
6639 Py_XDECREF(res);
6640 Py_XDECREF(errorHandler);
6641 Py_XDECREF(exc);
6642 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006643}
6644
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006646PyObject *
6647PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006648 Py_ssize_t size,
6649 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 PyObject *result;
6652 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6653 if (unicode == NULL)
6654 return NULL;
6655 result = unicode_encode_ucs1(unicode, errors, 256);
6656 Py_DECREF(unicode);
6657 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658}
6659
Alexander Belopolsky40018472011-02-26 01:02:56 +00006660PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006661_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006662{
6663 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 PyErr_BadArgument();
6665 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006666 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006667 if (PyUnicode_READY(unicode) == -1)
6668 return NULL;
6669 /* Fast path: if it is a one-byte string, construct
6670 bytes object directly. */
6671 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6672 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6673 PyUnicode_GET_LENGTH(unicode));
6674 /* Non-Latin-1 characters present. Defer to above function to
6675 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006676 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006677}
6678
6679PyObject*
6680PyUnicode_AsLatin1String(PyObject *unicode)
6681{
6682 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006683}
6684
6685/* --- 7-bit ASCII Codec -------------------------------------------------- */
6686
Alexander Belopolsky40018472011-02-26 01:02:56 +00006687PyObject *
6688PyUnicode_DecodeASCII(const char *s,
6689 Py_ssize_t size,
6690 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006693 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006694 int kind;
6695 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006696 Py_ssize_t startinpos;
6697 Py_ssize_t endinpos;
6698 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 const char *e;
6700 PyObject *errorHandler = NULL;
6701 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006702
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006704 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006705
Guido van Rossumd57fd912000-03-10 22:53:23 +00006706 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006707 if (size == 1 && (unsigned char)s[0] < 128)
6708 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006709
Victor Stinner8f674cc2013-04-17 23:02:17 +02006710 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006711 writer.min_length = size;
6712 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006713 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006714
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006715 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006716 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006717 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006718 writer.pos = outpos;
6719 if (writer.pos == size)
6720 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006721
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006722 s += writer.pos;
6723 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006724 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006725 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006727 PyUnicode_WRITE(kind, data, writer.pos, c);
6728 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 ++s;
6730 }
6731 else {
6732 startinpos = s-starts;
6733 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006734 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 errors, &errorHandler,
6736 "ascii", "ordinal not in range(128)",
6737 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006738 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006740 kind = writer.kind;
6741 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 Py_XDECREF(errorHandler);
6745 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006746 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006747
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006749 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006750 Py_XDECREF(errorHandler);
6751 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752 return NULL;
6753}
6754
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006756PyObject *
6757PyUnicode_EncodeASCII(const Py_UNICODE *p,
6758 Py_ssize_t size,
6759 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006761 PyObject *result;
6762 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6763 if (unicode == NULL)
6764 return NULL;
6765 result = unicode_encode_ucs1(unicode, errors, 128);
6766 Py_DECREF(unicode);
6767 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768}
6769
Alexander Belopolsky40018472011-02-26 01:02:56 +00006770PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006771_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772{
6773 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 PyErr_BadArgument();
6775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777 if (PyUnicode_READY(unicode) == -1)
6778 return NULL;
6779 /* Fast path: if it is an ASCII-only string, construct bytes object
6780 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006781 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006782 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6783 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006785}
6786
6787PyObject *
6788PyUnicode_AsASCIIString(PyObject *unicode)
6789{
6790 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791}
6792
Victor Stinner99b95382011-07-04 14:23:54 +02006793#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006794
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006795/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006796
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006797#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006798#define NEED_RETRY
6799#endif
6800
Victor Stinner3a50e702011-10-18 21:21:00 +02006801#ifndef WC_ERR_INVALID_CHARS
6802# define WC_ERR_INVALID_CHARS 0x0080
6803#endif
6804
6805static char*
6806code_page_name(UINT code_page, PyObject **obj)
6807{
6808 *obj = NULL;
6809 if (code_page == CP_ACP)
6810 return "mbcs";
6811 if (code_page == CP_UTF7)
6812 return "CP_UTF7";
6813 if (code_page == CP_UTF8)
6814 return "CP_UTF8";
6815
6816 *obj = PyBytes_FromFormat("cp%u", code_page);
6817 if (*obj == NULL)
6818 return NULL;
6819 return PyBytes_AS_STRING(*obj);
6820}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006821
Alexander Belopolsky40018472011-02-26 01:02:56 +00006822static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006823is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006824{
6825 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006826 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827
Victor Stinner3a50e702011-10-18 21:21:00 +02006828 if (!IsDBCSLeadByteEx(code_page, *curr))
6829 return 0;
6830
6831 prev = CharPrevExA(code_page, s, curr, 0);
6832 if (prev == curr)
6833 return 1;
6834 /* FIXME: This code is limited to "true" double-byte encodings,
6835 as it assumes an incomplete character consists of a single
6836 byte. */
6837 if (curr - prev == 2)
6838 return 1;
6839 if (!IsDBCSLeadByteEx(code_page, *prev))
6840 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006841 return 0;
6842}
6843
Victor Stinner3a50e702011-10-18 21:21:00 +02006844static DWORD
6845decode_code_page_flags(UINT code_page)
6846{
6847 if (code_page == CP_UTF7) {
6848 /* The CP_UTF7 decoder only supports flags=0 */
6849 return 0;
6850 }
6851 else
6852 return MB_ERR_INVALID_CHARS;
6853}
6854
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006856 * Decode a byte string from a Windows code page into unicode object in strict
6857 * mode.
6858 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006859 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6860 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006861 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006862static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006863decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006864 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 const char *in,
6866 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006867{
Victor Stinner3a50e702011-10-18 21:21:00 +02006868 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006869 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006870 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871
6872 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006873 assert(insize > 0);
6874 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6875 if (outsize <= 0)
6876 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006877
6878 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006880 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006881 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 if (*v == NULL)
6883 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006885 }
6886 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006887 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006888 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006889 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006890 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006891 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006892 }
6893
6894 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006895 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6896 if (outsize <= 0)
6897 goto error;
6898 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006899
Victor Stinner3a50e702011-10-18 21:21:00 +02006900error:
6901 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6902 return -2;
6903 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006904 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006905}
6906
Victor Stinner3a50e702011-10-18 21:21:00 +02006907/*
6908 * Decode a byte string from a code page into unicode object with an error
6909 * handler.
6910 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006911 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006912 * UnicodeDecodeError exception and returns -1 on error.
6913 */
6914static int
6915decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006916 PyObject **v,
6917 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006918 const char *errors)
6919{
6920 const char *startin = in;
6921 const char *endin = in + size;
6922 const DWORD flags = decode_code_page_flags(code_page);
6923 /* Ideally, we should get reason from FormatMessage. This is the Windows
6924 2000 English version of the message. */
6925 const char *reason = "No mapping for the Unicode character exists "
6926 "in the target code page.";
6927 /* each step cannot decode more than 1 character, but a character can be
6928 represented as a surrogate pair */
6929 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006930 int insize;
6931 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006932 PyObject *errorHandler = NULL;
6933 PyObject *exc = NULL;
6934 PyObject *encoding_obj = NULL;
6935 char *encoding;
6936 DWORD err;
6937 int ret = -1;
6938
6939 assert(size > 0);
6940
6941 encoding = code_page_name(code_page, &encoding_obj);
6942 if (encoding == NULL)
6943 return -1;
6944
6945 if (errors == NULL || strcmp(errors, "strict") == 0) {
6946 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6947 UnicodeDecodeError. */
6948 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6949 if (exc != NULL) {
6950 PyCodec_StrictErrors(exc);
6951 Py_CLEAR(exc);
6952 }
6953 goto error;
6954 }
6955
6956 if (*v == NULL) {
6957 /* Create unicode object */
6958 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6959 PyErr_NoMemory();
6960 goto error;
6961 }
Victor Stinnerab595942011-12-17 04:59:06 +01006962 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006963 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006964 if (*v == NULL)
6965 goto error;
6966 startout = PyUnicode_AS_UNICODE(*v);
6967 }
6968 else {
6969 /* Extend unicode object */
6970 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6971 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6972 PyErr_NoMemory();
6973 goto error;
6974 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006975 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006976 goto error;
6977 startout = PyUnicode_AS_UNICODE(*v) + n;
6978 }
6979
6980 /* Decode the byte string character per character */
6981 out = startout;
6982 while (in < endin)
6983 {
6984 /* Decode a character */
6985 insize = 1;
6986 do
6987 {
6988 outsize = MultiByteToWideChar(code_page, flags,
6989 in, insize,
6990 buffer, Py_ARRAY_LENGTH(buffer));
6991 if (outsize > 0)
6992 break;
6993 err = GetLastError();
6994 if (err != ERROR_NO_UNICODE_TRANSLATION
6995 && err != ERROR_INSUFFICIENT_BUFFER)
6996 {
6997 PyErr_SetFromWindowsErr(0);
6998 goto error;
6999 }
7000 insize++;
7001 }
7002 /* 4=maximum length of a UTF-8 sequence */
7003 while (insize <= 4 && (in + insize) <= endin);
7004
7005 if (outsize <= 0) {
7006 Py_ssize_t startinpos, endinpos, outpos;
7007
7008 startinpos = in - startin;
7009 endinpos = startinpos + 1;
7010 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007011 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007012 errors, &errorHandler,
7013 encoding, reason,
7014 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007015 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007016 {
7017 goto error;
7018 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007019 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007020 }
7021 else {
7022 in += insize;
7023 memcpy(out, buffer, outsize * sizeof(wchar_t));
7024 out += outsize;
7025 }
7026 }
7027
7028 /* write a NUL character at the end */
7029 *out = 0;
7030
7031 /* Extend unicode object */
7032 outsize = out - startout;
7033 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007034 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007036 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007037
7038error:
7039 Py_XDECREF(encoding_obj);
7040 Py_XDECREF(errorHandler);
7041 Py_XDECREF(exc);
7042 return ret;
7043}
7044
Victor Stinner3a50e702011-10-18 21:21:00 +02007045static PyObject *
7046decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007047 const char *s, Py_ssize_t size,
7048 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049{
Victor Stinner76a31a62011-11-04 00:05:13 +01007050 PyObject *v = NULL;
7051 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052
Victor Stinner3a50e702011-10-18 21:21:00 +02007053 if (code_page < 0) {
7054 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7055 return NULL;
7056 }
7057
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007058 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007059 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060
Victor Stinner76a31a62011-11-04 00:05:13 +01007061 do
7062 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007064 if (size > INT_MAX) {
7065 chunk_size = INT_MAX;
7066 final = 0;
7067 done = 0;
7068 }
7069 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007070#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007071 {
7072 chunk_size = (int)size;
7073 final = (consumed == NULL);
7074 done = 1;
7075 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007076
Victor Stinner76a31a62011-11-04 00:05:13 +01007077 /* Skip trailing lead-byte unless 'final' is set */
7078 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7079 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080
Victor Stinner76a31a62011-11-04 00:05:13 +01007081 if (chunk_size == 0 && done) {
7082 if (v != NULL)
7083 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007084 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007085 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
Victor Stinner76a31a62011-11-04 00:05:13 +01007087
7088 converted = decode_code_page_strict(code_page, &v,
7089 s, chunk_size);
7090 if (converted == -2)
7091 converted = decode_code_page_errors(code_page, &v,
7092 s, chunk_size,
7093 errors);
7094 assert(converted != 0);
7095
7096 if (converted < 0) {
7097 Py_XDECREF(v);
7098 return NULL;
7099 }
7100
7101 if (consumed)
7102 *consumed += converted;
7103
7104 s += converted;
7105 size -= converted;
7106 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007107
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007108 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109}
7110
Alexander Belopolsky40018472011-02-26 01:02:56 +00007111PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007112PyUnicode_DecodeCodePageStateful(int code_page,
7113 const char *s,
7114 Py_ssize_t size,
7115 const char *errors,
7116 Py_ssize_t *consumed)
7117{
7118 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7119}
7120
7121PyObject *
7122PyUnicode_DecodeMBCSStateful(const char *s,
7123 Py_ssize_t size,
7124 const char *errors,
7125 Py_ssize_t *consumed)
7126{
7127 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7128}
7129
7130PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007131PyUnicode_DecodeMBCS(const char *s,
7132 Py_ssize_t size,
7133 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007134{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007135 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7136}
7137
Victor Stinner3a50e702011-10-18 21:21:00 +02007138static DWORD
7139encode_code_page_flags(UINT code_page, const char *errors)
7140{
7141 if (code_page == CP_UTF8) {
7142 if (winver.dwMajorVersion >= 6)
7143 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7144 and later */
7145 return WC_ERR_INVALID_CHARS;
7146 else
7147 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7148 return 0;
7149 }
7150 else if (code_page == CP_UTF7) {
7151 /* CP_UTF7 only supports flags=0 */
7152 return 0;
7153 }
7154 else {
7155 if (errors != NULL && strcmp(errors, "replace") == 0)
7156 return 0;
7157 else
7158 return WC_NO_BEST_FIT_CHARS;
7159 }
7160}
7161
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007162/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 * Encode a Unicode string to a Windows code page into a byte string in strict
7164 * mode.
7165 *
7166 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007167 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007168 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007169static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007170encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007171 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007172 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007173{
Victor Stinner554f3f02010-06-16 23:33:54 +00007174 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 BOOL *pusedDefaultChar = &usedDefaultChar;
7176 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007177 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007178 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007179 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 const DWORD flags = encode_code_page_flags(code_page, NULL);
7181 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007182 /* Create a substring so that we can get the UTF-16 representation
7183 of just the slice under consideration. */
7184 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007185
Martin v. Löwis3d325192011-11-04 18:23:06 +01007186 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007187
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007189 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007191 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007192
Victor Stinner2fc507f2011-11-04 20:06:39 +01007193 substring = PyUnicode_Substring(unicode, offset, offset+len);
7194 if (substring == NULL)
7195 return -1;
7196 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7197 if (p == NULL) {
7198 Py_DECREF(substring);
7199 return -1;
7200 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007201 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007202
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007203 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007205 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 NULL, 0,
7207 NULL, pusedDefaultChar);
7208 if (outsize <= 0)
7209 goto error;
7210 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 if (pusedDefaultChar && *pusedDefaultChar) {
7212 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007213 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007215
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007217 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007219 if (*outbytes == NULL) {
7220 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007221 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007224 }
7225 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007226 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 const Py_ssize_t n = PyBytes_Size(*outbytes);
7228 if (outsize > PY_SSIZE_T_MAX - n) {
7229 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007230 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007231 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007233 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7234 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238 }
7239
7240 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007242 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 out, outsize,
7244 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007245 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 if (outsize <= 0)
7247 goto error;
7248 if (pusedDefaultChar && *pusedDefaultChar)
7249 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007250 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007251
Victor Stinner3a50e702011-10-18 21:21:00 +02007252error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007253 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007254 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7255 return -2;
7256 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007257 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007258}
7259
Victor Stinner3a50e702011-10-18 21:21:00 +02007260/*
7261 * Encode a Unicode string to a Windows code page into a byte string using a
7262 * error handler.
7263 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007264 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 * -1 on other error.
7266 */
7267static int
7268encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007269 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007270 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007271{
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007273 Py_ssize_t pos = unicode_offset;
7274 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 /* Ideally, we should get reason from FormatMessage. This is the Windows
7276 2000 English version of the message. */
7277 const char *reason = "invalid character";
7278 /* 4=maximum length of a UTF-8 sequence */
7279 char buffer[4];
7280 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7281 Py_ssize_t outsize;
7282 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 PyObject *errorHandler = NULL;
7284 PyObject *exc = NULL;
7285 PyObject *encoding_obj = NULL;
7286 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007287 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007288 PyObject *rep;
7289 int ret = -1;
7290
7291 assert(insize > 0);
7292
7293 encoding = code_page_name(code_page, &encoding_obj);
7294 if (encoding == NULL)
7295 return -1;
7296
7297 if (errors == NULL || strcmp(errors, "strict") == 0) {
7298 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7299 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007300 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 if (exc != NULL) {
7302 PyCodec_StrictErrors(exc);
7303 Py_DECREF(exc);
7304 }
7305 Py_XDECREF(encoding_obj);
7306 return -1;
7307 }
7308
7309 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7310 pusedDefaultChar = &usedDefaultChar;
7311 else
7312 pusedDefaultChar = NULL;
7313
7314 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7315 PyErr_NoMemory();
7316 goto error;
7317 }
7318 outsize = insize * Py_ARRAY_LENGTH(buffer);
7319
7320 if (*outbytes == NULL) {
7321 /* Create string object */
7322 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7323 if (*outbytes == NULL)
7324 goto error;
7325 out = PyBytes_AS_STRING(*outbytes);
7326 }
7327 else {
7328 /* Extend string object */
7329 Py_ssize_t n = PyBytes_Size(*outbytes);
7330 if (n > PY_SSIZE_T_MAX - outsize) {
7331 PyErr_NoMemory();
7332 goto error;
7333 }
7334 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7335 goto error;
7336 out = PyBytes_AS_STRING(*outbytes) + n;
7337 }
7338
7339 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007342 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7343 wchar_t chars[2];
7344 int charsize;
7345 if (ch < 0x10000) {
7346 chars[0] = (wchar_t)ch;
7347 charsize = 1;
7348 }
7349 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007350 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7351 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007352 charsize = 2;
7353 }
7354
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007356 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007357 buffer, Py_ARRAY_LENGTH(buffer),
7358 NULL, pusedDefaultChar);
7359 if (outsize > 0) {
7360 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7361 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007362 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007363 memcpy(out, buffer, outsize);
7364 out += outsize;
7365 continue;
7366 }
7367 }
7368 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7369 PyErr_SetFromWindowsErr(0);
7370 goto error;
7371 }
7372
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 rep = unicode_encode_call_errorhandler(
7374 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007375 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007376 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 if (rep == NULL)
7378 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007379 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007380
7381 if (PyBytes_Check(rep)) {
7382 outsize = PyBytes_GET_SIZE(rep);
7383 if (outsize != 1) {
7384 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7385 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7386 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7387 Py_DECREF(rep);
7388 goto error;
7389 }
7390 out = PyBytes_AS_STRING(*outbytes) + offset;
7391 }
7392 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7393 out += outsize;
7394 }
7395 else {
7396 Py_ssize_t i;
7397 enum PyUnicode_Kind kind;
7398 void *data;
7399
Benjamin Petersonbac79492012-01-14 13:34:47 -05007400 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 Py_DECREF(rep);
7402 goto error;
7403 }
7404
7405 outsize = PyUnicode_GET_LENGTH(rep);
7406 if (outsize != 1) {
7407 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7408 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7409 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7410 Py_DECREF(rep);
7411 goto error;
7412 }
7413 out = PyBytes_AS_STRING(*outbytes) + offset;
7414 }
7415 kind = PyUnicode_KIND(rep);
7416 data = PyUnicode_DATA(rep);
7417 for (i=0; i < outsize; i++) {
7418 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7419 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007420 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007421 encoding, unicode,
7422 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 "unable to encode error handler result to ASCII");
7424 Py_DECREF(rep);
7425 goto error;
7426 }
7427 *out = (unsigned char)ch;
7428 out++;
7429 }
7430 }
7431 Py_DECREF(rep);
7432 }
7433 /* write a NUL byte */
7434 *out = 0;
7435 outsize = out - PyBytes_AS_STRING(*outbytes);
7436 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7437 if (_PyBytes_Resize(outbytes, outsize) < 0)
7438 goto error;
7439 ret = 0;
7440
7441error:
7442 Py_XDECREF(encoding_obj);
7443 Py_XDECREF(errorHandler);
7444 Py_XDECREF(exc);
7445 return ret;
7446}
7447
Victor Stinner3a50e702011-10-18 21:21:00 +02007448static PyObject *
7449encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007450 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 const char *errors)
7452{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007453 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007455 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007456 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007457
Benjamin Petersonbac79492012-01-14 13:34:47 -05007458 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007459 return NULL;
7460 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007461
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 if (code_page < 0) {
7463 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7464 return NULL;
7465 }
7466
Martin v. Löwis3d325192011-11-04 18:23:06 +01007467 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007468 return PyBytes_FromStringAndSize(NULL, 0);
7469
Victor Stinner7581cef2011-11-03 22:32:33 +01007470 offset = 0;
7471 do
7472 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007473#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007475 chunks. */
7476 if (len > INT_MAX/2) {
7477 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007478 done = 0;
7479 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007480 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007481#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007482 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007483 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007484 done = 1;
7485 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007486
Victor Stinner76a31a62011-11-04 00:05:13 +01007487 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007488 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007489 errors);
7490 if (ret == -2)
7491 ret = encode_code_page_errors(code_page, &outbytes,
7492 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007493 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007494 if (ret < 0) {
7495 Py_XDECREF(outbytes);
7496 return NULL;
7497 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007498
Victor Stinner7581cef2011-11-03 22:32:33 +01007499 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007500 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007501 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007502
Victor Stinner3a50e702011-10-18 21:21:00 +02007503 return outbytes;
7504}
7505
7506PyObject *
7507PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7508 Py_ssize_t size,
7509 const char *errors)
7510{
Victor Stinner7581cef2011-11-03 22:32:33 +01007511 PyObject *unicode, *res;
7512 unicode = PyUnicode_FromUnicode(p, size);
7513 if (unicode == NULL)
7514 return NULL;
7515 res = encode_code_page(CP_ACP, unicode, errors);
7516 Py_DECREF(unicode);
7517 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007518}
7519
7520PyObject *
7521PyUnicode_EncodeCodePage(int code_page,
7522 PyObject *unicode,
7523 const char *errors)
7524{
Victor Stinner7581cef2011-11-03 22:32:33 +01007525 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007526}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007527
Alexander Belopolsky40018472011-02-26 01:02:56 +00007528PyObject *
7529PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007530{
7531 if (!PyUnicode_Check(unicode)) {
7532 PyErr_BadArgument();
7533 return NULL;
7534 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007535 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007536}
7537
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007538#undef NEED_RETRY
7539
Victor Stinner99b95382011-07-04 14:23:54 +02007540#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007541
Guido van Rossumd57fd912000-03-10 22:53:23 +00007542/* --- Character Mapping Codec -------------------------------------------- */
7543
Victor Stinnerfb161b12013-04-18 01:44:27 +02007544static int
7545charmap_decode_string(const char *s,
7546 Py_ssize_t size,
7547 PyObject *mapping,
7548 const char *errors,
7549 _PyUnicodeWriter *writer)
7550{
7551 const char *starts = s;
7552 const char *e;
7553 Py_ssize_t startinpos, endinpos;
7554 PyObject *errorHandler = NULL, *exc = NULL;
7555 Py_ssize_t maplen;
7556 enum PyUnicode_Kind mapkind;
7557 void *mapdata;
7558 Py_UCS4 x;
7559 unsigned char ch;
7560
7561 if (PyUnicode_READY(mapping) == -1)
7562 return -1;
7563
7564 maplen = PyUnicode_GET_LENGTH(mapping);
7565 mapdata = PyUnicode_DATA(mapping);
7566 mapkind = PyUnicode_KIND(mapping);
7567
7568 e = s + size;
7569
7570 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7571 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7572 * is disabled in encoding aliases, latin1 is preferred because
7573 * its implementation is faster. */
7574 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7575 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7576 Py_UCS4 maxchar = writer->maxchar;
7577
7578 assert (writer->kind == PyUnicode_1BYTE_KIND);
7579 while (s < e) {
7580 ch = *s;
7581 x = mapdata_ucs1[ch];
7582 if (x > maxchar) {
7583 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7584 goto onError;
7585 maxchar = writer->maxchar;
7586 outdata = (Py_UCS1 *)writer->data;
7587 }
7588 outdata[writer->pos] = x;
7589 writer->pos++;
7590 ++s;
7591 }
7592 return 0;
7593 }
7594
7595 while (s < e) {
7596 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7597 enum PyUnicode_Kind outkind = writer->kind;
7598 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7599 if (outkind == PyUnicode_1BYTE_KIND) {
7600 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7601 Py_UCS4 maxchar = writer->maxchar;
7602 while (s < e) {
7603 ch = *s;
7604 x = mapdata_ucs2[ch];
7605 if (x > maxchar)
7606 goto Error;
7607 outdata[writer->pos] = x;
7608 writer->pos++;
7609 ++s;
7610 }
7611 break;
7612 }
7613 else if (outkind == PyUnicode_2BYTE_KIND) {
7614 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7615 while (s < e) {
7616 ch = *s;
7617 x = mapdata_ucs2[ch];
7618 if (x == 0xFFFE)
7619 goto Error;
7620 outdata[writer->pos] = x;
7621 writer->pos++;
7622 ++s;
7623 }
7624 break;
7625 }
7626 }
7627 ch = *s;
7628
7629 if (ch < maplen)
7630 x = PyUnicode_READ(mapkind, mapdata, ch);
7631 else
7632 x = 0xfffe; /* invalid value */
7633Error:
7634 if (x == 0xfffe)
7635 {
7636 /* undefined mapping */
7637 startinpos = s-starts;
7638 endinpos = startinpos+1;
7639 if (unicode_decode_call_errorhandler_writer(
7640 errors, &errorHandler,
7641 "charmap", "character maps to <undefined>",
7642 &starts, &e, &startinpos, &endinpos, &exc, &s,
7643 writer)) {
7644 goto onError;
7645 }
7646 continue;
7647 }
7648
7649 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7650 goto onError;
7651 ++s;
7652 }
7653 Py_XDECREF(errorHandler);
7654 Py_XDECREF(exc);
7655 return 0;
7656
7657onError:
7658 Py_XDECREF(errorHandler);
7659 Py_XDECREF(exc);
7660 return -1;
7661}
7662
7663static int
7664charmap_decode_mapping(const char *s,
7665 Py_ssize_t size,
7666 PyObject *mapping,
7667 const char *errors,
7668 _PyUnicodeWriter *writer)
7669{
7670 const char *starts = s;
7671 const char *e;
7672 Py_ssize_t startinpos, endinpos;
7673 PyObject *errorHandler = NULL, *exc = NULL;
7674 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007675 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007676
7677 e = s + size;
7678
7679 while (s < e) {
7680 ch = *s;
7681
7682 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7683 key = PyLong_FromLong((long)ch);
7684 if (key == NULL)
7685 goto onError;
7686
7687 item = PyObject_GetItem(mapping, key);
7688 Py_DECREF(key);
7689 if (item == NULL) {
7690 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7691 /* No mapping found means: mapping is undefined. */
7692 PyErr_Clear();
7693 goto Undefined;
7694 } else
7695 goto onError;
7696 }
7697
7698 /* Apply mapping */
7699 if (item == Py_None)
7700 goto Undefined;
7701 if (PyLong_Check(item)) {
7702 long value = PyLong_AS_LONG(item);
7703 if (value == 0xFFFE)
7704 goto Undefined;
7705 if (value < 0 || value > MAX_UNICODE) {
7706 PyErr_Format(PyExc_TypeError,
7707 "character mapping must be in range(0x%lx)",
7708 (unsigned long)MAX_UNICODE + 1);
7709 goto onError;
7710 }
7711
7712 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7713 goto onError;
7714 }
7715 else if (PyUnicode_Check(item)) {
7716 if (PyUnicode_READY(item) == -1)
7717 goto onError;
7718 if (PyUnicode_GET_LENGTH(item) == 1) {
7719 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7720 if (value == 0xFFFE)
7721 goto Undefined;
7722 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7723 goto onError;
7724 }
7725 else {
7726 writer->overallocate = 1;
7727 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7728 goto onError;
7729 }
7730 }
7731 else {
7732 /* wrong return value */
7733 PyErr_SetString(PyExc_TypeError,
7734 "character mapping must return integer, None or str");
7735 goto onError;
7736 }
7737 Py_CLEAR(item);
7738 ++s;
7739 continue;
7740
7741Undefined:
7742 /* undefined mapping */
7743 Py_CLEAR(item);
7744 startinpos = s-starts;
7745 endinpos = startinpos+1;
7746 if (unicode_decode_call_errorhandler_writer(
7747 errors, &errorHandler,
7748 "charmap", "character maps to <undefined>",
7749 &starts, &e, &startinpos, &endinpos, &exc, &s,
7750 writer)) {
7751 goto onError;
7752 }
7753 }
7754 Py_XDECREF(errorHandler);
7755 Py_XDECREF(exc);
7756 return 0;
7757
7758onError:
7759 Py_XDECREF(item);
7760 Py_XDECREF(errorHandler);
7761 Py_XDECREF(exc);
7762 return -1;
7763}
7764
Alexander Belopolsky40018472011-02-26 01:02:56 +00007765PyObject *
7766PyUnicode_DecodeCharmap(const char *s,
7767 Py_ssize_t size,
7768 PyObject *mapping,
7769 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007770{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007771 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007772
Guido van Rossumd57fd912000-03-10 22:53:23 +00007773 /* Default to Latin-1 */
7774 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776
Guido van Rossumd57fd912000-03-10 22:53:23 +00007777 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007778 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007779 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007780 writer.min_length = size;
7781 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007782 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007783
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007784 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007785 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7786 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007787 }
7788 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007789 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7790 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007791 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007792 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007793
Benjamin Peterson29060642009-01-31 22:14:21 +00007794 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007795 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007796 return NULL;
7797}
7798
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007799/* Charmap encoding: the lookup table */
7800
Alexander Belopolsky40018472011-02-26 01:02:56 +00007801struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007802 PyObject_HEAD
7803 unsigned char level1[32];
7804 int count2, count3;
7805 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007806};
7807
7808static PyObject*
7809encoding_map_size(PyObject *obj, PyObject* args)
7810{
7811 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007812 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007813 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007814}
7815
7816static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007817 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 PyDoc_STR("Return the size (in bytes) of this object") },
7819 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007820};
7821
7822static void
7823encoding_map_dealloc(PyObject* o)
7824{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007825 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007826}
7827
7828static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007829 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 "EncodingMap", /*tp_name*/
7831 sizeof(struct encoding_map), /*tp_basicsize*/
7832 0, /*tp_itemsize*/
7833 /* methods */
7834 encoding_map_dealloc, /*tp_dealloc*/
7835 0, /*tp_print*/
7836 0, /*tp_getattr*/
7837 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007838 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 0, /*tp_repr*/
7840 0, /*tp_as_number*/
7841 0, /*tp_as_sequence*/
7842 0, /*tp_as_mapping*/
7843 0, /*tp_hash*/
7844 0, /*tp_call*/
7845 0, /*tp_str*/
7846 0, /*tp_getattro*/
7847 0, /*tp_setattro*/
7848 0, /*tp_as_buffer*/
7849 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7850 0, /*tp_doc*/
7851 0, /*tp_traverse*/
7852 0, /*tp_clear*/
7853 0, /*tp_richcompare*/
7854 0, /*tp_weaklistoffset*/
7855 0, /*tp_iter*/
7856 0, /*tp_iternext*/
7857 encoding_map_methods, /*tp_methods*/
7858 0, /*tp_members*/
7859 0, /*tp_getset*/
7860 0, /*tp_base*/
7861 0, /*tp_dict*/
7862 0, /*tp_descr_get*/
7863 0, /*tp_descr_set*/
7864 0, /*tp_dictoffset*/
7865 0, /*tp_init*/
7866 0, /*tp_alloc*/
7867 0, /*tp_new*/
7868 0, /*tp_free*/
7869 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870};
7871
7872PyObject*
7873PyUnicode_BuildEncodingMap(PyObject* string)
7874{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 PyObject *result;
7876 struct encoding_map *mresult;
7877 int i;
7878 int need_dict = 0;
7879 unsigned char level1[32];
7880 unsigned char level2[512];
7881 unsigned char *mlevel1, *mlevel2, *mlevel3;
7882 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007883 int kind;
7884 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007885 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007887
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007888 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007889 PyErr_BadArgument();
7890 return NULL;
7891 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007892 kind = PyUnicode_KIND(string);
7893 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007894 length = PyUnicode_GET_LENGTH(string);
7895 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007896 memset(level1, 0xFF, sizeof level1);
7897 memset(level2, 0xFF, sizeof level2);
7898
7899 /* If there isn't a one-to-one mapping of NULL to \0,
7900 or if there are non-BMP characters, we need to use
7901 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007902 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007903 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007904 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007906 ch = PyUnicode_READ(kind, data, i);
7907 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007908 need_dict = 1;
7909 break;
7910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007911 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 /* unmapped character */
7913 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007914 l1 = ch >> 11;
7915 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916 if (level1[l1] == 0xFF)
7917 level1[l1] = count2++;
7918 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007919 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007920 }
7921
7922 if (count2 >= 0xFF || count3 >= 0xFF)
7923 need_dict = 1;
7924
7925 if (need_dict) {
7926 PyObject *result = PyDict_New();
7927 PyObject *key, *value;
7928 if (!result)
7929 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007930 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007931 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007932 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 if (!key || !value)
7934 goto failed1;
7935 if (PyDict_SetItem(result, key, value) == -1)
7936 goto failed1;
7937 Py_DECREF(key);
7938 Py_DECREF(value);
7939 }
7940 return result;
7941 failed1:
7942 Py_XDECREF(key);
7943 Py_XDECREF(value);
7944 Py_DECREF(result);
7945 return NULL;
7946 }
7947
7948 /* Create a three-level trie */
7949 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7950 16*count2 + 128*count3 - 1);
7951 if (!result)
7952 return PyErr_NoMemory();
7953 PyObject_Init(result, &EncodingMapType);
7954 mresult = (struct encoding_map*)result;
7955 mresult->count2 = count2;
7956 mresult->count3 = count3;
7957 mlevel1 = mresult->level1;
7958 mlevel2 = mresult->level23;
7959 mlevel3 = mresult->level23 + 16*count2;
7960 memcpy(mlevel1, level1, 32);
7961 memset(mlevel2, 0xFF, 16*count2);
7962 memset(mlevel3, 0, 128*count3);
7963 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007964 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007966 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7967 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007968 /* unmapped character */
7969 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007970 o1 = ch>>11;
7971 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007972 i2 = 16*mlevel1[o1] + o2;
7973 if (mlevel2[i2] == 0xFF)
7974 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007975 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007976 i3 = 128*mlevel2[i2] + o3;
7977 mlevel3[i3] = i;
7978 }
7979 return result;
7980}
7981
7982static int
Victor Stinner22168992011-11-20 17:09:18 +01007983encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007984{
7985 struct encoding_map *map = (struct encoding_map*)mapping;
7986 int l1 = c>>11;
7987 int l2 = (c>>7) & 0xF;
7988 int l3 = c & 0x7F;
7989 int i;
7990
Victor Stinner22168992011-11-20 17:09:18 +01007991 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007993 if (c == 0)
7994 return 0;
7995 /* level 1*/
7996 i = map->level1[l1];
7997 if (i == 0xFF) {
7998 return -1;
7999 }
8000 /* level 2*/
8001 i = map->level23[16*i+l2];
8002 if (i == 0xFF) {
8003 return -1;
8004 }
8005 /* level 3 */
8006 i = map->level23[16*map->count2 + 128*i + l3];
8007 if (i == 0) {
8008 return -1;
8009 }
8010 return i;
8011}
8012
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008013/* Lookup the character ch in the mapping. If the character
8014 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008015 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008016static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008017charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008018{
Christian Heimes217cfd12007-12-02 14:31:20 +00008019 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008020 PyObject *x;
8021
8022 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008024 x = PyObject_GetItem(mapping, w);
8025 Py_DECREF(w);
8026 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8028 /* No mapping found means: mapping is undefined. */
8029 PyErr_Clear();
8030 x = Py_None;
8031 Py_INCREF(x);
8032 return x;
8033 } else
8034 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008035 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008036 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008038 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 long value = PyLong_AS_LONG(x);
8040 if (value < 0 || value > 255) {
8041 PyErr_SetString(PyExc_TypeError,
8042 "character mapping must be in range(256)");
8043 Py_DECREF(x);
8044 return NULL;
8045 }
8046 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008047 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008048 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008050 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008051 /* wrong return value */
8052 PyErr_Format(PyExc_TypeError,
8053 "character mapping must return integer, bytes or None, not %.400s",
8054 x->ob_type->tp_name);
8055 Py_DECREF(x);
8056 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008057 }
8058}
8059
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008060static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008061charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008063 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8064 /* exponentially overallocate to minimize reallocations */
8065 if (requiredsize < 2*outsize)
8066 requiredsize = 2*outsize;
8067 if (_PyBytes_Resize(outobj, requiredsize))
8068 return -1;
8069 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070}
8071
Benjamin Peterson14339b62009-01-31 16:36:08 +00008072typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008073 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008074} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008076 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008077 space is available. Return a new reference to the object that
8078 was put in the output buffer, or Py_None, if the mapping was undefined
8079 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008080 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008081static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008082charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008083 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008084{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085 PyObject *rep;
8086 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008087 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008088
Christian Heimes90aa7642007-12-19 02:45:37 +00008089 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 if (res == -1)
8093 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 if (outsize<requiredsize)
8095 if (charmapencode_resize(outobj, outpos, requiredsize))
8096 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008097 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008098 outstart[(*outpos)++] = (char)res;
8099 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 }
8101
8102 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008103 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008105 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 Py_DECREF(rep);
8107 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 if (PyLong_Check(rep)) {
8110 Py_ssize_t requiredsize = *outpos+1;
8111 if (outsize<requiredsize)
8112 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8113 Py_DECREF(rep);
8114 return enc_EXCEPTION;
8115 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008116 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008118 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008119 else {
8120 const char *repchars = PyBytes_AS_STRING(rep);
8121 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8122 Py_ssize_t requiredsize = *outpos+repsize;
8123 if (outsize<requiredsize)
8124 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8125 Py_DECREF(rep);
8126 return enc_EXCEPTION;
8127 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008128 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008129 memcpy(outstart + *outpos, repchars, repsize);
8130 *outpos += repsize;
8131 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008133 Py_DECREF(rep);
8134 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135}
8136
8137/* handle an error in PyUnicode_EncodeCharmap
8138 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008139static int
8140charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008141 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008142 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008143 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008144 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008145{
8146 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008147 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008148 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008149 enum PyUnicode_Kind kind;
8150 void *data;
8151 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008153 Py_ssize_t collstartpos = *inpos;
8154 Py_ssize_t collendpos = *inpos+1;
8155 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008156 char *encoding = "charmap";
8157 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008158 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008159 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008160 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008161
Benjamin Petersonbac79492012-01-14 13:34:47 -05008162 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008163 return -1;
8164 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165 /* find all unencodable characters */
8166 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008167 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008168 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008169 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008170 val = encoding_map_lookup(ch, mapping);
8171 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 break;
8173 ++collendpos;
8174 continue;
8175 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008176
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008177 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8178 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 if (rep==NULL)
8180 return -1;
8181 else if (rep!=Py_None) {
8182 Py_DECREF(rep);
8183 break;
8184 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008185 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008187 }
8188 /* cache callback name lookup
8189 * (if not done yet, i.e. it's the first error) */
8190 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 if ((errors==NULL) || (!strcmp(errors, "strict")))
8192 *known_errorHandler = 1;
8193 else if (!strcmp(errors, "replace"))
8194 *known_errorHandler = 2;
8195 else if (!strcmp(errors, "ignore"))
8196 *known_errorHandler = 3;
8197 else if (!strcmp(errors, "xmlcharrefreplace"))
8198 *known_errorHandler = 4;
8199 else
8200 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008201 }
8202 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008203 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008204 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008205 return -1;
8206 case 2: /* replace */
8207 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 x = charmapencode_output('?', mapping, res, respos);
8209 if (x==enc_EXCEPTION) {
8210 return -1;
8211 }
8212 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008213 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 return -1;
8215 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008216 }
8217 /* fall through */
8218 case 3: /* ignore */
8219 *inpos = collendpos;
8220 break;
8221 case 4: /* xmlcharrefreplace */
8222 /* generate replacement (temporarily (mis)uses p) */
8223 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 char buffer[2+29+1+1];
8225 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008226 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008227 for (cp = buffer; *cp; ++cp) {
8228 x = charmapencode_output(*cp, mapping, res, respos);
8229 if (x==enc_EXCEPTION)
8230 return -1;
8231 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008232 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 return -1;
8234 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008235 }
8236 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008237 *inpos = collendpos;
8238 break;
8239 default:
8240 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008241 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008243 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008245 if (PyBytes_Check(repunicode)) {
8246 /* Directly copy bytes result to output. */
8247 Py_ssize_t outsize = PyBytes_Size(*res);
8248 Py_ssize_t requiredsize;
8249 repsize = PyBytes_Size(repunicode);
8250 requiredsize = *respos + repsize;
8251 if (requiredsize > outsize)
8252 /* Make room for all additional bytes. */
8253 if (charmapencode_resize(res, respos, requiredsize)) {
8254 Py_DECREF(repunicode);
8255 return -1;
8256 }
8257 memcpy(PyBytes_AsString(*res) + *respos,
8258 PyBytes_AsString(repunicode), repsize);
8259 *respos += repsize;
8260 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008261 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008262 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008263 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008264 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008265 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008266 Py_DECREF(repunicode);
8267 return -1;
8268 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008269 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008270 data = PyUnicode_DATA(repunicode);
8271 kind = PyUnicode_KIND(repunicode);
8272 for (index = 0; index < repsize; index++) {
8273 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8274 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008276 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 return -1;
8278 }
8279 else if (x==enc_FAILED) {
8280 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008281 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 return -1;
8283 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008284 }
8285 *inpos = newpos;
8286 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 }
8288 return 0;
8289}
8290
Alexander Belopolsky40018472011-02-26 01:02:56 +00008291PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008292_PyUnicode_EncodeCharmap(PyObject *unicode,
8293 PyObject *mapping,
8294 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008295{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296 /* output object */
8297 PyObject *res = NULL;
8298 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008299 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008300 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008301 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008302 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303 PyObject *errorHandler = NULL;
8304 PyObject *exc = NULL;
8305 /* the following variable is used for caching string comparisons
8306 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8307 * 3=ignore, 4=xmlcharrefreplace */
8308 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008309 void *data;
8310 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008311
Benjamin Petersonbac79492012-01-14 13:34:47 -05008312 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008313 return NULL;
8314 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008315 data = PyUnicode_DATA(unicode);
8316 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008317
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318 /* Default to Latin-1 */
8319 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008320 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322 /* allocate enough for a simple encoding without
8323 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008324 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 if (res == NULL)
8326 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008327 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008329
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008331 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008333 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 if (x==enc_EXCEPTION) /* error */
8335 goto onError;
8336 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008337 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008338 &exc,
8339 &known_errorHandler, &errorHandler, errors,
8340 &res, &respos)) {
8341 goto onError;
8342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008343 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 else
8345 /* done with this character => adjust input position */
8346 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008347 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008350 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008351 if (_PyBytes_Resize(&res, respos) < 0)
8352 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008353
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 Py_XDECREF(exc);
8355 Py_XDECREF(errorHandler);
8356 return res;
8357
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 Py_XDECREF(res);
8360 Py_XDECREF(exc);
8361 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008362 return NULL;
8363}
8364
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008365/* Deprecated */
8366PyObject *
8367PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8368 Py_ssize_t size,
8369 PyObject *mapping,
8370 const char *errors)
8371{
8372 PyObject *result;
8373 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8374 if (unicode == NULL)
8375 return NULL;
8376 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8377 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008378 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008379}
8380
Alexander Belopolsky40018472011-02-26 01:02:56 +00008381PyObject *
8382PyUnicode_AsCharmapString(PyObject *unicode,
8383 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008384{
8385 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 PyErr_BadArgument();
8387 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008388 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008389 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008390}
8391
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008393static void
8394make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008395 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008396 Py_ssize_t startpos, Py_ssize_t endpos,
8397 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008398{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008400 *exceptionObject = _PyUnicodeTranslateError_Create(
8401 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 }
8403 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8405 goto onError;
8406 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8407 goto onError;
8408 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8409 goto onError;
8410 return;
8411 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008412 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008413 }
8414}
8415
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416/* error handling callback helper:
8417 build arguments, call the callback and check the arguments,
8418 put the result into newpos and return the replacement string, which
8419 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420static PyObject *
8421unicode_translate_call_errorhandler(const char *errors,
8422 PyObject **errorHandler,
8423 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425 Py_ssize_t startpos, Py_ssize_t endpos,
8426 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008427{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008428 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008430 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 PyObject *restuple;
8432 PyObject *resunicode;
8433
8434 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 }
8439
8440 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008441 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444
8445 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008447 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008450 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 Py_DECREF(restuple);
8452 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 }
8454 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 &resunicode, &i_newpos)) {
8456 Py_DECREF(restuple);
8457 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008458 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008459 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008461 else
8462 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008463 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008464 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 Py_DECREF(restuple);
8466 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008467 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 Py_INCREF(resunicode);
8469 Py_DECREF(restuple);
8470 return resunicode;
8471}
8472
8473/* Lookup the character ch in the mapping and put the result in result,
8474 which must be decrefed by the caller.
8475 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008476static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478{
Christian Heimes217cfd12007-12-02 14:31:20 +00008479 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480 PyObject *x;
8481
8482 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 x = PyObject_GetItem(mapping, w);
8485 Py_DECREF(w);
8486 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8488 /* No mapping found means: use 1:1 mapping. */
8489 PyErr_Clear();
8490 *result = NULL;
8491 return 0;
8492 } else
8493 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494 }
8495 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 *result = x;
8497 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008499 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 long value = PyLong_AS_LONG(x);
8501 long max = PyUnicode_GetMax();
8502 if (value < 0 || value > max) {
8503 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008504 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 Py_DECREF(x);
8506 return -1;
8507 }
8508 *result = x;
8509 return 0;
8510 }
8511 else if (PyUnicode_Check(x)) {
8512 *result = x;
8513 return 0;
8514 }
8515 else {
8516 /* wrong return value */
8517 PyErr_SetString(PyExc_TypeError,
8518 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008519 Py_DECREF(x);
8520 return -1;
8521 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522}
8523/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 if not reallocate and adjust various state variables.
8525 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008526static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008531 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008532 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 /* exponentially overallocate to minimize reallocations */
8534 if (requiredsize < 2 * oldsize)
8535 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008536 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8537 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008539 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008540 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 }
8542 return 0;
8543}
8544/* lookup the character, put the result in the output string and adjust
8545 various state variables. Return a new reference to the object that
8546 was put in the output buffer in *result, or Py_None, if the mapping was
8547 undefined (in which case no character was written).
8548 The called must decref result.
8549 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008550static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8552 PyObject *mapping, Py_UCS4 **output,
8553 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008554 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008555{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008556 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8557 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008561 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 }
8563 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008565 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 }
8569 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 Py_ssize_t repsize;
8571 if (PyUnicode_READY(*res) == -1)
8572 return -1;
8573 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 if (repsize==1) {
8575 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008576 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 }
8578 else if (repsize!=0) {
8579 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 Py_ssize_t requiredsize = *opos +
8581 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583 Py_ssize_t i;
8584 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008586 for(i = 0; i < repsize; i++)
8587 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589 }
8590 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008591 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592 return 0;
8593}
8594
Alexander Belopolsky40018472011-02-26 01:02:56 +00008595PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596_PyUnicode_TranslateCharmap(PyObject *input,
8597 PyObject *mapping,
8598 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 /* input object */
8601 char *idata;
8602 Py_ssize_t size, i;
8603 int kind;
8604 /* output buffer */
8605 Py_UCS4 *output = NULL;
8606 Py_ssize_t osize;
8607 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 char *reason = "character maps to <undefined>";
8611 PyObject *errorHandler = NULL;
8612 PyObject *exc = NULL;
8613 /* the following variable is used for caching string comparisons
8614 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8615 * 3=ignore, 4=xmlcharrefreplace */
8616 int known_errorHandler = -1;
8617
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 PyErr_BadArgument();
8620 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008621 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623 if (PyUnicode_READY(input) == -1)
8624 return NULL;
8625 idata = (char*)PyUnicode_DATA(input);
8626 kind = PyUnicode_KIND(input);
8627 size = PyUnicode_GET_LENGTH(input);
8628 i = 0;
8629
8630 if (size == 0) {
8631 Py_INCREF(input);
8632 return input;
8633 }
8634
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008635 /* allocate enough for a simple 1:1 translation without
8636 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 osize = size;
8638 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8639 opos = 0;
8640 if (output == NULL) {
8641 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 /* try to encode it */
8647 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 if (charmaptranslate_output(input, i, mapping,
8649 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 Py_XDECREF(x);
8651 goto onError;
8652 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008653 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 else { /* untranslatable character */
8657 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8658 Py_ssize_t repsize;
8659 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 Py_ssize_t collstart = i;
8663 Py_ssize_t collend = i+1;
8664 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008665
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 while (collend < size) {
8668 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 goto onError;
8670 Py_XDECREF(x);
8671 if (x!=Py_None)
8672 break;
8673 ++collend;
8674 }
8675 /* cache callback name lookup
8676 * (if not done yet, i.e. it's the first error) */
8677 if (known_errorHandler==-1) {
8678 if ((errors==NULL) || (!strcmp(errors, "strict")))
8679 known_errorHandler = 1;
8680 else if (!strcmp(errors, "replace"))
8681 known_errorHandler = 2;
8682 else if (!strcmp(errors, "ignore"))
8683 known_errorHandler = 3;
8684 else if (!strcmp(errors, "xmlcharrefreplace"))
8685 known_errorHandler = 4;
8686 else
8687 known_errorHandler = 0;
8688 }
8689 switch (known_errorHandler) {
8690 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008691 make_translate_exception(&exc,
8692 input, collstart, collend, reason);
8693 if (exc != NULL)
8694 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008695 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 case 2: /* replace */
8697 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 for (coll = collstart; coll<collend; coll++)
8699 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 /* fall through */
8701 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008702 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 break;
8704 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008705 /* generate replacement (temporarily (mis)uses i) */
8706 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 char buffer[2+29+1+1];
8708 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8710 if (charmaptranslate_makespace(&output, &osize,
8711 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 goto onError;
8713 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 break;
8718 default:
8719 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 reason, input, &exc,
8721 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008722 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008724 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008725 Py_DECREF(repunicode);
8726 goto onError;
8727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008729 repsize = PyUnicode_GET_LENGTH(repunicode);
8730 if (charmaptranslate_makespace(&output, &osize,
8731 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 Py_DECREF(repunicode);
8733 goto onError;
8734 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735 for (uni2 = 0; repsize-->0; ++uni2)
8736 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8737 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008739 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008740 }
8741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008742 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8743 if (!res)
8744 goto onError;
8745 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008746 Py_XDECREF(exc);
8747 Py_XDECREF(errorHandler);
8748 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752 Py_XDECREF(exc);
8753 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008754 return NULL;
8755}
8756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008757/* Deprecated. Use PyUnicode_Translate instead. */
8758PyObject *
8759PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8760 Py_ssize_t size,
8761 PyObject *mapping,
8762 const char *errors)
8763{
Christian Heimes5f520f42012-09-11 14:03:25 +02008764 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8766 if (!unicode)
8767 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008768 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8769 Py_DECREF(unicode);
8770 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771}
8772
Alexander Belopolsky40018472011-02-26 01:02:56 +00008773PyObject *
8774PyUnicode_Translate(PyObject *str,
8775 PyObject *mapping,
8776 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008777{
8778 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008779
Guido van Rossumd57fd912000-03-10 22:53:23 +00008780 str = PyUnicode_FromObject(str);
8781 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008782 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 Py_DECREF(str);
8785 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786}
Tim Petersced69f82003-09-16 20:30:58 +00008787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008788static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008789fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790{
8791 /* No need to call PyUnicode_READY(self) because this function is only
8792 called as a callback from fixup() which does it already. */
8793 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8794 const int kind = PyUnicode_KIND(self);
8795 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008796 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008797 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008798 Py_ssize_t i;
8799
8800 for (i = 0; i < len; ++i) {
8801 ch = PyUnicode_READ(kind, data, i);
8802 fixed = 0;
8803 if (ch > 127) {
8804 if (Py_UNICODE_ISSPACE(ch))
8805 fixed = ' ';
8806 else {
8807 const int decimal = Py_UNICODE_TODECIMAL(ch);
8808 if (decimal >= 0)
8809 fixed = '0' + decimal;
8810 }
8811 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008812 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008813 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008814 PyUnicode_WRITE(kind, data, i, fixed);
8815 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008816 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008817 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008818 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 }
8820
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008821 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822}
8823
8824PyObject *
8825_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8826{
8827 if (!PyUnicode_Check(unicode)) {
8828 PyErr_BadInternalCall();
8829 return NULL;
8830 }
8831 if (PyUnicode_READY(unicode) == -1)
8832 return NULL;
8833 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8834 /* If the string is already ASCII, just return the same string */
8835 Py_INCREF(unicode);
8836 return unicode;
8837 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008838 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839}
8840
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008841PyObject *
8842PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8843 Py_ssize_t length)
8844{
Victor Stinnerf0124502011-11-21 23:12:56 +01008845 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008846 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008847 Py_UCS4 maxchar;
8848 enum PyUnicode_Kind kind;
8849 void *data;
8850
Victor Stinner99d7ad02012-02-22 13:37:39 +01008851 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008852 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008853 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008854 if (ch > 127) {
8855 int decimal = Py_UNICODE_TODECIMAL(ch);
8856 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008857 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008858 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008859 }
8860 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008861
8862 /* Copy to a new string */
8863 decimal = PyUnicode_New(length, maxchar);
8864 if (decimal == NULL)
8865 return decimal;
8866 kind = PyUnicode_KIND(decimal);
8867 data = PyUnicode_DATA(decimal);
8868 /* Iterate over code points */
8869 for (i = 0; i < length; i++) {
8870 Py_UNICODE ch = s[i];
8871 if (ch > 127) {
8872 int decimal = Py_UNICODE_TODECIMAL(ch);
8873 if (decimal >= 0)
8874 ch = '0' + decimal;
8875 }
8876 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008878 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008879}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008880/* --- Decimal Encoder ---------------------------------------------------- */
8881
Alexander Belopolsky40018472011-02-26 01:02:56 +00008882int
8883PyUnicode_EncodeDecimal(Py_UNICODE *s,
8884 Py_ssize_t length,
8885 char *output,
8886 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008887{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008888 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008889 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008890 enum PyUnicode_Kind kind;
8891 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008892
8893 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 PyErr_BadArgument();
8895 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008896 }
8897
Victor Stinner42bf7752011-11-21 22:52:58 +01008898 unicode = PyUnicode_FromUnicode(s, length);
8899 if (unicode == NULL)
8900 return -1;
8901
Benjamin Petersonbac79492012-01-14 13:34:47 -05008902 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008903 Py_DECREF(unicode);
8904 return -1;
8905 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008906 kind = PyUnicode_KIND(unicode);
8907 data = PyUnicode_DATA(unicode);
8908
Victor Stinnerb84d7232011-11-22 01:50:07 +01008909 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008910 PyObject *exc;
8911 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008912 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008913 Py_ssize_t startpos;
8914
8915 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008916
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008918 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008919 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008920 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008921 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008922 decimal = Py_UNICODE_TODECIMAL(ch);
8923 if (decimal >= 0) {
8924 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008925 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008926 continue;
8927 }
8928 if (0 < ch && ch < 256) {
8929 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008930 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 continue;
8932 }
Victor Stinner6345be92011-11-25 20:09:01 +01008933
Victor Stinner42bf7752011-11-21 22:52:58 +01008934 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008935 exc = NULL;
8936 raise_encode_exception(&exc, "decimal", unicode,
8937 startpos, startpos+1,
8938 "invalid decimal Unicode string");
8939 Py_XDECREF(exc);
8940 Py_DECREF(unicode);
8941 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008942 }
8943 /* 0-terminate the output string */
8944 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008945 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008946 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008947}
8948
Guido van Rossumd57fd912000-03-10 22:53:23 +00008949/* --- Helpers ------------------------------------------------------------ */
8950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008952any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008953 Py_ssize_t start,
8954 Py_ssize_t end)
8955{
8956 int kind1, kind2, kind;
8957 void *buf1, *buf2;
8958 Py_ssize_t len1, len2, result;
8959
8960 kind1 = PyUnicode_KIND(s1);
8961 kind2 = PyUnicode_KIND(s2);
8962 kind = kind1 > kind2 ? kind1 : kind2;
8963 buf1 = PyUnicode_DATA(s1);
8964 buf2 = PyUnicode_DATA(s2);
8965 if (kind1 != kind)
8966 buf1 = _PyUnicode_AsKind(s1, kind);
8967 if (!buf1)
8968 return -2;
8969 if (kind2 != kind)
8970 buf2 = _PyUnicode_AsKind(s2, kind);
8971 if (!buf2) {
8972 if (kind1 != kind) PyMem_Free(buf1);
8973 return -2;
8974 }
8975 len1 = PyUnicode_GET_LENGTH(s1);
8976 len2 = PyUnicode_GET_LENGTH(s2);
8977
Victor Stinner794d5672011-10-10 03:21:36 +02008978 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008979 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008980 case PyUnicode_1BYTE_KIND:
8981 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8982 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8983 else
8984 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8985 break;
8986 case PyUnicode_2BYTE_KIND:
8987 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8988 break;
8989 case PyUnicode_4BYTE_KIND:
8990 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8991 break;
8992 default:
8993 assert(0); result = -2;
8994 }
8995 }
8996 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008997 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008998 case PyUnicode_1BYTE_KIND:
8999 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9000 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9001 else
9002 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9003 break;
9004 case PyUnicode_2BYTE_KIND:
9005 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9006 break;
9007 case PyUnicode_4BYTE_KIND:
9008 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9009 break;
9010 default:
9011 assert(0); result = -2;
9012 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009013 }
9014
9015 if (kind1 != kind)
9016 PyMem_Free(buf1);
9017 if (kind2 != kind)
9018 PyMem_Free(buf2);
9019
9020 return result;
9021}
9022
9023Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009024_PyUnicode_InsertThousandsGrouping(
9025 PyObject *unicode, Py_ssize_t index,
9026 Py_ssize_t n_buffer,
9027 void *digits, Py_ssize_t n_digits,
9028 Py_ssize_t min_width,
9029 const char *grouping, PyObject *thousands_sep,
9030 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031{
Victor Stinner41a863c2012-02-24 00:37:51 +01009032 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009033 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009034 Py_ssize_t thousands_sep_len;
9035 Py_ssize_t len;
9036
9037 if (unicode != NULL) {
9038 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009039 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009040 }
9041 else {
9042 kind = PyUnicode_1BYTE_KIND;
9043 data = NULL;
9044 }
9045 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9046 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9047 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9048 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009049 if (thousands_sep_kind < kind) {
9050 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9051 if (!thousands_sep_data)
9052 return -1;
9053 }
9054 else {
9055 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9056 if (!data)
9057 return -1;
9058 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009059 }
9060
Benjamin Petersonead6b532011-12-20 17:23:42 -06009061 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009063 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009064 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009065 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009066 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009067 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009068 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009069 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009070 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009071 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009072 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009073 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009075 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009076 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009077 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009078 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009079 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009081 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009082 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009083 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009084 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009085 break;
9086 default:
9087 assert(0);
9088 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009090 if (unicode != NULL && thousands_sep_kind != kind) {
9091 if (thousands_sep_kind < kind)
9092 PyMem_Free(thousands_sep_data);
9093 else
9094 PyMem_Free(data);
9095 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009096 if (unicode == NULL) {
9097 *maxchar = 127;
9098 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009099 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009100 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 }
9102 }
9103 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104}
9105
9106
Thomas Wouters477c8d52006-05-27 19:21:47 +00009107/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009108#define ADJUST_INDICES(start, end, len) \
9109 if (end > len) \
9110 end = len; \
9111 else if (end < 0) { \
9112 end += len; \
9113 if (end < 0) \
9114 end = 0; \
9115 } \
9116 if (start < 0) { \
9117 start += len; \
9118 if (start < 0) \
9119 start = 0; \
9120 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009121
Alexander Belopolsky40018472011-02-26 01:02:56 +00009122Py_ssize_t
9123PyUnicode_Count(PyObject *str,
9124 PyObject *substr,
9125 Py_ssize_t start,
9126 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009128 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009129 PyObject* str_obj;
9130 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009131 int kind1, kind2, kind;
9132 void *buf1 = NULL, *buf2 = NULL;
9133 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009134
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009135 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009136 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009137 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009138 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009139 if (!sub_obj) {
9140 Py_DECREF(str_obj);
9141 return -1;
9142 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009143 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009144 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 Py_DECREF(str_obj);
9146 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147 }
Tim Petersced69f82003-09-16 20:30:58 +00009148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009149 kind1 = PyUnicode_KIND(str_obj);
9150 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009151 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009153 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009154 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009155 if (kind2 > kind) {
9156 Py_DECREF(sub_obj);
9157 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009158 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009159 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009160 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 if (!buf2)
9163 goto onError;
9164 len1 = PyUnicode_GET_LENGTH(str_obj);
9165 len2 = PyUnicode_GET_LENGTH(sub_obj);
9166
9167 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009168 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009170 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9171 result = asciilib_count(
9172 ((Py_UCS1*)buf1) + start, end - start,
9173 buf2, len2, PY_SSIZE_T_MAX
9174 );
9175 else
9176 result = ucs1lib_count(
9177 ((Py_UCS1*)buf1) + start, end - start,
9178 buf2, len2, PY_SSIZE_T_MAX
9179 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 break;
9181 case PyUnicode_2BYTE_KIND:
9182 result = ucs2lib_count(
9183 ((Py_UCS2*)buf1) + start, end - start,
9184 buf2, len2, PY_SSIZE_T_MAX
9185 );
9186 break;
9187 case PyUnicode_4BYTE_KIND:
9188 result = ucs4lib_count(
9189 ((Py_UCS4*)buf1) + start, end - start,
9190 buf2, len2, PY_SSIZE_T_MAX
9191 );
9192 break;
9193 default:
9194 assert(0); result = 0;
9195 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009196
9197 Py_DECREF(sub_obj);
9198 Py_DECREF(str_obj);
9199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009200 if (kind2 != kind)
9201 PyMem_Free(buf2);
9202
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 onError:
9205 Py_DECREF(sub_obj);
9206 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207 if (kind2 != kind && buf2)
9208 PyMem_Free(buf2);
9209 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009210}
9211
Alexander Belopolsky40018472011-02-26 01:02:56 +00009212Py_ssize_t
9213PyUnicode_Find(PyObject *str,
9214 PyObject *sub,
9215 Py_ssize_t start,
9216 Py_ssize_t end,
9217 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009218{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009219 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009220
Guido van Rossumd57fd912000-03-10 22:53:23 +00009221 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009222 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009223 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009224 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009225 if (!sub) {
9226 Py_DECREF(str);
9227 return -2;
9228 }
9229 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9230 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009231 Py_DECREF(str);
9232 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233 }
Tim Petersced69f82003-09-16 20:30:58 +00009234
Victor Stinner794d5672011-10-10 03:21:36 +02009235 result = any_find_slice(direction,
9236 str, sub, start, end
9237 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009238
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009240 Py_DECREF(sub);
9241
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242 return result;
9243}
9244
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245Py_ssize_t
9246PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9247 Py_ssize_t start, Py_ssize_t end,
9248 int direction)
9249{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009250 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009251 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 if (PyUnicode_READY(str) == -1)
9253 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009254 if (start < 0 || end < 0) {
9255 PyErr_SetString(PyExc_IndexError, "string index out of range");
9256 return -2;
9257 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 if (end > PyUnicode_GET_LENGTH(str))
9259 end = PyUnicode_GET_LENGTH(str);
9260 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009261 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9262 kind, end-start, ch, direction);
9263 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009265 else
9266 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009267}
9268
Alexander Belopolsky40018472011-02-26 01:02:56 +00009269static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009270tailmatch(PyObject *self,
9271 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009272 Py_ssize_t start,
9273 Py_ssize_t end,
9274 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009275{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 int kind_self;
9277 int kind_sub;
9278 void *data_self;
9279 void *data_sub;
9280 Py_ssize_t offset;
9281 Py_ssize_t i;
9282 Py_ssize_t end_sub;
9283
9284 if (PyUnicode_READY(self) == -1 ||
9285 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009286 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287
9288 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009289 return 1;
9290
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
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296 kind_self = PyUnicode_KIND(self);
9297 data_self = PyUnicode_DATA(self);
9298 kind_sub = PyUnicode_KIND(substring);
9299 data_sub = PyUnicode_DATA(substring);
9300 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9301
9302 if (direction > 0)
9303 offset = end;
9304 else
9305 offset = start;
9306
9307 if (PyUnicode_READ(kind_self, data_self, offset) ==
9308 PyUnicode_READ(kind_sub, data_sub, 0) &&
9309 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9310 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9311 /* If both are of the same kind, memcmp is sufficient */
9312 if (kind_self == kind_sub) {
9313 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009314 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315 data_sub,
9316 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009317 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318 }
9319 /* otherwise we have to compare each character by first accesing it */
9320 else {
9321 /* We do not need to compare 0 and len(substring)-1 because
9322 the if statement above ensured already that they are equal
9323 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 for (i = 1; i < end_sub; ++i) {
9325 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9326 PyUnicode_READ(kind_sub, data_sub, i))
9327 return 0;
9328 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009329 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009330 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331 }
9332
9333 return 0;
9334}
9335
Alexander Belopolsky40018472011-02-26 01:02:56 +00009336Py_ssize_t
9337PyUnicode_Tailmatch(PyObject *str,
9338 PyObject *substr,
9339 Py_ssize_t start,
9340 Py_ssize_t end,
9341 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009343 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009344
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345 str = PyUnicode_FromObject(str);
9346 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009347 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009348 substr = PyUnicode_FromObject(substr);
9349 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009350 Py_DECREF(str);
9351 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352 }
Tim Petersced69f82003-09-16 20:30:58 +00009353
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009354 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009355 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356 Py_DECREF(str);
9357 Py_DECREF(substr);
9358 return result;
9359}
9360
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361/* Apply fixfct filter to the Unicode object self and return a
9362 reference to the modified object */
9363
Alexander Belopolsky40018472011-02-26 01:02:56 +00009364static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009365fixup(PyObject *self,
9366 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 PyObject *u;
9369 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009370 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009372 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009374 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009375 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 /* fix functions return the new maximum character in a string,
9378 if the kind of the resulting unicode object does not change,
9379 everything is fine. Otherwise we need to change the string kind
9380 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009381 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009382
9383 if (maxchar_new == 0) {
9384 /* no changes */;
9385 if (PyUnicode_CheckExact(self)) {
9386 Py_DECREF(u);
9387 Py_INCREF(self);
9388 return self;
9389 }
9390 else
9391 return u;
9392 }
9393
Victor Stinnere6abb482012-05-02 01:15:40 +02009394 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395
Victor Stinnereaab6042011-12-11 22:22:39 +01009396 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009398
9399 /* In case the maximum character changed, we need to
9400 convert the string to the new category. */
9401 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9402 if (v == NULL) {
9403 Py_DECREF(u);
9404 return NULL;
9405 }
9406 if (maxchar_new > maxchar_old) {
9407 /* If the maxchar increased so that the kind changed, not all
9408 characters are representable anymore and we need to fix the
9409 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009410 _PyUnicode_FastCopyCharacters(v, 0,
9411 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009412 maxchar_old = fixfct(v);
9413 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 }
9415 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009416 _PyUnicode_FastCopyCharacters(v, 0,
9417 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009419 Py_DECREF(u);
9420 assert(_PyUnicode_CheckConsistency(v, 1));
9421 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422}
9423
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009424static PyObject *
9425ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009427 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9428 char *resdata, *data = PyUnicode_DATA(self);
9429 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009430
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009431 res = PyUnicode_New(len, 127);
9432 if (res == NULL)
9433 return NULL;
9434 resdata = PyUnicode_DATA(res);
9435 if (lower)
9436 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009438 _Py_bytes_upper(resdata, data, len);
9439 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009440}
9441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009443handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009444{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009445 Py_ssize_t j;
9446 int final_sigma;
9447 Py_UCS4 c;
9448 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009449
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009450 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9451
9452 where ! is a negation and \p{xxx} is a character with property xxx.
9453 */
9454 for (j = i - 1; j >= 0; j--) {
9455 c = PyUnicode_READ(kind, data, j);
9456 if (!_PyUnicode_IsCaseIgnorable(c))
9457 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009459 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9460 if (final_sigma) {
9461 for (j = i + 1; j < length; j++) {
9462 c = PyUnicode_READ(kind, data, j);
9463 if (!_PyUnicode_IsCaseIgnorable(c))
9464 break;
9465 }
9466 final_sigma = j == length || !_PyUnicode_IsCased(c);
9467 }
9468 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009469}
9470
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009471static int
9472lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9473 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009475 /* Obscure special case. */
9476 if (c == 0x3A3) {
9477 mapped[0] = handle_capital_sigma(kind, data, length, i);
9478 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009479 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009480 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481}
9482
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009483static Py_ssize_t
9484do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009486 Py_ssize_t i, k = 0;
9487 int n_res, j;
9488 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009489
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009490 c = PyUnicode_READ(kind, data, 0);
9491 n_res = _PyUnicode_ToUpperFull(c, mapped);
9492 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009493 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009494 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009496 for (i = 1; i < length; i++) {
9497 c = PyUnicode_READ(kind, data, i);
9498 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9499 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009500 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009501 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009502 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009503 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009504 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505}
9506
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009507static Py_ssize_t
9508do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9509 Py_ssize_t i, k = 0;
9510
9511 for (i = 0; i < length; i++) {
9512 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9513 int n_res, j;
9514 if (Py_UNICODE_ISUPPER(c)) {
9515 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9516 }
9517 else if (Py_UNICODE_ISLOWER(c)) {
9518 n_res = _PyUnicode_ToUpperFull(c, mapped);
9519 }
9520 else {
9521 n_res = 1;
9522 mapped[0] = c;
9523 }
9524 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009525 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009526 res[k++] = mapped[j];
9527 }
9528 }
9529 return k;
9530}
9531
9532static Py_ssize_t
9533do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9534 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009536 Py_ssize_t i, k = 0;
9537
9538 for (i = 0; i < length; i++) {
9539 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9540 int n_res, j;
9541 if (lower)
9542 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9543 else
9544 n_res = _PyUnicode_ToUpperFull(c, mapped);
9545 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009546 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009547 res[k++] = mapped[j];
9548 }
9549 }
9550 return k;
9551}
9552
9553static Py_ssize_t
9554do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9555{
9556 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9557}
9558
9559static Py_ssize_t
9560do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9561{
9562 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9563}
9564
Benjamin Petersone51757f2012-01-12 21:10:29 -05009565static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009566do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9567{
9568 Py_ssize_t i, k = 0;
9569
9570 for (i = 0; i < length; i++) {
9571 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9572 Py_UCS4 mapped[3];
9573 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9574 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009575 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009576 res[k++] = mapped[j];
9577 }
9578 }
9579 return k;
9580}
9581
9582static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009583do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9584{
9585 Py_ssize_t i, k = 0;
9586 int previous_is_cased;
9587
9588 previous_is_cased = 0;
9589 for (i = 0; i < length; i++) {
9590 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9591 Py_UCS4 mapped[3];
9592 int n_res, j;
9593
9594 if (previous_is_cased)
9595 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9596 else
9597 n_res = _PyUnicode_ToTitleFull(c, mapped);
9598
9599 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009600 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009601 res[k++] = mapped[j];
9602 }
9603
9604 previous_is_cased = _PyUnicode_IsCased(c);
9605 }
9606 return k;
9607}
9608
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009609static PyObject *
9610case_operation(PyObject *self,
9611 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9612{
9613 PyObject *res = NULL;
9614 Py_ssize_t length, newlength = 0;
9615 int kind, outkind;
9616 void *data, *outdata;
9617 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9618
Benjamin Petersoneea48462012-01-16 14:28:50 -05009619 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009620
9621 kind = PyUnicode_KIND(self);
9622 data = PyUnicode_DATA(self);
9623 length = PyUnicode_GET_LENGTH(self);
9624 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9625 if (tmp == NULL)
9626 return PyErr_NoMemory();
9627 newlength = perform(kind, data, length, tmp, &maxchar);
9628 res = PyUnicode_New(newlength, maxchar);
9629 if (res == NULL)
9630 goto leave;
9631 tmpend = tmp + newlength;
9632 outdata = PyUnicode_DATA(res);
9633 outkind = PyUnicode_KIND(res);
9634 switch (outkind) {
9635 case PyUnicode_1BYTE_KIND:
9636 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9637 break;
9638 case PyUnicode_2BYTE_KIND:
9639 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9640 break;
9641 case PyUnicode_4BYTE_KIND:
9642 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9643 break;
9644 default:
9645 assert(0);
9646 break;
9647 }
9648 leave:
9649 PyMem_FREE(tmp);
9650 return res;
9651}
9652
Tim Peters8ce9f162004-08-27 01:49:32 +00009653PyObject *
9654PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009655{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009657 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009659 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009660 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9661 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009662 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009664 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009666 int use_memcpy;
9667 unsigned char *res_data = NULL, *sep_data = NULL;
9668 PyObject *last_obj;
9669 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009671 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009672 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009673 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009674 }
9675
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009676 /* NOTE: the following code can't call back into Python code,
9677 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009678 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009679
Tim Peters05eba1f2004-08-27 21:32:02 +00009680 seqlen = PySequence_Fast_GET_SIZE(fseq);
9681 /* If empty sequence, return u"". */
9682 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009683 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009684 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009685 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009686
Tim Peters05eba1f2004-08-27 21:32:02 +00009687 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009688 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009689 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009690 if (seqlen == 1) {
9691 if (PyUnicode_CheckExact(items[0])) {
9692 res = items[0];
9693 Py_INCREF(res);
9694 Py_DECREF(fseq);
9695 return res;
9696 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009697 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009698 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009699 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009700 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009701 /* Set up sep and seplen */
9702 if (separator == NULL) {
9703 /* fall back to a blank space separator */
9704 sep = PyUnicode_FromOrdinal(' ');
9705 if (!sep)
9706 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009707 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009708 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009709 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009710 else {
9711 if (!PyUnicode_Check(separator)) {
9712 PyErr_Format(PyExc_TypeError,
9713 "separator: expected str instance,"
9714 " %.80s found",
9715 Py_TYPE(separator)->tp_name);
9716 goto onError;
9717 }
9718 if (PyUnicode_READY(separator))
9719 goto onError;
9720 sep = separator;
9721 seplen = PyUnicode_GET_LENGTH(separator);
9722 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9723 /* inc refcount to keep this code path symmetric with the
9724 above case of a blank separator */
9725 Py_INCREF(sep);
9726 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009728 }
9729
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009730 /* There are at least two things to join, or else we have a subclass
9731 * of str in the sequence.
9732 * Do a pre-pass to figure out the total amount of space we'll
9733 * need (sz), and see whether all argument are strings.
9734 */
9735 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009736#ifdef Py_DEBUG
9737 use_memcpy = 0;
9738#else
9739 use_memcpy = 1;
9740#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009741 for (i = 0; i < seqlen; i++) {
9742 const Py_ssize_t old_sz = sz;
9743 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009744 if (!PyUnicode_Check(item)) {
9745 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009746 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009747 " %.80s found",
9748 i, Py_TYPE(item)->tp_name);
9749 goto onError;
9750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 if (PyUnicode_READY(item) == -1)
9752 goto onError;
9753 sz += PyUnicode_GET_LENGTH(item);
9754 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009755 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009756 if (i != 0)
9757 sz += seplen;
9758 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9759 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009760 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009761 goto onError;
9762 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009763 if (use_memcpy && last_obj != NULL) {
9764 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9765 use_memcpy = 0;
9766 }
9767 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009768 }
Tim Petersced69f82003-09-16 20:30:58 +00009769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009771 if (res == NULL)
9772 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009773
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009774 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009775#ifdef Py_DEBUG
9776 use_memcpy = 0;
9777#else
9778 if (use_memcpy) {
9779 res_data = PyUnicode_1BYTE_DATA(res);
9780 kind = PyUnicode_KIND(res);
9781 if (seplen != 0)
9782 sep_data = PyUnicode_1BYTE_DATA(sep);
9783 }
9784#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009785 if (use_memcpy) {
9786 for (i = 0; i < seqlen; ++i) {
9787 Py_ssize_t itemlen;
9788 item = items[i];
9789
9790 /* Copy item, and maybe the separator. */
9791 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009792 Py_MEMCPY(res_data,
9793 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009794 kind * seplen);
9795 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009796 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009797
9798 itemlen = PyUnicode_GET_LENGTH(item);
9799 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009800 Py_MEMCPY(res_data,
9801 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009802 kind * itemlen);
9803 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009804 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009805 }
9806 assert(res_data == PyUnicode_1BYTE_DATA(res)
9807 + kind * PyUnicode_GET_LENGTH(res));
9808 }
9809 else {
9810 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9811 Py_ssize_t itemlen;
9812 item = items[i];
9813
9814 /* Copy item, and maybe the separator. */
9815 if (i && seplen != 0) {
9816 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9817 res_offset += seplen;
9818 }
9819
9820 itemlen = PyUnicode_GET_LENGTH(item);
9821 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009822 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009823 res_offset += itemlen;
9824 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009825 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009826 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009827 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009828
Tim Peters05eba1f2004-08-27 21:32:02 +00009829 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009830 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009831 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009833
Benjamin Peterson29060642009-01-31 22:14:21 +00009834 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009835 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009837 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009838 return NULL;
9839}
9840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841#define FILL(kind, data, value, start, length) \
9842 do { \
9843 Py_ssize_t i_ = 0; \
9844 assert(kind != PyUnicode_WCHAR_KIND); \
9845 switch ((kind)) { \
9846 case PyUnicode_1BYTE_KIND: { \
9847 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009848 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 break; \
9850 } \
9851 case PyUnicode_2BYTE_KIND: { \
9852 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9853 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9854 break; \
9855 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009856 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009857 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9858 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9859 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009860 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009861 } \
9862 } \
9863 } while (0)
9864
Victor Stinnerd3f08822012-05-29 12:57:52 +02009865void
9866_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9867 Py_UCS4 fill_char)
9868{
9869 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9870 const void *data = PyUnicode_DATA(unicode);
9871 assert(PyUnicode_IS_READY(unicode));
9872 assert(unicode_modifiable(unicode));
9873 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9874 assert(start >= 0);
9875 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9876 FILL(kind, data, fill_char, start, length);
9877}
9878
Victor Stinner3fe55312012-01-04 00:33:50 +01009879Py_ssize_t
9880PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9881 Py_UCS4 fill_char)
9882{
9883 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009884
9885 if (!PyUnicode_Check(unicode)) {
9886 PyErr_BadInternalCall();
9887 return -1;
9888 }
9889 if (PyUnicode_READY(unicode) == -1)
9890 return -1;
9891 if (unicode_check_modifiable(unicode))
9892 return -1;
9893
Victor Stinnerd3f08822012-05-29 12:57:52 +02009894 if (start < 0) {
9895 PyErr_SetString(PyExc_IndexError, "string index out of range");
9896 return -1;
9897 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009898 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9899 PyErr_SetString(PyExc_ValueError,
9900 "fill character is bigger than "
9901 "the string maximum character");
9902 return -1;
9903 }
9904
9905 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9906 length = Py_MIN(maxlen, length);
9907 if (length <= 0)
9908 return 0;
9909
Victor Stinnerd3f08822012-05-29 12:57:52 +02009910 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009911 return length;
9912}
9913
Victor Stinner9310abb2011-10-05 00:59:23 +02009914static PyObject *
9915pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009916 Py_ssize_t left,
9917 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 PyObject *u;
9921 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009922 int kind;
9923 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924
9925 if (left < 0)
9926 left = 0;
9927 if (right < 0)
9928 right = 0;
9929
Victor Stinnerc4b49542011-12-11 22:44:26 +01009930 if (left == 0 && right == 0)
9931 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9934 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009935 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9936 return NULL;
9937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009938 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009939 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009941 if (!u)
9942 return NULL;
9943
9944 kind = PyUnicode_KIND(u);
9945 data = PyUnicode_DATA(u);
9946 if (left)
9947 FILL(kind, data, fill, 0, left);
9948 if (right)
9949 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009950 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009951 assert(_PyUnicode_CheckConsistency(u, 1));
9952 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953}
9954
Alexander Belopolsky40018472011-02-26 01:02:56 +00009955PyObject *
9956PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959
9960 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009961 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009962 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009963 if (PyUnicode_READY(string) == -1) {
9964 Py_DECREF(string);
9965 return NULL;
9966 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009967
Benjamin Petersonead6b532011-12-20 17:23:42 -06009968 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009970 if (PyUnicode_IS_ASCII(string))
9971 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009972 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009973 PyUnicode_GET_LENGTH(string), keepends);
9974 else
9975 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009976 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 break;
9979 case PyUnicode_2BYTE_KIND:
9980 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009981 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 PyUnicode_GET_LENGTH(string), keepends);
9983 break;
9984 case PyUnicode_4BYTE_KIND:
9985 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009986 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 PyUnicode_GET_LENGTH(string), keepends);
9988 break;
9989 default:
9990 assert(0);
9991 list = 0;
9992 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993 Py_DECREF(string);
9994 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995}
9996
Alexander Belopolsky40018472011-02-26 01:02:56 +00009997static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009998split(PyObject *self,
9999 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010000 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 int kind1, kind2, kind;
10003 void *buf1, *buf2;
10004 Py_ssize_t len1, len2;
10005 PyObject* out;
10006
Guido van Rossumd57fd912000-03-10 22:53:23 +000010007 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010008 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 if (PyUnicode_READY(self) == -1)
10011 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010014 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010016 if (PyUnicode_IS_ASCII(self))
10017 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010018 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010019 PyUnicode_GET_LENGTH(self), maxcount
10020 );
10021 else
10022 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010023 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010024 PyUnicode_GET_LENGTH(self), maxcount
10025 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 case PyUnicode_2BYTE_KIND:
10027 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010028 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 PyUnicode_GET_LENGTH(self), maxcount
10030 );
10031 case PyUnicode_4BYTE_KIND:
10032 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010033 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 PyUnicode_GET_LENGTH(self), maxcount
10035 );
10036 default:
10037 assert(0);
10038 return NULL;
10039 }
10040
10041 if (PyUnicode_READY(substring) == -1)
10042 return NULL;
10043
10044 kind1 = PyUnicode_KIND(self);
10045 kind2 = PyUnicode_KIND(substring);
10046 kind = kind1 > kind2 ? kind1 : kind2;
10047 buf1 = PyUnicode_DATA(self);
10048 buf2 = PyUnicode_DATA(substring);
10049 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010050 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 if (!buf1)
10052 return NULL;
10053 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010054 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 if (!buf2) {
10056 if (kind1 != kind) PyMem_Free(buf1);
10057 return NULL;
10058 }
10059 len1 = PyUnicode_GET_LENGTH(self);
10060 len2 = PyUnicode_GET_LENGTH(substring);
10061
Benjamin Petersonead6b532011-12-20 17:23:42 -060010062 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010064 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10065 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010066 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010067 else
10068 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010069 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 break;
10071 case PyUnicode_2BYTE_KIND:
10072 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010073 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 break;
10075 case PyUnicode_4BYTE_KIND:
10076 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010077 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 break;
10079 default:
10080 out = NULL;
10081 }
10082 if (kind1 != kind)
10083 PyMem_Free(buf1);
10084 if (kind2 != kind)
10085 PyMem_Free(buf2);
10086 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010087}
10088
Alexander Belopolsky40018472011-02-26 01:02:56 +000010089static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010090rsplit(PyObject *self,
10091 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010092 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 int kind1, kind2, kind;
10095 void *buf1, *buf2;
10096 Py_ssize_t len1, len2;
10097 PyObject* out;
10098
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010099 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010100 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (PyUnicode_READY(self) == -1)
10103 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010106 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010108 if (PyUnicode_IS_ASCII(self))
10109 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010110 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010111 PyUnicode_GET_LENGTH(self), maxcount
10112 );
10113 else
10114 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010115 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010116 PyUnicode_GET_LENGTH(self), maxcount
10117 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 case PyUnicode_2BYTE_KIND:
10119 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010120 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 PyUnicode_GET_LENGTH(self), maxcount
10122 );
10123 case PyUnicode_4BYTE_KIND:
10124 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010125 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 PyUnicode_GET_LENGTH(self), maxcount
10127 );
10128 default:
10129 assert(0);
10130 return NULL;
10131 }
10132
10133 if (PyUnicode_READY(substring) == -1)
10134 return NULL;
10135
10136 kind1 = PyUnicode_KIND(self);
10137 kind2 = PyUnicode_KIND(substring);
10138 kind = kind1 > kind2 ? kind1 : kind2;
10139 buf1 = PyUnicode_DATA(self);
10140 buf2 = PyUnicode_DATA(substring);
10141 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 if (!buf1)
10144 return NULL;
10145 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010146 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 if (!buf2) {
10148 if (kind1 != kind) PyMem_Free(buf1);
10149 return NULL;
10150 }
10151 len1 = PyUnicode_GET_LENGTH(self);
10152 len2 = PyUnicode_GET_LENGTH(substring);
10153
Benjamin Petersonead6b532011-12-20 17:23:42 -060010154 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010156 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10157 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010158 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010159 else
10160 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010161 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 break;
10163 case PyUnicode_2BYTE_KIND:
10164 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010165 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 break;
10167 case PyUnicode_4BYTE_KIND:
10168 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010169 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 break;
10171 default:
10172 out = NULL;
10173 }
10174 if (kind1 != kind)
10175 PyMem_Free(buf1);
10176 if (kind2 != kind)
10177 PyMem_Free(buf2);
10178 return out;
10179}
10180
10181static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010182anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10183 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010185 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010187 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10188 return asciilib_find(buf1, len1, buf2, len2, offset);
10189 else
10190 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 case PyUnicode_2BYTE_KIND:
10192 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10193 case PyUnicode_4BYTE_KIND:
10194 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10195 }
10196 assert(0);
10197 return -1;
10198}
10199
10200static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010201anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10202 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010204 switch (kind) {
10205 case PyUnicode_1BYTE_KIND:
10206 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10207 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10208 else
10209 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10210 case PyUnicode_2BYTE_KIND:
10211 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10212 case PyUnicode_4BYTE_KIND:
10213 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10214 }
10215 assert(0);
10216 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010217}
10218
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010219static void
10220replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10221 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10222{
10223 int kind = PyUnicode_KIND(u);
10224 void *data = PyUnicode_DATA(u);
10225 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10226 if (kind == PyUnicode_1BYTE_KIND) {
10227 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10228 (Py_UCS1 *)data + len,
10229 u1, u2, maxcount);
10230 }
10231 else if (kind == PyUnicode_2BYTE_KIND) {
10232 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10233 (Py_UCS2 *)data + len,
10234 u1, u2, maxcount);
10235 }
10236 else {
10237 assert(kind == PyUnicode_4BYTE_KIND);
10238 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10239 (Py_UCS4 *)data + len,
10240 u1, u2, maxcount);
10241 }
10242}
10243
Alexander Belopolsky40018472011-02-26 01:02:56 +000010244static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245replace(PyObject *self, PyObject *str1,
10246 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 PyObject *u;
10249 char *sbuf = PyUnicode_DATA(self);
10250 char *buf1 = PyUnicode_DATA(str1);
10251 char *buf2 = PyUnicode_DATA(str2);
10252 int srelease = 0, release1 = 0, release2 = 0;
10253 int skind = PyUnicode_KIND(self);
10254 int kind1 = PyUnicode_KIND(str1);
10255 int kind2 = PyUnicode_KIND(str2);
10256 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10257 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10258 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010259 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010260 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010261
10262 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010263 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010265 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010266
Victor Stinner59de0ee2011-10-07 10:01:28 +020010267 if (str1 == str2)
10268 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269
Victor Stinner49a0a212011-10-12 23:46:10 +020010270 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010271 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10272 if (maxchar < maxchar_str1)
10273 /* substring too wide to be present */
10274 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010275 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10276 /* Replacing str1 with str2 may cause a maxchar reduction in the
10277 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010278 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010279 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010284 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010286 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010287 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010288 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010289
Victor Stinner69ed0f42013-04-09 21:48:24 +020010290 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010291 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010292 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010293 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010294 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010296 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010298
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010299 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10300 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010301 }
10302 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 int rkind = skind;
10304 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010305 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 if (kind1 < rkind) {
10308 /* widen substring */
10309 buf1 = _PyUnicode_AsKind(str1, rkind);
10310 if (!buf1) goto error;
10311 release1 = 1;
10312 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010314 if (i < 0)
10315 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (rkind > kind2) {
10317 /* widen replacement */
10318 buf2 = _PyUnicode_AsKind(str2, rkind);
10319 if (!buf2) goto error;
10320 release2 = 1;
10321 }
10322 else if (rkind < kind2) {
10323 /* widen self and buf1 */
10324 rkind = kind2;
10325 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010326 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 sbuf = _PyUnicode_AsKind(self, rkind);
10328 if (!sbuf) goto error;
10329 srelease = 1;
10330 buf1 = _PyUnicode_AsKind(str1, rkind);
10331 if (!buf1) goto error;
10332 release1 = 1;
10333 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010334 u = PyUnicode_New(slen, maxchar);
10335 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010337 assert(PyUnicode_KIND(u) == rkind);
10338 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010339
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010340 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010341 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010342 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010344 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010346
10347 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010348 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010349 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010350 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010351 if (i == -1)
10352 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010353 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010355 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010357 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010359 }
10360 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010362 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 int rkind = skind;
10364 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010367 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 buf1 = _PyUnicode_AsKind(str1, rkind);
10369 if (!buf1) goto error;
10370 release1 = 1;
10371 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010373 if (n == 0)
10374 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010376 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 buf2 = _PyUnicode_AsKind(str2, rkind);
10378 if (!buf2) goto error;
10379 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010382 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 rkind = kind2;
10384 sbuf = _PyUnicode_AsKind(self, rkind);
10385 if (!sbuf) goto error;
10386 srelease = 1;
10387 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010388 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 buf1 = _PyUnicode_AsKind(str1, rkind);
10390 if (!buf1) goto error;
10391 release1 = 1;
10392 }
10393 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10394 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010395 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 PyErr_SetString(PyExc_OverflowError,
10397 "replace string is too long");
10398 goto error;
10399 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010400 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010401 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010402 _Py_INCREF_UNICODE_EMPTY();
10403 if (!unicode_empty)
10404 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010405 u = unicode_empty;
10406 goto done;
10407 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010408 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 PyErr_SetString(PyExc_OverflowError,
10410 "replace string is too long");
10411 goto error;
10412 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010413 u = PyUnicode_New(new_size, maxchar);
10414 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 assert(PyUnicode_KIND(u) == rkind);
10417 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 ires = i = 0;
10419 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010420 while (n-- > 0) {
10421 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010422 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010423 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010424 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010425 if (j == -1)
10426 break;
10427 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010428 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010429 memcpy(res + rkind * ires,
10430 sbuf + rkind * i,
10431 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010433 }
10434 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010436 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010438 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010444 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010445 memcpy(res + rkind * ires,
10446 sbuf + rkind * i,
10447 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010448 }
10449 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010450 /* interleave */
10451 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010452 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010454 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010456 if (--n <= 0)
10457 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 memcpy(res + rkind * ires,
10459 sbuf + rkind * i,
10460 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 ires++;
10462 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010464 memcpy(res + rkind * ires,
10465 sbuf + rkind * i,
10466 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010467 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010468 }
10469
10470 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010471 unicode_adjust_maxchar(&u);
10472 if (u == NULL)
10473 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010475
10476 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 if (srelease)
10478 PyMem_FREE(sbuf);
10479 if (release1)
10480 PyMem_FREE(buf1);
10481 if (release2)
10482 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010483 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010485
Benjamin Peterson29060642009-01-31 22:14:21 +000010486 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (srelease)
10489 PyMem_FREE(sbuf);
10490 if (release1)
10491 PyMem_FREE(buf1);
10492 if (release2)
10493 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010494 return unicode_result_unchanged(self);
10495
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 error:
10497 if (srelease && sbuf)
10498 PyMem_FREE(sbuf);
10499 if (release1 && buf1)
10500 PyMem_FREE(buf1);
10501 if (release2 && buf2)
10502 PyMem_FREE(buf2);
10503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504}
10505
10506/* --- Unicode Object Methods --------------------------------------------- */
10507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010508PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010509 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510\n\
10511Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010513
10514static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010515unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010516{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010517 if (PyUnicode_READY(self) == -1)
10518 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010519 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520}
10521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010522PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010523 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524\n\
10525Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010526have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010527
10528static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010529unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010531 if (PyUnicode_READY(self) == -1)
10532 return NULL;
10533 if (PyUnicode_GET_LENGTH(self) == 0)
10534 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010535 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536}
10537
Benjamin Petersond5890c82012-01-14 13:23:30 -050010538PyDoc_STRVAR(casefold__doc__,
10539 "S.casefold() -> str\n\
10540\n\
10541Return a version of S suitable for caseless comparisons.");
10542
10543static PyObject *
10544unicode_casefold(PyObject *self)
10545{
10546 if (PyUnicode_READY(self) == -1)
10547 return NULL;
10548 if (PyUnicode_IS_ASCII(self))
10549 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010550 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010551}
10552
10553
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010554/* Argument converter. Coerces to a single unicode character */
10555
10556static int
10557convert_uc(PyObject *obj, void *addr)
10558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010560 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010561
Benjamin Peterson14339b62009-01-31 16:36:08 +000010562 uniobj = PyUnicode_FromObject(obj);
10563 if (uniobj == NULL) {
10564 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010565 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010566 return 0;
10567 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010570 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010571 Py_DECREF(uniobj);
10572 return 0;
10573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575 Py_DECREF(uniobj);
10576 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010577}
10578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010579PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010580 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010581\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010582Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010583done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584
10585static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010586unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010587{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010588 Py_ssize_t marg, left;
10589 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 Py_UCS4 fillchar = ' ';
10591
Victor Stinnere9a29352011-10-01 02:14:59 +020010592 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594
Benjamin Petersonbac79492012-01-14 13:34:47 -050010595 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596 return NULL;
10597
Victor Stinnerc4b49542011-12-11 22:44:26 +010010598 if (PyUnicode_GET_LENGTH(self) >= width)
10599 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600
Victor Stinnerc4b49542011-12-11 22:44:26 +010010601 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602 left = marg / 2 + (marg & width & 1);
10603
Victor Stinner9310abb2011-10-05 00:59:23 +020010604 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605}
10606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607/* This function assumes that str1 and str2 are readied by the caller. */
10608
Marc-André Lemburge5034372000-08-08 08:04:29 +000010609static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010610unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010611{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010612#define COMPARE(TYPE1, TYPE2) \
10613 do { \
10614 TYPE1* p1 = (TYPE1 *)data1; \
10615 TYPE2* p2 = (TYPE2 *)data2; \
10616 TYPE1* end = p1 + len; \
10617 Py_UCS4 c1, c2; \
10618 for (; p1 != end; p1++, p2++) { \
10619 c1 = *p1; \
10620 c2 = *p2; \
10621 if (c1 != c2) \
10622 return (c1 < c2) ? -1 : 1; \
10623 } \
10624 } \
10625 while (0)
10626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 int kind1, kind2;
10628 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010629 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 kind1 = PyUnicode_KIND(str1);
10632 kind2 = PyUnicode_KIND(str2);
10633 data1 = PyUnicode_DATA(str1);
10634 data2 = PyUnicode_DATA(str2);
10635 len1 = PyUnicode_GET_LENGTH(str1);
10636 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010637 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010638
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010639 switch(kind1) {
10640 case PyUnicode_1BYTE_KIND:
10641 {
10642 switch(kind2) {
10643 case PyUnicode_1BYTE_KIND:
10644 {
10645 int cmp = memcmp(data1, data2, len);
10646 /* normalize result of memcmp() into the range [-1; 1] */
10647 if (cmp < 0)
10648 return -1;
10649 if (cmp > 0)
10650 return 1;
10651 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010652 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010653 case PyUnicode_2BYTE_KIND:
10654 COMPARE(Py_UCS1, Py_UCS2);
10655 break;
10656 case PyUnicode_4BYTE_KIND:
10657 COMPARE(Py_UCS1, Py_UCS4);
10658 break;
10659 default:
10660 assert(0);
10661 }
10662 break;
10663 }
10664 case PyUnicode_2BYTE_KIND:
10665 {
10666 switch(kind2) {
10667 case PyUnicode_1BYTE_KIND:
10668 COMPARE(Py_UCS2, Py_UCS1);
10669 break;
10670 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010671 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010672 COMPARE(Py_UCS2, Py_UCS2);
10673 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010674 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010675 case PyUnicode_4BYTE_KIND:
10676 COMPARE(Py_UCS2, Py_UCS4);
10677 break;
10678 default:
10679 assert(0);
10680 }
10681 break;
10682 }
10683 case PyUnicode_4BYTE_KIND:
10684 {
10685 switch(kind2) {
10686 case PyUnicode_1BYTE_KIND:
10687 COMPARE(Py_UCS4, Py_UCS1);
10688 break;
10689 case PyUnicode_2BYTE_KIND:
10690 COMPARE(Py_UCS4, Py_UCS2);
10691 break;
10692 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010693 {
10694#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10695 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10696 /* normalize result of wmemcmp() into the range [-1; 1] */
10697 if (cmp < 0)
10698 return -1;
10699 if (cmp > 0)
10700 return 1;
10701#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010702 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010703#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010704 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010705 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010706 default:
10707 assert(0);
10708 }
10709 break;
10710 }
10711 default:
10712 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010713 }
10714
Victor Stinner770e19e2012-10-04 22:59:45 +020010715 if (len1 == len2)
10716 return 0;
10717 if (len1 < len2)
10718 return -1;
10719 else
10720 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010721
10722#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010723}
10724
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010725Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010726unicode_compare_eq(PyObject *str1, PyObject *str2)
10727{
10728 int kind;
10729 void *data1, *data2;
10730 Py_ssize_t len;
10731 int cmp;
10732
Victor Stinnere5567ad2012-10-23 02:48:49 +020010733 len = PyUnicode_GET_LENGTH(str1);
10734 if (PyUnicode_GET_LENGTH(str2) != len)
10735 return 0;
10736 kind = PyUnicode_KIND(str1);
10737 if (PyUnicode_KIND(str2) != kind)
10738 return 0;
10739 data1 = PyUnicode_DATA(str1);
10740 data2 = PyUnicode_DATA(str2);
10741
10742 cmp = memcmp(data1, data2, len * kind);
10743 return (cmp == 0);
10744}
10745
10746
Alexander Belopolsky40018472011-02-26 01:02:56 +000010747int
10748PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10751 if (PyUnicode_READY(left) == -1 ||
10752 PyUnicode_READY(right) == -1)
10753 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010754
10755 /* a string is equal to itself */
10756 if (left == right)
10757 return 0;
10758
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010759 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010761 PyErr_Format(PyExc_TypeError,
10762 "Can't compare %.100s and %.100s",
10763 left->ob_type->tp_name,
10764 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765 return -1;
10766}
10767
Martin v. Löwis5b222132007-06-10 09:51:05 +000010768int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010769_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10770{
10771 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10772 if (right_str == NULL)
10773 return -1;
10774 return PyUnicode_Compare(left, right_str);
10775}
10776
10777int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010778PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 Py_ssize_t i;
10781 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 Py_UCS4 chr;
10783
Victor Stinner910337b2011-10-03 03:20:16 +020010784 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 if (PyUnicode_READY(uni) == -1)
10786 return -1;
10787 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010788 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010789 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010790 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010791 size_t len, len2 = strlen(str);
10792 int cmp;
10793
10794 len = Py_MIN(len1, len2);
10795 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010796 if (cmp != 0) {
10797 if (cmp < 0)
10798 return -1;
10799 else
10800 return 1;
10801 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010802 if (len1 > len2)
10803 return 1; /* uni is longer */
10804 if (len2 > len1)
10805 return -1; /* str is longer */
10806 return 0;
10807 }
10808 else {
10809 void *data = PyUnicode_DATA(uni);
10810 /* Compare Unicode string and source character set string */
10811 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10812 if (chr != str[i])
10813 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10814 /* This check keeps Python strings that end in '\0' from comparing equal
10815 to C strings identical up to that point. */
10816 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10817 return 1; /* uni is longer */
10818 if (str[i])
10819 return -1; /* str is longer */
10820 return 0;
10821 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010822}
10823
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010824
Benjamin Peterson29060642009-01-31 22:14:21 +000010825#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010826 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010827
Alexander Belopolsky40018472011-02-26 01:02:56 +000010828PyObject *
10829PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010830{
10831 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010832 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010833
Victor Stinnere5567ad2012-10-23 02:48:49 +020010834 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10835 Py_RETURN_NOTIMPLEMENTED;
10836
10837 if (PyUnicode_READY(left) == -1 ||
10838 PyUnicode_READY(right) == -1)
10839 return NULL;
10840
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010841 if (left == right) {
10842 switch (op) {
10843 case Py_EQ:
10844 case Py_LE:
10845 case Py_GE:
10846 /* a string is equal to itself */
10847 v = Py_True;
10848 break;
10849 case Py_NE:
10850 case Py_LT:
10851 case Py_GT:
10852 v = Py_False;
10853 break;
10854 default:
10855 PyErr_BadArgument();
10856 return NULL;
10857 }
10858 }
10859 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010860 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010861 result ^= (op == Py_NE);
10862 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010863 }
10864 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010865 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010866
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010867 /* Convert the return value to a Boolean */
10868 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010869 case Py_LE:
10870 v = TEST_COND(result <= 0);
10871 break;
10872 case Py_GE:
10873 v = TEST_COND(result >= 0);
10874 break;
10875 case Py_LT:
10876 v = TEST_COND(result == -1);
10877 break;
10878 case Py_GT:
10879 v = TEST_COND(result == 1);
10880 break;
10881 default:
10882 PyErr_BadArgument();
10883 return NULL;
10884 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010885 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010886 Py_INCREF(v);
10887 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010888}
10889
Alexander Belopolsky40018472011-02-26 01:02:56 +000010890int
10891PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010892{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010893 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010894 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 void *buf1, *buf2;
10896 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010897 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010898
10899 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010900 sub = PyUnicode_FromObject(element);
10901 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 PyErr_Format(PyExc_TypeError,
10903 "'in <string>' requires string as left operand, not %s",
10904 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010905 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010906 }
10907
Thomas Wouters477c8d52006-05-27 19:21:47 +000010908 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010909 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010910 Py_DECREF(sub);
10911 return -1;
10912 }
10913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010914 kind1 = PyUnicode_KIND(str);
10915 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010916 buf1 = PyUnicode_DATA(str);
10917 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010918 if (kind2 != kind1) {
10919 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010920 Py_DECREF(sub);
10921 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010922 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010923 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010924 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010925 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 if (!buf2) {
10927 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010928 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 return -1;
10930 }
10931 len1 = PyUnicode_GET_LENGTH(str);
10932 len2 = PyUnicode_GET_LENGTH(sub);
10933
Victor Stinner77282cb2013-04-14 19:22:47 +020010934 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010935 case PyUnicode_1BYTE_KIND:
10936 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10937 break;
10938 case PyUnicode_2BYTE_KIND:
10939 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10940 break;
10941 case PyUnicode_4BYTE_KIND:
10942 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10943 break;
10944 default:
10945 result = -1;
10946 assert(0);
10947 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010948
10949 Py_DECREF(str);
10950 Py_DECREF(sub);
10951
Victor Stinner77282cb2013-04-14 19:22:47 +020010952 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953 PyMem_Free(buf2);
10954
Guido van Rossum403d68b2000-03-13 15:55:09 +000010955 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010956}
10957
Guido van Rossumd57fd912000-03-10 22:53:23 +000010958/* Concat to string or Unicode object giving a new Unicode object. */
10959
Alexander Belopolsky40018472011-02-26 01:02:56 +000010960PyObject *
10961PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010964 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010965 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010966
10967 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010970 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010971 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010973 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974
10975 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010976 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010977 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010980 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010981 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983 }
10984
Victor Stinner488fa492011-12-12 00:01:39 +010010985 u_len = PyUnicode_GET_LENGTH(u);
10986 v_len = PyUnicode_GET_LENGTH(v);
10987 if (u_len > PY_SSIZE_T_MAX - v_len) {
10988 PyErr_SetString(PyExc_OverflowError,
10989 "strings are too large to concat");
10990 goto onError;
10991 }
10992 new_len = u_len + v_len;
10993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010994 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010995 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010996 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010999 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011001 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011002 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11003 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011004 Py_DECREF(u);
11005 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011006 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008
Benjamin Peterson29060642009-01-31 22:14:21 +000011009 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010 Py_XDECREF(u);
11011 Py_XDECREF(v);
11012 return NULL;
11013}
11014
Walter Dörwald1ab83302007-05-18 17:15:44 +000011015void
Victor Stinner23e56682011-10-03 03:54:37 +020011016PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011017{
Victor Stinner23e56682011-10-03 03:54:37 +020011018 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011019 Py_UCS4 maxchar, maxchar2;
11020 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011021
11022 if (p_left == NULL) {
11023 if (!PyErr_Occurred())
11024 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011025 return;
11026 }
Victor Stinner23e56682011-10-03 03:54:37 +020011027 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011028 if (right == NULL || left == NULL
11029 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011030 if (!PyErr_Occurred())
11031 PyErr_BadInternalCall();
11032 goto error;
11033 }
11034
Benjamin Petersonbac79492012-01-14 13:34:47 -050011035 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011036 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011037 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011038 goto error;
11039
Victor Stinner488fa492011-12-12 00:01:39 +010011040 /* Shortcuts */
11041 if (left == unicode_empty) {
11042 Py_DECREF(left);
11043 Py_INCREF(right);
11044 *p_left = right;
11045 return;
11046 }
11047 if (right == unicode_empty)
11048 return;
11049
11050 left_len = PyUnicode_GET_LENGTH(left);
11051 right_len = PyUnicode_GET_LENGTH(right);
11052 if (left_len > PY_SSIZE_T_MAX - right_len) {
11053 PyErr_SetString(PyExc_OverflowError,
11054 "strings are too large to concat");
11055 goto error;
11056 }
11057 new_len = left_len + right_len;
11058
11059 if (unicode_modifiable(left)
11060 && PyUnicode_CheckExact(right)
11061 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011062 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11063 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011064 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011065 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011066 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11067 {
11068 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011069 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011070 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011071
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011072 /* copy 'right' into the newly allocated area of 'left' */
11073 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011074 }
Victor Stinner488fa492011-12-12 00:01:39 +010011075 else {
11076 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11077 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011078 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011079
Victor Stinner488fa492011-12-12 00:01:39 +010011080 /* Concat the two Unicode strings */
11081 res = PyUnicode_New(new_len, maxchar);
11082 if (res == NULL)
11083 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011084 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11085 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011086 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011087 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011088 }
11089 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011090 return;
11091
11092error:
Victor Stinner488fa492011-12-12 00:01:39 +010011093 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011094}
11095
11096void
11097PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11098{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011099 PyUnicode_Append(pleft, right);
11100 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011101}
11102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011103PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011104 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011106Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011107string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011108interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
11110static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011111unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011113 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011114 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011115 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 int kind1, kind2, kind;
11118 void *buf1, *buf2;
11119 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120
Jesus Ceaac451502011-04-20 17:09:23 +020011121 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11122 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011123 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011125 kind1 = PyUnicode_KIND(self);
11126 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011127 if (kind2 > kind1) {
11128 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011129 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011130 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011131 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011132 buf1 = PyUnicode_DATA(self);
11133 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011135 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 if (!buf2) {
11137 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 return NULL;
11139 }
11140 len1 = PyUnicode_GET_LENGTH(self);
11141 len2 = PyUnicode_GET_LENGTH(substring);
11142
11143 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011144 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 case PyUnicode_1BYTE_KIND:
11146 iresult = ucs1lib_count(
11147 ((Py_UCS1*)buf1) + start, end - start,
11148 buf2, len2, PY_SSIZE_T_MAX
11149 );
11150 break;
11151 case PyUnicode_2BYTE_KIND:
11152 iresult = ucs2lib_count(
11153 ((Py_UCS2*)buf1) + start, end - start,
11154 buf2, len2, PY_SSIZE_T_MAX
11155 );
11156 break;
11157 case PyUnicode_4BYTE_KIND:
11158 iresult = ucs4lib_count(
11159 ((Py_UCS4*)buf1) + start, end - start,
11160 buf2, len2, PY_SSIZE_T_MAX
11161 );
11162 break;
11163 default:
11164 assert(0); iresult = 0;
11165 }
11166
11167 result = PyLong_FromSsize_t(iresult);
11168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 if (kind2 != kind)
11170 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171
11172 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011173
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174 return result;
11175}
11176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011177PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011178 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011180Encode S using the codec registered for encoding. Default encoding\n\
11181is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011182handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011183a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11184'xmlcharrefreplace' as well as any other name registered with\n\
11185codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186
11187static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011188unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011190 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 char *encoding = NULL;
11192 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011193
Benjamin Peterson308d6372009-09-18 21:42:35 +000011194 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11195 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011197 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011198}
11199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011200PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011201 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202\n\
11203Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011204If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205
11206static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011207unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011209 Py_ssize_t i, j, line_pos, src_len, incr;
11210 Py_UCS4 ch;
11211 PyObject *u;
11212 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011213 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011215 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011216 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217
Ezio Melotti745d54d2013-11-16 19:10:57 +020011218 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11219 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011220 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221
Antoine Pitrou22425222011-10-04 19:10:51 +020011222 if (PyUnicode_READY(self) == -1)
11223 return NULL;
11224
Thomas Wouters7e474022000-07-16 12:04:32 +000011225 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011226 src_len = PyUnicode_GET_LENGTH(self);
11227 i = j = line_pos = 0;
11228 kind = PyUnicode_KIND(self);
11229 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011230 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011231 for (; i < src_len; i++) {
11232 ch = PyUnicode_READ(kind, src_data, i);
11233 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011234 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011235 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011236 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011237 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011238 goto overflow;
11239 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011240 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011241 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011244 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011245 goto overflow;
11246 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 if (ch == '\n' || ch == '\r')
11249 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011251 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011252 if (!found)
11253 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011254
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011256 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257 if (!u)
11258 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011259 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260
Antoine Pitroue71d5742011-10-04 15:55:09 +020011261 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 for (; i < src_len; i++) {
11264 ch = PyUnicode_READ(kind, src_data, i);
11265 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011267 incr = tabsize - (line_pos % tabsize);
11268 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011269 FILL(kind, dest_data, ' ', j, incr);
11270 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011272 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011274 line_pos++;
11275 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011276 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011277 if (ch == '\n' || ch == '\r')
11278 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011280 }
11281 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011282 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011283
Antoine Pitroue71d5742011-10-04 15:55:09 +020011284 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011285 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11286 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287}
11288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011289PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291\n\
11292Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011293such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294arguments start and end are interpreted as in slice notation.\n\
11295\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011296Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297
11298static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011301 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011302 Py_ssize_t start;
11303 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011304 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305
Jesus Ceaac451502011-04-20 17:09:23 +020011306 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11307 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309
Christian Heimesd47802e2013-06-29 21:33:36 +020011310 if (PyUnicode_READY(self) == -1) {
11311 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011313 }
11314 if (PyUnicode_READY(substring) == -1) {
11315 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011316 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011317 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318
Victor Stinner7931d9a2011-11-04 00:22:48 +010011319 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320
11321 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 if (result == -2)
11324 return NULL;
11325
Christian Heimes217cfd12007-12-02 14:31:20 +000011326 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327}
11328
11329static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011330unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011332 void *data;
11333 enum PyUnicode_Kind kind;
11334 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011335
11336 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11337 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011339 }
11340 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11341 PyErr_SetString(PyExc_IndexError, "string index out of range");
11342 return NULL;
11343 }
11344 kind = PyUnicode_KIND(self);
11345 data = PyUnicode_DATA(self);
11346 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011347 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348}
11349
Guido van Rossumc2504932007-09-18 19:42:40 +000011350/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011351 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011352static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011353unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354{
Guido van Rossumc2504932007-09-18 19:42:40 +000011355 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011356 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011357
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011358#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011359 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011360#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 if (_PyUnicode_HASH(self) != -1)
11362 return _PyUnicode_HASH(self);
11363 if (PyUnicode_READY(self) == -1)
11364 return -1;
11365 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011366 /*
11367 We make the hash of the empty string be 0, rather than using
11368 (prefix ^ suffix), since this slightly obfuscates the hash secret
11369 */
11370 if (len == 0) {
11371 _PyUnicode_HASH(self) = 0;
11372 return 0;
11373 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011374 x = _Py_HashBytes(PyUnicode_DATA(self),
11375 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011377 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378}
11379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011380PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011381 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011383Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384
11385static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011388 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011389 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011390 Py_ssize_t start;
11391 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392
Jesus Ceaac451502011-04-20 17:09:23 +020011393 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11394 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396
Christian Heimesd47a0452013-06-29 21:21:37 +020011397 if (PyUnicode_READY(self) == -1) {
11398 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011400 }
11401 if (PyUnicode_READY(substring) == -1) {
11402 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011404 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405
Victor Stinner7931d9a2011-11-04 00:22:48 +010011406 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 if (result == -2)
11411 return NULL;
11412
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413 if (result < 0) {
11414 PyErr_SetString(PyExc_ValueError, "substring not found");
11415 return NULL;
11416 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011417
Christian Heimes217cfd12007-12-02 14:31:20 +000011418 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419}
11420
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011421PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011424Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011425at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
11427static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011428unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011430 Py_ssize_t i, length;
11431 int kind;
11432 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 int cased;
11434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 if (PyUnicode_READY(self) == -1)
11436 return NULL;
11437 length = PyUnicode_GET_LENGTH(self);
11438 kind = PyUnicode_KIND(self);
11439 data = PyUnicode_DATA(self);
11440
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 if (length == 1)
11443 return PyBool_FromLong(
11444 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011446 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011449
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 for (i = 0; i < length; i++) {
11452 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011453
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11455 return PyBool_FromLong(0);
11456 else if (!cased && Py_UNICODE_ISLOWER(ch))
11457 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011459 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460}
11461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011462PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011463 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011465Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011466at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467
11468static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011469unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 Py_ssize_t i, length;
11472 int kind;
11473 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 int cased;
11475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (PyUnicode_READY(self) == -1)
11477 return NULL;
11478 length = PyUnicode_GET_LENGTH(self);
11479 kind = PyUnicode_KIND(self);
11480 data = PyUnicode_DATA(self);
11481
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011483 if (length == 1)
11484 return PyBool_FromLong(
11485 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011487 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011490
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011492 for (i = 0; i < length; i++) {
11493 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011494
Benjamin Peterson29060642009-01-31 22:14:21 +000011495 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11496 return PyBool_FromLong(0);
11497 else if (!cased && Py_UNICODE_ISUPPER(ch))
11498 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011500 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501}
11502
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011503PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011504 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011506Return True if S is a titlecased string and there is at least one\n\
11507character in S, i.e. upper- and titlecase characters may only\n\
11508follow uncased characters and lowercase characters only cased ones.\n\
11509Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
11511static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011512unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 Py_ssize_t i, length;
11515 int kind;
11516 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 int cased, previous_is_cased;
11518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 if (PyUnicode_READY(self) == -1)
11520 return NULL;
11521 length = PyUnicode_GET_LENGTH(self);
11522 kind = PyUnicode_KIND(self);
11523 data = PyUnicode_DATA(self);
11524
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 if (length == 1) {
11527 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11528 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11529 (Py_UNICODE_ISUPPER(ch) != 0));
11530 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011532 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011534 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011535
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536 cased = 0;
11537 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 for (i = 0; i < length; i++) {
11539 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011540
Benjamin Peterson29060642009-01-31 22:14:21 +000011541 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11542 if (previous_is_cased)
11543 return PyBool_FromLong(0);
11544 previous_is_cased = 1;
11545 cased = 1;
11546 }
11547 else if (Py_UNICODE_ISLOWER(ch)) {
11548 if (!previous_is_cased)
11549 return PyBool_FromLong(0);
11550 previous_is_cased = 1;
11551 cased = 1;
11552 }
11553 else
11554 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011556 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557}
11558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011559PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011560 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011562Return True if all characters in S are whitespace\n\
11563and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
11565static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011566unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 Py_ssize_t i, length;
11569 int kind;
11570 void *data;
11571
11572 if (PyUnicode_READY(self) == -1)
11573 return NULL;
11574 length = PyUnicode_GET_LENGTH(self);
11575 kind = PyUnicode_KIND(self);
11576 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 if (length == 1)
11580 return PyBool_FromLong(
11581 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011583 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011584 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011585 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011586
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011587 for (i = 0; i < length; i++) {
11588 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011589 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011592 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593}
11594
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011595PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011596 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011597\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011598Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011599and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011600
11601static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011602unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 Py_ssize_t i, length;
11605 int kind;
11606 void *data;
11607
11608 if (PyUnicode_READY(self) == -1)
11609 return NULL;
11610 length = PyUnicode_GET_LENGTH(self);
11611 kind = PyUnicode_KIND(self);
11612 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011613
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011614 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 if (length == 1)
11616 return PyBool_FromLong(
11617 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011618
11619 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011621 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623 for (i = 0; i < length; i++) {
11624 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011626 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011627 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011628}
11629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011630PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011631 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011632\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011633Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011634and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011635
11636static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011637unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011638{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 int kind;
11640 void *data;
11641 Py_ssize_t len, i;
11642
11643 if (PyUnicode_READY(self) == -1)
11644 return NULL;
11645
11646 kind = PyUnicode_KIND(self);
11647 data = PyUnicode_DATA(self);
11648 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011650 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 if (len == 1) {
11652 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11653 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11654 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011655
11656 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 for (i = 0; i < len; i++) {
11661 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011662 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011663 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011664 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011665 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011666}
11667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011668PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011669 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011671Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011672False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673
11674static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011675unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 Py_ssize_t i, length;
11678 int kind;
11679 void *data;
11680
11681 if (PyUnicode_READY(self) == -1)
11682 return NULL;
11683 length = PyUnicode_GET_LENGTH(self);
11684 kind = PyUnicode_KIND(self);
11685 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 if (length == 1)
11689 return PyBool_FromLong(
11690 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011692 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 for (i = 0; i < length; i++) {
11697 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011698 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011700 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701}
11702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011703PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011704 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011706Return True if all characters in S are digits\n\
11707and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708
11709static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011710unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 Py_ssize_t i, length;
11713 int kind;
11714 void *data;
11715
11716 if (PyUnicode_READY(self) == -1)
11717 return NULL;
11718 length = PyUnicode_GET_LENGTH(self);
11719 kind = PyUnicode_KIND(self);
11720 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 if (length == 1) {
11724 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11725 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11726 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011728 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011730 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732 for (i = 0; i < length; i++) {
11733 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011736 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737}
11738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011739PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011740 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011742Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011743False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744
11745static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011746unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 Py_ssize_t i, length;
11749 int kind;
11750 void *data;
11751
11752 if (PyUnicode_READY(self) == -1)
11753 return NULL;
11754 length = PyUnicode_GET_LENGTH(self);
11755 kind = PyUnicode_KIND(self);
11756 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 if (length == 1)
11760 return PyBool_FromLong(
11761 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011763 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011765 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 for (i = 0; i < length; i++) {
11768 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011769 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011771 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772}
11773
Martin v. Löwis47383402007-08-15 07:32:56 +000011774int
11775PyUnicode_IsIdentifier(PyObject *self)
11776{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 int kind;
11778 void *data;
11779 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011780 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 if (PyUnicode_READY(self) == -1) {
11783 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011784 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 }
11786
11787 /* Special case for empty strings */
11788 if (PyUnicode_GET_LENGTH(self) == 0)
11789 return 0;
11790 kind = PyUnicode_KIND(self);
11791 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011792
11793 /* PEP 3131 says that the first character must be in
11794 XID_Start and subsequent characters in XID_Continue,
11795 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011796 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011797 letters, digits, underscore). However, given the current
11798 definition of XID_Start and XID_Continue, it is sufficient
11799 to check just for these, except that _ must be allowed
11800 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011802 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011803 return 0;
11804
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011805 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011807 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011808 return 1;
11809}
11810
11811PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011812 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011813\n\
11814Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011815to the language definition.\n\
11816\n\
11817Use keyword.iskeyword() to test for reserved identifiers\n\
11818such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011819
11820static PyObject*
11821unicode_isidentifier(PyObject *self)
11822{
11823 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11824}
11825
Georg Brandl559e5d72008-06-11 18:37:52 +000011826PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011828\n\
11829Return True if all characters in S are considered\n\
11830printable in repr() or S is empty, False otherwise.");
11831
11832static PyObject*
11833unicode_isprintable(PyObject *self)
11834{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 Py_ssize_t i, length;
11836 int kind;
11837 void *data;
11838
11839 if (PyUnicode_READY(self) == -1)
11840 return NULL;
11841 length = PyUnicode_GET_LENGTH(self);
11842 kind = PyUnicode_KIND(self);
11843 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011844
11845 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 if (length == 1)
11847 return PyBool_FromLong(
11848 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 for (i = 0; i < length; i++) {
11851 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011852 Py_RETURN_FALSE;
11853 }
11854 }
11855 Py_RETURN_TRUE;
11856}
11857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011858PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011859 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860\n\
11861Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011862iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863
11864static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011865unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011867 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868}
11869
Martin v. Löwis18e16552006-02-15 17:27:45 +000011870static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011871unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 if (PyUnicode_READY(self) == -1)
11874 return -1;
11875 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876}
11877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011878PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011881Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011882done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883
11884static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011885unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011887 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 Py_UCS4 fillchar = ' ';
11889
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011890 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891 return NULL;
11892
Benjamin Petersonbac79492012-01-14 13:34:47 -050011893 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011894 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895
Victor Stinnerc4b49542011-12-11 22:44:26 +010011896 if (PyUnicode_GET_LENGTH(self) >= width)
11897 return unicode_result_unchanged(self);
11898
11899 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900}
11901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011902PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011903 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011905Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906
11907static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011908unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011910 if (PyUnicode_READY(self) == -1)
11911 return NULL;
11912 if (PyUnicode_IS_ASCII(self))
11913 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011914 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915}
11916
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011917#define LEFTSTRIP 0
11918#define RIGHTSTRIP 1
11919#define BOTHSTRIP 2
11920
11921/* Arrays indexed by above */
11922static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11923
11924#define STRIPNAME(i) (stripformat[i]+3)
11925
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011926/* externally visible for str.strip(unicode) */
11927PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011928_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011929{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 void *data;
11931 int kind;
11932 Py_ssize_t i, j, len;
11933 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011934 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011936 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11937 return NULL;
11938
11939 kind = PyUnicode_KIND(self);
11940 data = PyUnicode_DATA(self);
11941 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011942 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11944 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011945 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011946
Benjamin Peterson14339b62009-01-31 16:36:08 +000011947 i = 0;
11948 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011949 while (i < len) {
11950 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11951 if (!BLOOM(sepmask, ch))
11952 break;
11953 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11954 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 i++;
11956 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011957 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011958
Benjamin Peterson14339b62009-01-31 16:36:08 +000011959 j = len;
11960 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011961 j--;
11962 while (j >= i) {
11963 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11964 if (!BLOOM(sepmask, ch))
11965 break;
11966 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11967 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011968 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011969 }
11970
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011972 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011973
Victor Stinner7931d9a2011-11-04 00:22:48 +010011974 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975}
11976
11977PyObject*
11978PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11979{
11980 unsigned char *data;
11981 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011982 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983
Victor Stinnerde636f32011-10-01 03:55:54 +020011984 if (PyUnicode_READY(self) == -1)
11985 return NULL;
11986
Victor Stinner684d5fd2012-05-03 02:32:34 +020011987 length = PyUnicode_GET_LENGTH(self);
11988 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020011989
Victor Stinner684d5fd2012-05-03 02:32:34 +020011990 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011991 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992
Victor Stinnerde636f32011-10-01 03:55:54 +020011993 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011994 PyErr_SetString(PyExc_IndexError, "string index out of range");
11995 return NULL;
11996 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020011997 if (start >= length || end < start)
11998 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020011999
Victor Stinner684d5fd2012-05-03 02:32:34 +020012000 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012001 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012002 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012003 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012004 }
12005 else {
12006 kind = PyUnicode_KIND(self);
12007 data = PyUnicode_1BYTE_DATA(self);
12008 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012009 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012010 length);
12011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013
12014static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012015do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012017 Py_ssize_t len, i, j;
12018
12019 if (PyUnicode_READY(self) == -1)
12020 return NULL;
12021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012023
Victor Stinnercc7af722013-04-09 22:39:24 +020012024 if (PyUnicode_IS_ASCII(self)) {
12025 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12026
12027 i = 0;
12028 if (striptype != RIGHTSTRIP) {
12029 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012030 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012031 if (!_Py_ascii_whitespace[ch])
12032 break;
12033 i++;
12034 }
12035 }
12036
12037 j = len;
12038 if (striptype != LEFTSTRIP) {
12039 j--;
12040 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012041 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012042 if (!_Py_ascii_whitespace[ch])
12043 break;
12044 j--;
12045 }
12046 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012047 }
12048 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012049 else {
12050 int kind = PyUnicode_KIND(self);
12051 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012052
Victor Stinnercc7af722013-04-09 22:39:24 +020012053 i = 0;
12054 if (striptype != RIGHTSTRIP) {
12055 while (i < len) {
12056 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12057 if (!Py_UNICODE_ISSPACE(ch))
12058 break;
12059 i++;
12060 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012061 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012062
12063 j = len;
12064 if (striptype != LEFTSTRIP) {
12065 j--;
12066 while (j >= i) {
12067 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12068 if (!Py_UNICODE_ISSPACE(ch))
12069 break;
12070 j--;
12071 }
12072 j++;
12073 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012074 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012075
Victor Stinner7931d9a2011-11-04 00:22:48 +010012076 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077}
12078
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012079
12080static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012081do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012082{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012083 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012084
Serhiy Storchakac6792272013-10-19 21:03:34 +030012085 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012086 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012087
Benjamin Peterson14339b62009-01-31 16:36:08 +000012088 if (sep != NULL && sep != Py_None) {
12089 if (PyUnicode_Check(sep))
12090 return _PyUnicode_XStrip(self, striptype, sep);
12091 else {
12092 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012093 "%s arg must be None or str",
12094 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012095 return NULL;
12096 }
12097 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012098
Benjamin Peterson14339b62009-01-31 16:36:08 +000012099 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012100}
12101
12102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012103PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012104 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012105\n\
12106Return a copy of the string S with leading and trailing\n\
12107whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012108If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012109
12110static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012111unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012112{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012113 if (PyTuple_GET_SIZE(args) == 0)
12114 return do_strip(self, BOTHSTRIP); /* Common case */
12115 else
12116 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012117}
12118
12119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012120PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012121 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122\n\
12123Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012124If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012125
12126static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012127unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012128{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012129 if (PyTuple_GET_SIZE(args) == 0)
12130 return do_strip(self, LEFTSTRIP); /* Common case */
12131 else
12132 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133}
12134
12135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012136PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012137 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012138\n\
12139Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012140If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141
12142static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012143unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012144{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012145 if (PyTuple_GET_SIZE(args) == 0)
12146 return do_strip(self, RIGHTSTRIP); /* Common case */
12147 else
12148 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012149}
12150
12151
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012153unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012155 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157
Serhiy Storchaka05997252013-01-26 12:14:02 +020012158 if (len < 1)
12159 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160
Victor Stinnerc4b49542011-12-11 22:44:26 +010012161 /* no repeat, return original string */
12162 if (len == 1)
12163 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012164
Benjamin Petersonbac79492012-01-14 13:34:47 -050012165 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 return NULL;
12167
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012168 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012169 PyErr_SetString(PyExc_OverflowError,
12170 "repeated string is too long");
12171 return NULL;
12172 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012174
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012175 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176 if (!u)
12177 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012178 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 if (PyUnicode_GET_LENGTH(str) == 1) {
12181 const int kind = PyUnicode_KIND(str);
12182 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012183 if (kind == PyUnicode_1BYTE_KIND) {
12184 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012185 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012186 }
12187 else if (kind == PyUnicode_2BYTE_KIND) {
12188 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012189 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012190 ucs2[n] = fill_char;
12191 } else {
12192 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12193 assert(kind == PyUnicode_4BYTE_KIND);
12194 for (n = 0; n < len; ++n)
12195 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012197 }
12198 else {
12199 /* number of characters copied this far */
12200 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012201 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 char *to = (char *) PyUnicode_DATA(u);
12203 Py_MEMCPY(to, PyUnicode_DATA(str),
12204 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012205 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 n = (done <= nchars-done) ? done : nchars-done;
12207 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012208 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012209 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210 }
12211
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012212 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012213 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214}
12215
Alexander Belopolsky40018472011-02-26 01:02:56 +000012216PyObject *
12217PyUnicode_Replace(PyObject *obj,
12218 PyObject *subobj,
12219 PyObject *replobj,
12220 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221{
12222 PyObject *self;
12223 PyObject *str1;
12224 PyObject *str2;
12225 PyObject *result;
12226
12227 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012228 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012229 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012231 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012232 Py_DECREF(self);
12233 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234 }
12235 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012236 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012237 Py_DECREF(self);
12238 Py_DECREF(str1);
12239 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012241 if (PyUnicode_READY(self) == -1 ||
12242 PyUnicode_READY(str1) == -1 ||
12243 PyUnicode_READY(str2) == -1)
12244 result = NULL;
12245 else
12246 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247 Py_DECREF(self);
12248 Py_DECREF(str1);
12249 Py_DECREF(str2);
12250 return result;
12251}
12252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012253PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012254 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255\n\
12256Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012257old replaced by new. If the optional argument count is\n\
12258given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
12260static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 PyObject *str1;
12264 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012265 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266 PyObject *result;
12267
Martin v. Löwis18e16552006-02-15 17:27:45 +000012268 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012270 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012271 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012273 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012274 return NULL;
12275 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012276 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012277 Py_DECREF(str1);
12278 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012279 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012280 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12281 result = NULL;
12282 else
12283 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284
12285 Py_DECREF(str1);
12286 Py_DECREF(str2);
12287 return result;
12288}
12289
Alexander Belopolsky40018472011-02-26 01:02:56 +000012290static PyObject *
12291unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012293 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 Py_ssize_t isize;
12295 Py_ssize_t osize, squote, dquote, i, o;
12296 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012297 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012301 return NULL;
12302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012303 isize = PyUnicode_GET_LENGTH(unicode);
12304 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 /* Compute length of output, quote characters, and
12307 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012308 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 max = 127;
12310 squote = dquote = 0;
12311 ikind = PyUnicode_KIND(unicode);
12312 for (i = 0; i < isize; i++) {
12313 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12314 switch (ch) {
12315 case '\'': squote++; osize++; break;
12316 case '"': dquote++; osize++; break;
12317 case '\\': case '\t': case '\r': case '\n':
12318 osize += 2; break;
12319 default:
12320 /* Fast-path ASCII */
12321 if (ch < ' ' || ch == 0x7f)
12322 osize += 4; /* \xHH */
12323 else if (ch < 0x7f)
12324 osize++;
12325 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12326 osize++;
12327 max = ch > max ? ch : max;
12328 }
12329 else if (ch < 0x100)
12330 osize += 4; /* \xHH */
12331 else if (ch < 0x10000)
12332 osize += 6; /* \uHHHH */
12333 else
12334 osize += 10; /* \uHHHHHHHH */
12335 }
12336 }
12337
12338 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012339 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012341 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 if (dquote)
12343 /* Both squote and dquote present. Use squote,
12344 and escape them */
12345 osize += squote;
12346 else
12347 quote = '"';
12348 }
Victor Stinner55c08782013-04-14 18:45:39 +020012349 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350
12351 repr = PyUnicode_New(osize, max);
12352 if (repr == NULL)
12353 return NULL;
12354 okind = PyUnicode_KIND(repr);
12355 odata = PyUnicode_DATA(repr);
12356
12357 PyUnicode_WRITE(okind, odata, 0, quote);
12358 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012359 if (unchanged) {
12360 _PyUnicode_FastCopyCharacters(repr, 1,
12361 unicode, 0,
12362 isize);
12363 }
12364 else {
12365 for (i = 0, o = 1; i < isize; i++) {
12366 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367
Victor Stinner55c08782013-04-14 18:45:39 +020012368 /* Escape quotes and backslashes */
12369 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012370 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012372 continue;
12373 }
12374
12375 /* Map special whitespace to '\t', \n', '\r' */
12376 if (ch == '\t') {
12377 PyUnicode_WRITE(okind, odata, o++, '\\');
12378 PyUnicode_WRITE(okind, odata, o++, 't');
12379 }
12380 else if (ch == '\n') {
12381 PyUnicode_WRITE(okind, odata, o++, '\\');
12382 PyUnicode_WRITE(okind, odata, o++, 'n');
12383 }
12384 else if (ch == '\r') {
12385 PyUnicode_WRITE(okind, odata, o++, '\\');
12386 PyUnicode_WRITE(okind, odata, o++, 'r');
12387 }
12388
12389 /* Map non-printable US ASCII to '\xhh' */
12390 else if (ch < ' ' || ch == 0x7F) {
12391 PyUnicode_WRITE(okind, odata, o++, '\\');
12392 PyUnicode_WRITE(okind, odata, o++, 'x');
12393 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12394 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12395 }
12396
12397 /* Copy ASCII characters as-is */
12398 else if (ch < 0x7F) {
12399 PyUnicode_WRITE(okind, odata, o++, ch);
12400 }
12401
12402 /* Non-ASCII characters */
12403 else {
12404 /* Map Unicode whitespace and control characters
12405 (categories Z* and C* except ASCII space)
12406 */
12407 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12408 PyUnicode_WRITE(okind, odata, o++, '\\');
12409 /* Map 8-bit characters to '\xhh' */
12410 if (ch <= 0xff) {
12411 PyUnicode_WRITE(okind, odata, o++, 'x');
12412 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12413 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12414 }
12415 /* Map 16-bit characters to '\uxxxx' */
12416 else if (ch <= 0xffff) {
12417 PyUnicode_WRITE(okind, odata, o++, 'u');
12418 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12419 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12420 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12421 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12422 }
12423 /* Map 21-bit characters to '\U00xxxxxx' */
12424 else {
12425 PyUnicode_WRITE(okind, odata, o++, 'U');
12426 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12427 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12428 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12429 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12430 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12431 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12432 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12433 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12434 }
12435 }
12436 /* Copy characters as-is */
12437 else {
12438 PyUnicode_WRITE(okind, odata, o++, ch);
12439 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012440 }
12441 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012444 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012445 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446}
12447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012448PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012449 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012450\n\
12451Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012452such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453arguments start and end are interpreted as in slice notation.\n\
12454\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012455Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012456
12457static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012460 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012461 Py_ssize_t start;
12462 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464
Jesus Ceaac451502011-04-20 17:09:23 +020012465 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12466 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012467 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012468
Christian Heimesea71a522013-06-29 21:17:34 +020012469 if (PyUnicode_READY(self) == -1) {
12470 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012472 }
12473 if (PyUnicode_READY(substring) == -1) {
12474 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012475 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477
Victor Stinner7931d9a2011-11-04 00:22:48 +010012478 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479
12480 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 if (result == -2)
12483 return NULL;
12484
Christian Heimes217cfd12007-12-02 14:31:20 +000012485 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486}
12487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012488PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012491Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492
12493static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012494unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012496 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012497 Py_ssize_t start;
12498 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012499 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012500
Jesus Ceaac451502011-04-20 17:09:23 +020012501 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12502 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504
Christian Heimesea71a522013-06-29 21:17:34 +020012505 if (PyUnicode_READY(self) == -1) {
12506 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012507 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012508 }
12509 if (PyUnicode_READY(substring) == -1) {
12510 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513
Victor Stinner7931d9a2011-11-04 00:22:48 +010012514 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515
12516 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012518 if (result == -2)
12519 return NULL;
12520
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521 if (result < 0) {
12522 PyErr_SetString(PyExc_ValueError, "substring not found");
12523 return NULL;
12524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012525
Christian Heimes217cfd12007-12-02 14:31:20 +000012526 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527}
12528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012529PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012530 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012532Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012533done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534
12535static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012536unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012538 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 Py_UCS4 fillchar = ' ';
12540
Victor Stinnere9a29352011-10-01 02:14:59 +020012541 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012543
Benjamin Petersonbac79492012-01-14 13:34:47 -050012544 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545 return NULL;
12546
Victor Stinnerc4b49542011-12-11 22:44:26 +010012547 if (PyUnicode_GET_LENGTH(self) >= width)
12548 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549
Victor Stinnerc4b49542011-12-11 22:44:26 +010012550 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551}
12552
Alexander Belopolsky40018472011-02-26 01:02:56 +000012553PyObject *
12554PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555{
12556 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012557
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558 s = PyUnicode_FromObject(s);
12559 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012560 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012561 if (sep != NULL) {
12562 sep = PyUnicode_FromObject(sep);
12563 if (sep == NULL) {
12564 Py_DECREF(s);
12565 return NULL;
12566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012567 }
12568
Victor Stinner9310abb2011-10-05 00:59:23 +020012569 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570
12571 Py_DECREF(s);
12572 Py_XDECREF(sep);
12573 return result;
12574}
12575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012576PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012577 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578\n\
12579Return a list of the words in S, using sep as the\n\
12580delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012581splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012582whitespace string is a separator and empty strings are\n\
12583removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584
12585static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012586unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012588 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012590 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012592 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12593 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594 return NULL;
12595
12596 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012597 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012599 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012601 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602}
12603
Thomas Wouters477c8d52006-05-27 19:21:47 +000012604PyObject *
12605PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12606{
12607 PyObject* str_obj;
12608 PyObject* sep_obj;
12609 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610 int kind1, kind2, kind;
12611 void *buf1 = NULL, *buf2 = NULL;
12612 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012613
12614 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012615 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012616 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012617 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012618 if (!sep_obj) {
12619 Py_DECREF(str_obj);
12620 return NULL;
12621 }
12622 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12623 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012624 Py_DECREF(str_obj);
12625 return NULL;
12626 }
12627
Victor Stinner14f8f022011-10-05 20:58:25 +020012628 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012630 kind = Py_MAX(kind1, kind2);
12631 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012633 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 if (!buf1)
12635 goto onError;
12636 buf2 = PyUnicode_DATA(sep_obj);
12637 if (kind2 != kind)
12638 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12639 if (!buf2)
12640 goto onError;
12641 len1 = PyUnicode_GET_LENGTH(str_obj);
12642 len2 = PyUnicode_GET_LENGTH(sep_obj);
12643
Benjamin Petersonead6b532011-12-20 17:23:42 -060012644 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012645 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012646 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12647 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12648 else
12649 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 break;
12651 case PyUnicode_2BYTE_KIND:
12652 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12653 break;
12654 case PyUnicode_4BYTE_KIND:
12655 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12656 break;
12657 default:
12658 assert(0);
12659 out = 0;
12660 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012661
12662 Py_DECREF(sep_obj);
12663 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 if (kind1 != kind)
12665 PyMem_Free(buf1);
12666 if (kind2 != kind)
12667 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012668
12669 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 onError:
12671 Py_DECREF(sep_obj);
12672 Py_DECREF(str_obj);
12673 if (kind1 != kind && buf1)
12674 PyMem_Free(buf1);
12675 if (kind2 != kind && buf2)
12676 PyMem_Free(buf2);
12677 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012678}
12679
12680
12681PyObject *
12682PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12683{
12684 PyObject* str_obj;
12685 PyObject* sep_obj;
12686 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 int kind1, kind2, kind;
12688 void *buf1 = NULL, *buf2 = NULL;
12689 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012690
12691 str_obj = PyUnicode_FromObject(str_in);
12692 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012693 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012694 sep_obj = PyUnicode_FromObject(sep_in);
12695 if (!sep_obj) {
12696 Py_DECREF(str_obj);
12697 return NULL;
12698 }
12699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 kind1 = PyUnicode_KIND(str_in);
12701 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012702 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 buf1 = PyUnicode_DATA(str_in);
12704 if (kind1 != kind)
12705 buf1 = _PyUnicode_AsKind(str_in, kind);
12706 if (!buf1)
12707 goto onError;
12708 buf2 = PyUnicode_DATA(sep_obj);
12709 if (kind2 != kind)
12710 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12711 if (!buf2)
12712 goto onError;
12713 len1 = PyUnicode_GET_LENGTH(str_obj);
12714 len2 = PyUnicode_GET_LENGTH(sep_obj);
12715
Benjamin Petersonead6b532011-12-20 17:23:42 -060012716 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012718 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12719 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12720 else
12721 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 break;
12723 case PyUnicode_2BYTE_KIND:
12724 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12725 break;
12726 case PyUnicode_4BYTE_KIND:
12727 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12728 break;
12729 default:
12730 assert(0);
12731 out = 0;
12732 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012733
12734 Py_DECREF(sep_obj);
12735 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 if (kind1 != kind)
12737 PyMem_Free(buf1);
12738 if (kind2 != kind)
12739 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012740
12741 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 onError:
12743 Py_DECREF(sep_obj);
12744 Py_DECREF(str_obj);
12745 if (kind1 != kind && buf1)
12746 PyMem_Free(buf1);
12747 if (kind2 != kind && buf2)
12748 PyMem_Free(buf2);
12749 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012750}
12751
12752PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012754\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012755Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012756the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012757found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012758
12759static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012760unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012761{
Victor Stinner9310abb2011-10-05 00:59:23 +020012762 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012763}
12764
12765PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012766 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012767\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012768Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012769the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012770separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012771
12772static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012773unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012774{
Victor Stinner9310abb2011-10-05 00:59:23 +020012775 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012776}
12777
Alexander Belopolsky40018472011-02-26 01:02:56 +000012778PyObject *
12779PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012780{
12781 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012782
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012783 s = PyUnicode_FromObject(s);
12784 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012785 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012786 if (sep != NULL) {
12787 sep = PyUnicode_FromObject(sep);
12788 if (sep == NULL) {
12789 Py_DECREF(s);
12790 return NULL;
12791 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012792 }
12793
Victor Stinner9310abb2011-10-05 00:59:23 +020012794 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012795
12796 Py_DECREF(s);
12797 Py_XDECREF(sep);
12798 return result;
12799}
12800
12801PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012802 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012803\n\
12804Return a list of the words in S, using sep as the\n\
12805delimiter string, starting at the end of the string and\n\
12806working to the front. If maxsplit is given, at most maxsplit\n\
12807splits are done. If sep is not specified, any whitespace string\n\
12808is a separator.");
12809
12810static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012811unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012812{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012813 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012814 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012815 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012816
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012817 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12818 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012819 return NULL;
12820
12821 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012823 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012824 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012825 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012826 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012827}
12828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012829PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012830 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831\n\
12832Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012833Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012834is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012835
12836static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012837unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012839 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012840 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012842 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12843 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844 return NULL;
12845
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012846 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847}
12848
12849static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012850PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012852 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853}
12854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012855PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012856 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012857\n\
12858Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012859and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860
12861static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012862unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012864 if (PyUnicode_READY(self) == -1)
12865 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012866 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867}
12868
Larry Hastings61272b72014-01-07 12:41:53 -080012869/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012870
Larry Hastings31826802013-10-19 00:09:25 -070012871@staticmethod
12872str.maketrans as unicode_maketrans
12873
12874 x: object
12875
12876 y: unicode=NULL
12877
12878 z: unicode=NULL
12879
12880 /
12881
12882Return a translation table usable for str.translate().
12883
12884If there is only one argument, it must be a dictionary mapping Unicode
12885ordinals (integers) or characters to Unicode ordinals, strings or None.
12886Character keys will be then converted to ordinals.
12887If there are two arguments, they must be strings of equal length, and
12888in the resulting dictionary, each character in x will be mapped to the
12889character at the same position in y. If there is a third argument, it
12890must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012891[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012892
12893PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012894"maketrans(x, y=None, z=None, /)\n"
12895"--\n"
12896"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012897"Return a translation table usable for str.translate().\n"
12898"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012899"If there is only one argument, it must be a dictionary mapping Unicode\n"
12900"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12901"Character keys will be then converted to ordinals.\n"
12902"If there are two arguments, they must be strings of equal length, and\n"
12903"in the resulting dictionary, each character in x will be mapped to the\n"
12904"character at the same position in y. If there is a third argument, it\n"
12905"must be a string, whose characters will be mapped to None in the result.");
12906
12907#define UNICODE_MAKETRANS_METHODDEF \
12908 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12909
12910static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012911unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012912
12913static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012914unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012915{
Larry Hastings31826802013-10-19 00:09:25 -070012916 PyObject *return_value = NULL;
12917 PyObject *x;
12918 PyObject *y = NULL;
12919 PyObject *z = NULL;
12920
12921 if (!PyArg_ParseTuple(args,
12922 "O|UU:maketrans",
12923 &x, &y, &z))
12924 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012925 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012926
12927exit:
12928 return return_value;
12929}
12930
12931static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012932unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012933/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012934{
Georg Brandlceee0772007-11-27 23:48:05 +000012935 PyObject *new = NULL, *key, *value;
12936 Py_ssize_t i = 0;
12937 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012938
Georg Brandlceee0772007-11-27 23:48:05 +000012939 new = PyDict_New();
12940 if (!new)
12941 return NULL;
12942 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012943 int x_kind, y_kind, z_kind;
12944 void *x_data, *y_data, *z_data;
12945
Georg Brandlceee0772007-11-27 23:48:05 +000012946 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012947 if (!PyUnicode_Check(x)) {
12948 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12949 "be a string if there is a second argument");
12950 goto err;
12951 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012952 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012953 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12954 "arguments must have equal length");
12955 goto err;
12956 }
12957 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012958 x_kind = PyUnicode_KIND(x);
12959 y_kind = PyUnicode_KIND(y);
12960 x_data = PyUnicode_DATA(x);
12961 y_data = PyUnicode_DATA(y);
12962 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12963 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012964 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012965 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012966 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012967 if (!value) {
12968 Py_DECREF(key);
12969 goto err;
12970 }
Georg Brandlceee0772007-11-27 23:48:05 +000012971 res = PyDict_SetItem(new, key, value);
12972 Py_DECREF(key);
12973 Py_DECREF(value);
12974 if (res < 0)
12975 goto err;
12976 }
12977 /* create entries for deleting chars in z */
12978 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012979 z_kind = PyUnicode_KIND(z);
12980 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012981 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012983 if (!key)
12984 goto err;
12985 res = PyDict_SetItem(new, key, Py_None);
12986 Py_DECREF(key);
12987 if (res < 0)
12988 goto err;
12989 }
12990 }
12991 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992 int kind;
12993 void *data;
12994
Georg Brandlceee0772007-11-27 23:48:05 +000012995 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012996 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012997 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12998 "to maketrans it must be a dict");
12999 goto err;
13000 }
13001 /* copy entries into the new dict, converting string keys to int keys */
13002 while (PyDict_Next(x, &i, &key, &value)) {
13003 if (PyUnicode_Check(key)) {
13004 /* convert string keys to integer keys */
13005 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013006 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013007 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13008 "table must be of length 1");
13009 goto err;
13010 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 kind = PyUnicode_KIND(key);
13012 data = PyUnicode_DATA(key);
13013 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013014 if (!newkey)
13015 goto err;
13016 res = PyDict_SetItem(new, newkey, value);
13017 Py_DECREF(newkey);
13018 if (res < 0)
13019 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013020 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013021 /* just keep integer keys */
13022 if (PyDict_SetItem(new, key, value) < 0)
13023 goto err;
13024 } else {
13025 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13026 "be strings or integers");
13027 goto err;
13028 }
13029 }
13030 }
13031 return new;
13032 err:
13033 Py_DECREF(new);
13034 return NULL;
13035}
13036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013037PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013038 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013039\n\
13040Return a copy of the string S, where all characters have been mapped\n\
13041through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013042Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013043Unmapped characters are left untouched. Characters mapped to None\n\
13044are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013045
13046static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013047unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013048{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013049 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050}
13051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013052PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013053 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013055Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056
13057static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013058unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013060 if (PyUnicode_READY(self) == -1)
13061 return NULL;
13062 if (PyUnicode_IS_ASCII(self))
13063 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013064 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065}
13066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013067PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013068 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013070Pad a numeric string S with zeros on the left, to fill a field\n\
13071of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013072
13073static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013074unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013076 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013077 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013078 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013079 int kind;
13080 void *data;
13081 Py_UCS4 chr;
13082
Martin v. Löwis18e16552006-02-15 17:27:45 +000013083 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084 return NULL;
13085
Benjamin Petersonbac79492012-01-14 13:34:47 -050013086 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013087 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088
Victor Stinnerc4b49542011-12-11 22:44:26 +010013089 if (PyUnicode_GET_LENGTH(self) >= width)
13090 return unicode_result_unchanged(self);
13091
13092 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093
13094 u = pad(self, fill, 0, '0');
13095
Walter Dörwald068325e2002-04-15 13:36:47 +000013096 if (u == NULL)
13097 return NULL;
13098
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013099 kind = PyUnicode_KIND(u);
13100 data = PyUnicode_DATA(u);
13101 chr = PyUnicode_READ(kind, data, fill);
13102
13103 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013105 PyUnicode_WRITE(kind, data, 0, chr);
13106 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107 }
13108
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013109 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013110 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112
13113#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013114static PyObject *
13115unicode__decimal2ascii(PyObject *self)
13116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013117 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013118}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119#endif
13120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013121PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013122 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013124Return True if S starts with the specified prefix, False otherwise.\n\
13125With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013126With optional end, stop comparing S at that position.\n\
13127prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128
13129static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013130unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013131 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013133 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013134 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013135 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013136 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013137 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138
Jesus Ceaac451502011-04-20 17:09:23 +020013139 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013140 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013141 if (PyTuple_Check(subobj)) {
13142 Py_ssize_t i;
13143 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013144 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013145 if (substring == NULL)
13146 return NULL;
13147 result = tailmatch(self, substring, start, end, -1);
13148 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013149 if (result == -1)
13150 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013151 if (result) {
13152 Py_RETURN_TRUE;
13153 }
13154 }
13155 /* nothing matched */
13156 Py_RETURN_FALSE;
13157 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013158 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013159 if (substring == NULL) {
13160 if (PyErr_ExceptionMatches(PyExc_TypeError))
13161 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13162 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013164 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013165 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013167 if (result == -1)
13168 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013169 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170}
13171
13172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013173PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013176Return True if S ends with the specified suffix, False otherwise.\n\
13177With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013178With optional end, stop comparing S at that position.\n\
13179suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013180
13181static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013182unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013183 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013185 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013186 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013187 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013188 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013189 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190
Jesus Ceaac451502011-04-20 17:09:23 +020013191 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013192 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013193 if (PyTuple_Check(subobj)) {
13194 Py_ssize_t i;
13195 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013196 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013197 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013198 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013200 result = tailmatch(self, substring, start, end, +1);
13201 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013202 if (result == -1)
13203 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013204 if (result) {
13205 Py_RETURN_TRUE;
13206 }
13207 }
13208 Py_RETURN_FALSE;
13209 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013210 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013211 if (substring == NULL) {
13212 if (PyErr_ExceptionMatches(PyExc_TypeError))
13213 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13214 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013215 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013216 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013217 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013218 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013219 if (result == -1)
13220 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013221 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013222}
13223
Victor Stinner202fdca2012-05-07 12:47:02 +020013224Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013225_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013226{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013227 if (!writer->readonly)
13228 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13229 else {
13230 /* Copy-on-write mode: set buffer size to 0 so
13231 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13232 * next write. */
13233 writer->size = 0;
13234 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013235 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13236 writer->data = PyUnicode_DATA(writer->buffer);
13237 writer->kind = PyUnicode_KIND(writer->buffer);
13238}
13239
Victor Stinnerd3f08822012-05-29 12:57:52 +020013240void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013241_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013242{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013243 memset(writer, 0, sizeof(*writer));
13244#ifdef Py_DEBUG
13245 writer->kind = 5; /* invalid kind */
13246#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013247 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013248}
13249
Victor Stinnerd3f08822012-05-29 12:57:52 +020013250int
13251_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13252 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013253{
Victor Stinner6989ba02013-11-18 21:08:39 +010013254#ifdef MS_WINDOWS
13255 /* On Windows, overallocate by 50% is the best factor */
13256# define OVERALLOCATE_FACTOR 2
13257#else
13258 /* On Linux, overallocate by 25% is the best factor */
13259# define OVERALLOCATE_FACTOR 4
13260#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013261 Py_ssize_t newlen;
13262 PyObject *newbuffer;
13263
Victor Stinnerd3f08822012-05-29 12:57:52 +020013264 assert(length > 0);
13265
Victor Stinner202fdca2012-05-07 12:47:02 +020013266 if (length > PY_SSIZE_T_MAX - writer->pos) {
13267 PyErr_NoMemory();
13268 return -1;
13269 }
13270 newlen = writer->pos + length;
13271
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013272 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013273
Victor Stinnerd3f08822012-05-29 12:57:52 +020013274 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013275 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013276 if (writer->overallocate
13277 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13278 /* overallocate to limit the number of realloc() */
13279 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013280 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013281 if (newlen < writer->min_length)
13282 newlen = writer->min_length;
13283
Victor Stinnerd3f08822012-05-29 12:57:52 +020013284 writer->buffer = PyUnicode_New(newlen, maxchar);
13285 if (writer->buffer == NULL)
13286 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013287 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013288 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013289 if (writer->overallocate
13290 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13291 /* overallocate to limit the number of realloc() */
13292 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013293 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013294 if (newlen < writer->min_length)
13295 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013296
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013297 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013298 /* resize + widen */
13299 newbuffer = PyUnicode_New(newlen, maxchar);
13300 if (newbuffer == NULL)
13301 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013302 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13303 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013304 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013305 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013306 }
13307 else {
13308 newbuffer = resize_compact(writer->buffer, newlen);
13309 if (newbuffer == NULL)
13310 return -1;
13311 }
13312 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013313 }
13314 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013315 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013316 newbuffer = PyUnicode_New(writer->size, maxchar);
13317 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013318 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013319 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13320 writer->buffer, 0, writer->pos);
13321 Py_DECREF(writer->buffer);
13322 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013323 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013324 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013325 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013326
13327#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013328}
13329
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013330Py_LOCAL_INLINE(int)
13331_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013332{
13333 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13334 return -1;
13335 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13336 writer->pos++;
13337 return 0;
13338}
13339
13340int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013341_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13342{
13343 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13344}
13345
13346int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013347_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13348{
13349 Py_UCS4 maxchar;
13350 Py_ssize_t len;
13351
13352 if (PyUnicode_READY(str) == -1)
13353 return -1;
13354 len = PyUnicode_GET_LENGTH(str);
13355 if (len == 0)
13356 return 0;
13357 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13358 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013359 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013360 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013361 Py_INCREF(str);
13362 writer->buffer = str;
13363 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013364 writer->pos += len;
13365 return 0;
13366 }
13367 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13368 return -1;
13369 }
13370 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13371 str, 0, len);
13372 writer->pos += len;
13373 return 0;
13374}
13375
Victor Stinnere215d962012-10-06 23:03:36 +020013376int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013377_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13378 Py_ssize_t start, Py_ssize_t end)
13379{
13380 Py_UCS4 maxchar;
13381 Py_ssize_t len;
13382
13383 if (PyUnicode_READY(str) == -1)
13384 return -1;
13385
13386 assert(0 <= start);
13387 assert(end <= PyUnicode_GET_LENGTH(str));
13388 assert(start <= end);
13389
13390 if (end == 0)
13391 return 0;
13392
13393 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13394 return _PyUnicodeWriter_WriteStr(writer, str);
13395
13396 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13397 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13398 else
13399 maxchar = writer->maxchar;
13400 len = end - start;
13401
13402 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13403 return -1;
13404
13405 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13406 str, start, len);
13407 writer->pos += len;
13408 return 0;
13409}
13410
13411int
Victor Stinner4a587072013-11-19 12:54:53 +010013412_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13413 const char *ascii, Py_ssize_t len)
13414{
13415 if (len == -1)
13416 len = strlen(ascii);
13417
13418 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13419
13420 if (writer->buffer == NULL && !writer->overallocate) {
13421 PyObject *str;
13422
13423 str = _PyUnicode_FromASCII(ascii, len);
13424 if (str == NULL)
13425 return -1;
13426
13427 writer->readonly = 1;
13428 writer->buffer = str;
13429 _PyUnicodeWriter_Update(writer);
13430 writer->pos += len;
13431 return 0;
13432 }
13433
13434 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13435 return -1;
13436
13437 switch (writer->kind)
13438 {
13439 case PyUnicode_1BYTE_KIND:
13440 {
13441 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13442 Py_UCS1 *data = writer->data;
13443
13444 Py_MEMCPY(data + writer->pos, str, len);
13445 break;
13446 }
13447 case PyUnicode_2BYTE_KIND:
13448 {
13449 _PyUnicode_CONVERT_BYTES(
13450 Py_UCS1, Py_UCS2,
13451 ascii, ascii + len,
13452 (Py_UCS2 *)writer->data + writer->pos);
13453 break;
13454 }
13455 case PyUnicode_4BYTE_KIND:
13456 {
13457 _PyUnicode_CONVERT_BYTES(
13458 Py_UCS1, Py_UCS4,
13459 ascii, ascii + len,
13460 (Py_UCS4 *)writer->data + writer->pos);
13461 break;
13462 }
13463 default:
13464 assert(0);
13465 }
13466
13467 writer->pos += len;
13468 return 0;
13469}
13470
13471int
13472_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13473 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013474{
13475 Py_UCS4 maxchar;
13476
13477 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13478 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13479 return -1;
13480 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13481 writer->pos += len;
13482 return 0;
13483}
13484
Victor Stinnerd3f08822012-05-29 12:57:52 +020013485PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013486_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013487{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013488 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013489 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013490 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013491 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013492 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013493 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013494 str = writer->buffer;
13495 writer->buffer = NULL;
13496 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13497 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013498 }
13499 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13500 PyObject *newbuffer;
13501 newbuffer = resize_compact(writer->buffer, writer->pos);
13502 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013503 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013504 return NULL;
13505 }
13506 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013507 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013508 str = writer->buffer;
13509 writer->buffer = NULL;
13510 assert(_PyUnicode_CheckConsistency(str, 1));
13511 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013512}
13513
Victor Stinnerd3f08822012-05-29 12:57:52 +020013514void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013515_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013516{
13517 Py_CLEAR(writer->buffer);
13518}
13519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013520#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013521
13522PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013524\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013525Return a formatted version of S, using substitutions from args and kwargs.\n\
13526The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013527
Eric Smith27bbca62010-11-04 17:06:58 +000013528PyDoc_STRVAR(format_map__doc__,
13529 "S.format_map(mapping) -> str\n\
13530\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013531Return a formatted version of S, using substitutions from mapping.\n\
13532The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013533
Eric Smith4a7d76d2008-05-30 18:10:19 +000013534static PyObject *
13535unicode__format__(PyObject* self, PyObject* args)
13536{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013537 PyObject *format_spec;
13538 _PyUnicodeWriter writer;
13539 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013540
13541 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13542 return NULL;
13543
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 if (PyUnicode_READY(self) == -1)
13545 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013546 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13548 self, format_spec, 0,
13549 PyUnicode_GET_LENGTH(format_spec));
13550 if (ret == -1) {
13551 _PyUnicodeWriter_Dealloc(&writer);
13552 return NULL;
13553 }
13554 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013555}
13556
Eric Smith8c663262007-08-25 02:26:07 +000013557PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013559\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013560Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013561
13562static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013563unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013564{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013565 Py_ssize_t size;
13566
13567 /* If it's a compact object, account for base structure +
13568 character data. */
13569 if (PyUnicode_IS_COMPACT_ASCII(v))
13570 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13571 else if (PyUnicode_IS_COMPACT(v))
13572 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013573 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013574 else {
13575 /* If it is a two-block object, account for base object, and
13576 for character block if present. */
13577 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013578 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013579 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013580 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013581 }
13582 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013583 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013584 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013585 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013586 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013587 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588
13589 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013590}
13591
13592PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013594
13595static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013596unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013597{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013598 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013599 if (!copy)
13600 return NULL;
13601 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013602}
13603
Guido van Rossumd57fd912000-03-10 22:53:23 +000013604static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013605 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013606 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013607 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13608 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013609 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13610 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013611 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013612 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13613 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13614 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013615 {"expandtabs", (PyCFunction) unicode_expandtabs,
13616 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013617 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013618 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013619 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13620 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13621 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013622 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013623 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13624 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13625 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013626 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013627 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013628 {"splitlines", (PyCFunction) unicode_splitlines,
13629 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013630 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013631 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13632 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13633 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13634 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13635 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13636 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13637 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13638 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13639 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13640 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13641 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13642 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13643 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13644 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013645 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013646 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013647 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013648 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013649 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013650 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013651 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013652 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013653#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013654 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013655 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013656#endif
13657
Benjamin Peterson14339b62009-01-31 16:36:08 +000013658 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013659 {NULL, NULL}
13660};
13661
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013662static PyObject *
13663unicode_mod(PyObject *v, PyObject *w)
13664{
Brian Curtindfc80e32011-08-10 20:28:54 -050013665 if (!PyUnicode_Check(v))
13666 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013667 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013668}
13669
13670static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013671 0, /*nb_add*/
13672 0, /*nb_subtract*/
13673 0, /*nb_multiply*/
13674 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013675};
13676
Guido van Rossumd57fd912000-03-10 22:53:23 +000013677static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013678 (lenfunc) unicode_length, /* sq_length */
13679 PyUnicode_Concat, /* sq_concat */
13680 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13681 (ssizeargfunc) unicode_getitem, /* sq_item */
13682 0, /* sq_slice */
13683 0, /* sq_ass_item */
13684 0, /* sq_ass_slice */
13685 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013686};
13687
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013688static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013689unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013690{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013691 if (PyUnicode_READY(self) == -1)
13692 return NULL;
13693
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013694 if (PyIndex_Check(item)) {
13695 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013696 if (i == -1 && PyErr_Occurred())
13697 return NULL;
13698 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013699 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013700 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013701 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013702 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013703 PyObject *result;
13704 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013705 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013706 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013707
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013708 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013709 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013710 return NULL;
13711 }
13712
13713 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013714 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013715 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013716 slicelength == PyUnicode_GET_LENGTH(self)) {
13717 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013718 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013719 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013720 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013721 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013722 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013723 src_kind = PyUnicode_KIND(self);
13724 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013725 if (!PyUnicode_IS_ASCII(self)) {
13726 kind_limit = kind_maxchar_limit(src_kind);
13727 max_char = 0;
13728 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13729 ch = PyUnicode_READ(src_kind, src_data, cur);
13730 if (ch > max_char) {
13731 max_char = ch;
13732 if (max_char >= kind_limit)
13733 break;
13734 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013735 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013736 }
Victor Stinner55c99112011-10-13 01:17:06 +020013737 else
13738 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013739 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013740 if (result == NULL)
13741 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013742 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013743 dest_data = PyUnicode_DATA(result);
13744
13745 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013746 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13747 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013748 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013749 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013750 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013751 } else {
13752 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13753 return NULL;
13754 }
13755}
13756
13757static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013758 (lenfunc)unicode_length, /* mp_length */
13759 (binaryfunc)unicode_subscript, /* mp_subscript */
13760 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013761};
13762
Guido van Rossumd57fd912000-03-10 22:53:23 +000013763
Guido van Rossumd57fd912000-03-10 22:53:23 +000013764/* Helpers for PyUnicode_Format() */
13765
Victor Stinnera47082312012-10-04 02:19:54 +020013766struct unicode_formatter_t {
13767 PyObject *args;
13768 int args_owned;
13769 Py_ssize_t arglen, argidx;
13770 PyObject *dict;
13771
13772 enum PyUnicode_Kind fmtkind;
13773 Py_ssize_t fmtcnt, fmtpos;
13774 void *fmtdata;
13775 PyObject *fmtstr;
13776
13777 _PyUnicodeWriter writer;
13778};
13779
13780struct unicode_format_arg_t {
13781 Py_UCS4 ch;
13782 int flags;
13783 Py_ssize_t width;
13784 int prec;
13785 int sign;
13786};
13787
Guido van Rossumd57fd912000-03-10 22:53:23 +000013788static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013789unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013790{
Victor Stinnera47082312012-10-04 02:19:54 +020013791 Py_ssize_t argidx = ctx->argidx;
13792
13793 if (argidx < ctx->arglen) {
13794 ctx->argidx++;
13795 if (ctx->arglen < 0)
13796 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013797 else
Victor Stinnera47082312012-10-04 02:19:54 +020013798 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013799 }
13800 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013801 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013802 return NULL;
13803}
13804
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013805/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013806
Victor Stinnera47082312012-10-04 02:19:54 +020013807/* Format a float into the writer if the writer is not NULL, or into *p_output
13808 otherwise.
13809
13810 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013811static int
Victor Stinnera47082312012-10-04 02:19:54 +020013812formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13813 PyObject **p_output,
13814 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013815{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013816 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013817 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013818 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013819 int prec;
13820 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013821
Guido van Rossumd57fd912000-03-10 22:53:23 +000013822 x = PyFloat_AsDouble(v);
13823 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013824 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013825
Victor Stinnera47082312012-10-04 02:19:54 +020013826 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013829
Victor Stinnera47082312012-10-04 02:19:54 +020013830 if (arg->flags & F_ALT)
13831 dtoa_flags = Py_DTSF_ALT;
13832 else
13833 dtoa_flags = 0;
13834 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013835 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013836 return -1;
13837 len = strlen(p);
13838 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013839 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013840 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013841 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013842 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013843 }
13844 else
13845 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013846 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013847 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013848}
13849
Victor Stinnerd0880d52012-04-27 23:40:13 +020013850/* formatlong() emulates the format codes d, u, o, x and X, and
13851 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13852 * Python's regular ints.
13853 * Return value: a new PyUnicodeObject*, or NULL if error.
13854 * The output string is of the form
13855 * "-"? ("0x" | "0X")? digit+
13856 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13857 * set in flags. The case of hex digits will be correct,
13858 * There will be at least prec digits, zero-filled on the left if
13859 * necessary to get that many.
13860 * val object to be converted
13861 * flags bitmask of format flags; only F_ALT is looked at
13862 * prec minimum number of digits; 0-fill on left if needed
13863 * type a character in [duoxX]; u acts the same as d
13864 *
13865 * CAUTION: o, x and X conversions on regular ints can never
13866 * produce a '-' sign, but can for Python's unbounded ints.
13867 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013868static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013869formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013870{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013871 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013872 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013873 Py_ssize_t i;
13874 int sign; /* 1 if '-', else 0 */
13875 int len; /* number of characters */
13876 Py_ssize_t llen;
13877 int numdigits; /* len == numnondigits + numdigits */
13878 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013879 int prec = arg->prec;
13880 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013881
Victor Stinnerd0880d52012-04-27 23:40:13 +020013882 /* Avoid exceeding SSIZE_T_MAX */
13883 if (prec > INT_MAX-3) {
13884 PyErr_SetString(PyExc_OverflowError,
13885 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013886 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013887 }
13888
13889 assert(PyLong_Check(val));
13890
13891 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013892 default:
13893 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013894 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013895 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013896 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013897 /* int and int subclasses should print numerically when a numeric */
13898 /* format code is used (see issue18780) */
13899 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013900 break;
13901 case 'o':
13902 numnondigits = 2;
13903 result = PyNumber_ToBase(val, 8);
13904 break;
13905 case 'x':
13906 case 'X':
13907 numnondigits = 2;
13908 result = PyNumber_ToBase(val, 16);
13909 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013910 }
13911 if (!result)
13912 return NULL;
13913
13914 assert(unicode_modifiable(result));
13915 assert(PyUnicode_IS_READY(result));
13916 assert(PyUnicode_IS_ASCII(result));
13917
13918 /* To modify the string in-place, there can only be one reference. */
13919 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013920 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013921 PyErr_BadInternalCall();
13922 return NULL;
13923 }
13924 buf = PyUnicode_DATA(result);
13925 llen = PyUnicode_GET_LENGTH(result);
13926 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013927 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013928 PyErr_SetString(PyExc_ValueError,
13929 "string too large in _PyBytes_FormatLong");
13930 return NULL;
13931 }
13932 len = (int)llen;
13933 sign = buf[0] == '-';
13934 numnondigits += sign;
13935 numdigits = len - numnondigits;
13936 assert(numdigits > 0);
13937
13938 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013939 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013940 (type == 'o' || type == 'x' || type == 'X'))) {
13941 assert(buf[sign] == '0');
13942 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13943 buf[sign+1] == 'o');
13944 numnondigits -= 2;
13945 buf += 2;
13946 len -= 2;
13947 if (sign)
13948 buf[0] = '-';
13949 assert(len == numnondigits + numdigits);
13950 assert(numdigits > 0);
13951 }
13952
13953 /* Fill with leading zeroes to meet minimum width. */
13954 if (prec > numdigits) {
13955 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13956 numnondigits + prec);
13957 char *b1;
13958 if (!r1) {
13959 Py_DECREF(result);
13960 return NULL;
13961 }
13962 b1 = PyBytes_AS_STRING(r1);
13963 for (i = 0; i < numnondigits; ++i)
13964 *b1++ = *buf++;
13965 for (i = 0; i < prec - numdigits; i++)
13966 *b1++ = '0';
13967 for (i = 0; i < numdigits; i++)
13968 *b1++ = *buf++;
13969 *b1 = '\0';
13970 Py_DECREF(result);
13971 result = r1;
13972 buf = PyBytes_AS_STRING(result);
13973 len = numnondigits + prec;
13974 }
13975
13976 /* Fix up case for hex conversions. */
13977 if (type == 'X') {
13978 /* Need to convert all lower case letters to upper case.
13979 and need to convert 0x to 0X (and -0x to -0X). */
13980 for (i = 0; i < len; i++)
13981 if (buf[i] >= 'a' && buf[i] <= 'x')
13982 buf[i] -= 'a'-'A';
13983 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013984 if (!PyUnicode_Check(result)
13985 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013986 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013987 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013988 Py_DECREF(result);
13989 result = unicode;
13990 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013991 else if (len != PyUnicode_GET_LENGTH(result)) {
13992 if (PyUnicode_Resize(&result, len) < 0)
13993 Py_CLEAR(result);
13994 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013995 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013996}
13997
Ethan Furmandf3ed242014-01-05 06:50:30 -080013998/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020013999 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014000 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014001 * -1 and raise an exception on error */
14002static int
Victor Stinnera47082312012-10-04 02:19:54 +020014003mainformatlong(PyObject *v,
14004 struct unicode_format_arg_t *arg,
14005 PyObject **p_output,
14006 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014007{
14008 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014009 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014010
14011 if (!PyNumber_Check(v))
14012 goto wrongtype;
14013
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014014 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014015 /* if not, issue deprecation warning for now */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014016 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014017 if (type == 'o' || type == 'x' || type == 'X') {
14018 iobj = PyNumber_Index(v);
14019 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014020 PyErr_Clear();
14021 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14022 "automatic int conversions have been deprecated",
14023 1)) {
14024 return -1;
14025 }
14026 iobj = PyNumber_Long(v);
14027 if (iobj == NULL ) {
14028 if (PyErr_ExceptionMatches(PyExc_TypeError))
14029 goto wrongtype;
14030 return -1;
14031 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014032 }
14033 }
14034 else {
14035 iobj = PyNumber_Long(v);
14036 if (iobj == NULL ) {
14037 if (PyErr_ExceptionMatches(PyExc_TypeError))
14038 goto wrongtype;
14039 return -1;
14040 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014041 }
14042 assert(PyLong_Check(iobj));
14043 }
14044 else {
14045 iobj = v;
14046 Py_INCREF(iobj);
14047 }
14048
14049 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014050 && arg->width == -1 && arg->prec == -1
14051 && !(arg->flags & (F_SIGN | F_BLANK))
14052 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014053 {
14054 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014055 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014056 int base;
14057
Victor Stinnera47082312012-10-04 02:19:54 +020014058 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014059 {
14060 default:
14061 assert(0 && "'type' not in [diuoxX]");
14062 case 'd':
14063 case 'i':
14064 case 'u':
14065 base = 10;
14066 break;
14067 case 'o':
14068 base = 8;
14069 break;
14070 case 'x':
14071 case 'X':
14072 base = 16;
14073 break;
14074 }
14075
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014076 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14077 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014078 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014079 }
14080 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014081 return 1;
14082 }
14083
Victor Stinnera47082312012-10-04 02:19:54 +020014084 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014085 Py_DECREF(iobj);
14086 if (res == NULL)
14087 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014088 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014089 return 0;
14090
14091wrongtype:
14092 PyErr_Format(PyExc_TypeError,
14093 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014094 "not %.200s",
14095 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014096 return -1;
14097}
14098
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014099static Py_UCS4
14100formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014101{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014102 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014103 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014104 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014105 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014106 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014107 goto onError;
14108 }
14109 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014110 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014111 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014112 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014113 /* if not, issue deprecation warning for now */
Ethan Furmandf3ed242014-01-05 06:50:30 -080014114 if (!PyLong_Check(v)) {
14115 iobj = PyNumber_Index(v);
14116 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014117 PyErr_Clear();
14118 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14119 "automatic int conversions have been deprecated",
14120 1)) {
14121 return -1;
14122 }
14123 iobj = PyNumber_Long(v);
14124 if (iobj == NULL ) {
14125 if (PyErr_ExceptionMatches(PyExc_TypeError))
14126 goto onError;
14127 return -1;
14128 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014129 }
14130 v = iobj;
14131 Py_DECREF(iobj);
14132 }
14133 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 x = PyLong_AsLong(v);
14135 if (x == -1 && PyErr_Occurred())
14136 goto onError;
14137
Victor Stinner8faf8212011-12-08 22:14:11 +010014138 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014139 PyErr_SetString(PyExc_OverflowError,
14140 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014141 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014142 }
14143
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014144 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014145 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014146
Benjamin Peterson29060642009-01-31 22:14:21 +000014147 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014148 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014149 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014150 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014151}
14152
Victor Stinnera47082312012-10-04 02:19:54 +020014153/* Parse options of an argument: flags, width, precision.
14154 Handle also "%(name)" syntax.
14155
14156 Return 0 if the argument has been formatted into arg->str.
14157 Return 1 if the argument has been written into ctx->writer,
14158 Raise an exception and return -1 on error. */
14159static int
14160unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14161 struct unicode_format_arg_t *arg)
14162{
14163#define FORMAT_READ(ctx) \
14164 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14165
14166 PyObject *v;
14167
Victor Stinnera47082312012-10-04 02:19:54 +020014168 if (arg->ch == '(') {
14169 /* Get argument value from a dictionary. Example: "%(name)s". */
14170 Py_ssize_t keystart;
14171 Py_ssize_t keylen;
14172 PyObject *key;
14173 int pcount = 1;
14174
14175 if (ctx->dict == NULL) {
14176 PyErr_SetString(PyExc_TypeError,
14177 "format requires a mapping");
14178 return -1;
14179 }
14180 ++ctx->fmtpos;
14181 --ctx->fmtcnt;
14182 keystart = ctx->fmtpos;
14183 /* Skip over balanced parentheses */
14184 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14185 arg->ch = FORMAT_READ(ctx);
14186 if (arg->ch == ')')
14187 --pcount;
14188 else if (arg->ch == '(')
14189 ++pcount;
14190 ctx->fmtpos++;
14191 }
14192 keylen = ctx->fmtpos - keystart - 1;
14193 if (ctx->fmtcnt < 0 || pcount > 0) {
14194 PyErr_SetString(PyExc_ValueError,
14195 "incomplete format key");
14196 return -1;
14197 }
14198 key = PyUnicode_Substring(ctx->fmtstr,
14199 keystart, keystart + keylen);
14200 if (key == NULL)
14201 return -1;
14202 if (ctx->args_owned) {
14203 Py_DECREF(ctx->args);
14204 ctx->args_owned = 0;
14205 }
14206 ctx->args = PyObject_GetItem(ctx->dict, key);
14207 Py_DECREF(key);
14208 if (ctx->args == NULL)
14209 return -1;
14210 ctx->args_owned = 1;
14211 ctx->arglen = -1;
14212 ctx->argidx = -2;
14213 }
14214
14215 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014216 while (--ctx->fmtcnt >= 0) {
14217 arg->ch = FORMAT_READ(ctx);
14218 ctx->fmtpos++;
14219 switch (arg->ch) {
14220 case '-': arg->flags |= F_LJUST; continue;
14221 case '+': arg->flags |= F_SIGN; continue;
14222 case ' ': arg->flags |= F_BLANK; continue;
14223 case '#': arg->flags |= F_ALT; continue;
14224 case '0': arg->flags |= F_ZERO; continue;
14225 }
14226 break;
14227 }
14228
14229 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014230 if (arg->ch == '*') {
14231 v = unicode_format_getnextarg(ctx);
14232 if (v == NULL)
14233 return -1;
14234 if (!PyLong_Check(v)) {
14235 PyErr_SetString(PyExc_TypeError,
14236 "* wants int");
14237 return -1;
14238 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014239 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014240 if (arg->width == -1 && PyErr_Occurred())
14241 return -1;
14242 if (arg->width < 0) {
14243 arg->flags |= F_LJUST;
14244 arg->width = -arg->width;
14245 }
14246 if (--ctx->fmtcnt >= 0) {
14247 arg->ch = FORMAT_READ(ctx);
14248 ctx->fmtpos++;
14249 }
14250 }
14251 else if (arg->ch >= '0' && arg->ch <= '9') {
14252 arg->width = arg->ch - '0';
14253 while (--ctx->fmtcnt >= 0) {
14254 arg->ch = FORMAT_READ(ctx);
14255 ctx->fmtpos++;
14256 if (arg->ch < '0' || arg->ch > '9')
14257 break;
14258 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14259 mixing signed and unsigned comparison. Since arg->ch is between
14260 '0' and '9', casting to int is safe. */
14261 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14262 PyErr_SetString(PyExc_ValueError,
14263 "width too big");
14264 return -1;
14265 }
14266 arg->width = arg->width*10 + (arg->ch - '0');
14267 }
14268 }
14269
14270 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014271 if (arg->ch == '.') {
14272 arg->prec = 0;
14273 if (--ctx->fmtcnt >= 0) {
14274 arg->ch = FORMAT_READ(ctx);
14275 ctx->fmtpos++;
14276 }
14277 if (arg->ch == '*') {
14278 v = unicode_format_getnextarg(ctx);
14279 if (v == NULL)
14280 return -1;
14281 if (!PyLong_Check(v)) {
14282 PyErr_SetString(PyExc_TypeError,
14283 "* wants int");
14284 return -1;
14285 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014286 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014287 if (arg->prec == -1 && PyErr_Occurred())
14288 return -1;
14289 if (arg->prec < 0)
14290 arg->prec = 0;
14291 if (--ctx->fmtcnt >= 0) {
14292 arg->ch = FORMAT_READ(ctx);
14293 ctx->fmtpos++;
14294 }
14295 }
14296 else if (arg->ch >= '0' && arg->ch <= '9') {
14297 arg->prec = arg->ch - '0';
14298 while (--ctx->fmtcnt >= 0) {
14299 arg->ch = FORMAT_READ(ctx);
14300 ctx->fmtpos++;
14301 if (arg->ch < '0' || arg->ch > '9')
14302 break;
14303 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14304 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014305 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014306 return -1;
14307 }
14308 arg->prec = arg->prec*10 + (arg->ch - '0');
14309 }
14310 }
14311 }
14312
14313 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14314 if (ctx->fmtcnt >= 0) {
14315 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14316 if (--ctx->fmtcnt >= 0) {
14317 arg->ch = FORMAT_READ(ctx);
14318 ctx->fmtpos++;
14319 }
14320 }
14321 }
14322 if (ctx->fmtcnt < 0) {
14323 PyErr_SetString(PyExc_ValueError,
14324 "incomplete format");
14325 return -1;
14326 }
14327 return 0;
14328
14329#undef FORMAT_READ
14330}
14331
14332/* Format one argument. Supported conversion specifiers:
14333
14334 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014335 - "i", "d", "u": int or float
14336 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014337 - "e", "E", "f", "F", "g", "G": float
14338 - "c": int or str (1 character)
14339
Victor Stinner8dbd4212012-12-04 09:30:24 +010014340 When possible, the output is written directly into the Unicode writer
14341 (ctx->writer). A string is created when padding is required.
14342
Victor Stinnera47082312012-10-04 02:19:54 +020014343 Return 0 if the argument has been formatted into *p_str,
14344 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014345 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014346static int
14347unicode_format_arg_format(struct unicode_formatter_t *ctx,
14348 struct unicode_format_arg_t *arg,
14349 PyObject **p_str)
14350{
14351 PyObject *v;
14352 _PyUnicodeWriter *writer = &ctx->writer;
14353
14354 if (ctx->fmtcnt == 0)
14355 ctx->writer.overallocate = 0;
14356
14357 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014358 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014359 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014360 return 1;
14361 }
14362
14363 v = unicode_format_getnextarg(ctx);
14364 if (v == NULL)
14365 return -1;
14366
Victor Stinnera47082312012-10-04 02:19:54 +020014367
14368 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014369 case 's':
14370 case 'r':
14371 case 'a':
14372 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14373 /* Fast path */
14374 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14375 return -1;
14376 return 1;
14377 }
14378
14379 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14380 *p_str = v;
14381 Py_INCREF(*p_str);
14382 }
14383 else {
14384 if (arg->ch == 's')
14385 *p_str = PyObject_Str(v);
14386 else if (arg->ch == 'r')
14387 *p_str = PyObject_Repr(v);
14388 else
14389 *p_str = PyObject_ASCII(v);
14390 }
14391 break;
14392
14393 case 'i':
14394 case 'd':
14395 case 'u':
14396 case 'o':
14397 case 'x':
14398 case 'X':
14399 {
14400 int ret = mainformatlong(v, arg, p_str, writer);
14401 if (ret != 0)
14402 return ret;
14403 arg->sign = 1;
14404 break;
14405 }
14406
14407 case 'e':
14408 case 'E':
14409 case 'f':
14410 case 'F':
14411 case 'g':
14412 case 'G':
14413 if (arg->width == -1 && arg->prec == -1
14414 && !(arg->flags & (F_SIGN | F_BLANK)))
14415 {
14416 /* Fast path */
14417 if (formatfloat(v, arg, NULL, writer) == -1)
14418 return -1;
14419 return 1;
14420 }
14421
14422 arg->sign = 1;
14423 if (formatfloat(v, arg, p_str, NULL) == -1)
14424 return -1;
14425 break;
14426
14427 case 'c':
14428 {
14429 Py_UCS4 ch = formatchar(v);
14430 if (ch == (Py_UCS4) -1)
14431 return -1;
14432 if (arg->width == -1 && arg->prec == -1) {
14433 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014434 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014435 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014436 return 1;
14437 }
14438 *p_str = PyUnicode_FromOrdinal(ch);
14439 break;
14440 }
14441
14442 default:
14443 PyErr_Format(PyExc_ValueError,
14444 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014445 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014446 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14447 (int)arg->ch,
14448 ctx->fmtpos - 1);
14449 return -1;
14450 }
14451 if (*p_str == NULL)
14452 return -1;
14453 assert (PyUnicode_Check(*p_str));
14454 return 0;
14455}
14456
14457static int
14458unicode_format_arg_output(struct unicode_formatter_t *ctx,
14459 struct unicode_format_arg_t *arg,
14460 PyObject *str)
14461{
14462 Py_ssize_t len;
14463 enum PyUnicode_Kind kind;
14464 void *pbuf;
14465 Py_ssize_t pindex;
14466 Py_UCS4 signchar;
14467 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014468 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014469 Py_ssize_t sublen;
14470 _PyUnicodeWriter *writer = &ctx->writer;
14471 Py_UCS4 fill;
14472
14473 fill = ' ';
14474 if (arg->sign && arg->flags & F_ZERO)
14475 fill = '0';
14476
14477 if (PyUnicode_READY(str) == -1)
14478 return -1;
14479
14480 len = PyUnicode_GET_LENGTH(str);
14481 if ((arg->width == -1 || arg->width <= len)
14482 && (arg->prec == -1 || arg->prec >= len)
14483 && !(arg->flags & (F_SIGN | F_BLANK)))
14484 {
14485 /* Fast path */
14486 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14487 return -1;
14488 return 0;
14489 }
14490
14491 /* Truncate the string for "s", "r" and "a" formats
14492 if the precision is set */
14493 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14494 if (arg->prec >= 0 && len > arg->prec)
14495 len = arg->prec;
14496 }
14497
14498 /* Adjust sign and width */
14499 kind = PyUnicode_KIND(str);
14500 pbuf = PyUnicode_DATA(str);
14501 pindex = 0;
14502 signchar = '\0';
14503 if (arg->sign) {
14504 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14505 if (ch == '-' || ch == '+') {
14506 signchar = ch;
14507 len--;
14508 pindex++;
14509 }
14510 else if (arg->flags & F_SIGN)
14511 signchar = '+';
14512 else if (arg->flags & F_BLANK)
14513 signchar = ' ';
14514 else
14515 arg->sign = 0;
14516 }
14517 if (arg->width < len)
14518 arg->width = len;
14519
14520 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014521 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014522 if (!(arg->flags & F_LJUST)) {
14523 if (arg->sign) {
14524 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014525 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014526 }
14527 else {
14528 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014529 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014530 }
14531 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014532 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14533 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014534 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014535 }
14536
Victor Stinnera47082312012-10-04 02:19:54 +020014537 buflen = arg->width;
14538 if (arg->sign && len == arg->width)
14539 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014540 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014541 return -1;
14542
14543 /* Write the sign if needed */
14544 if (arg->sign) {
14545 if (fill != ' ') {
14546 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14547 writer->pos += 1;
14548 }
14549 if (arg->width > len)
14550 arg->width--;
14551 }
14552
14553 /* Write the numeric prefix for "x", "X" and "o" formats
14554 if the alternate form is used.
14555 For example, write "0x" for the "%#x" format. */
14556 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14557 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14558 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14559 if (fill != ' ') {
14560 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14561 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14562 writer->pos += 2;
14563 pindex += 2;
14564 }
14565 arg->width -= 2;
14566 if (arg->width < 0)
14567 arg->width = 0;
14568 len -= 2;
14569 }
14570
14571 /* Pad left with the fill character if needed */
14572 if (arg->width > len && !(arg->flags & F_LJUST)) {
14573 sublen = arg->width - len;
14574 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14575 writer->pos += sublen;
14576 arg->width = len;
14577 }
14578
14579 /* If padding with spaces: write sign if needed and/or numeric prefix if
14580 the alternate form is used */
14581 if (fill == ' ') {
14582 if (arg->sign) {
14583 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14584 writer->pos += 1;
14585 }
14586 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14587 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14588 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14589 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14590 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14591 writer->pos += 2;
14592 pindex += 2;
14593 }
14594 }
14595
14596 /* Write characters */
14597 if (len) {
14598 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14599 str, pindex, len);
14600 writer->pos += len;
14601 }
14602
14603 /* Pad right with the fill character if needed */
14604 if (arg->width > len) {
14605 sublen = arg->width - len;
14606 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14607 writer->pos += sublen;
14608 }
14609 return 0;
14610}
14611
14612/* Helper of PyUnicode_Format(): format one arg.
14613 Return 0 on success, raise an exception and return -1 on error. */
14614static int
14615unicode_format_arg(struct unicode_formatter_t *ctx)
14616{
14617 struct unicode_format_arg_t arg;
14618 PyObject *str;
14619 int ret;
14620
Victor Stinner8dbd4212012-12-04 09:30:24 +010014621 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14622 arg.flags = 0;
14623 arg.width = -1;
14624 arg.prec = -1;
14625 arg.sign = 0;
14626 str = NULL;
14627
Victor Stinnera47082312012-10-04 02:19:54 +020014628 ret = unicode_format_arg_parse(ctx, &arg);
14629 if (ret == -1)
14630 return -1;
14631
14632 ret = unicode_format_arg_format(ctx, &arg, &str);
14633 if (ret == -1)
14634 return -1;
14635
14636 if (ret != 1) {
14637 ret = unicode_format_arg_output(ctx, &arg, str);
14638 Py_DECREF(str);
14639 if (ret == -1)
14640 return -1;
14641 }
14642
14643 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14644 PyErr_SetString(PyExc_TypeError,
14645 "not all arguments converted during string formatting");
14646 return -1;
14647 }
14648 return 0;
14649}
14650
Alexander Belopolsky40018472011-02-26 01:02:56 +000014651PyObject *
14652PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014653{
Victor Stinnera47082312012-10-04 02:19:54 +020014654 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014655
Guido van Rossumd57fd912000-03-10 22:53:23 +000014656 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014657 PyErr_BadInternalCall();
14658 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014659 }
Victor Stinnera47082312012-10-04 02:19:54 +020014660
14661 ctx.fmtstr = PyUnicode_FromObject(format);
14662 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014663 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014664 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14665 Py_DECREF(ctx.fmtstr);
14666 return NULL;
14667 }
14668 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14669 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14670 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14671 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014672
Victor Stinner8f674cc2013-04-17 23:02:17 +020014673 _PyUnicodeWriter_Init(&ctx.writer);
14674 ctx.writer.min_length = ctx.fmtcnt + 100;
14675 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014676
Guido van Rossumd57fd912000-03-10 22:53:23 +000014677 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014678 ctx.arglen = PyTuple_Size(args);
14679 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014680 }
14681 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014682 ctx.arglen = -1;
14683 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014684 }
Victor Stinnera47082312012-10-04 02:19:54 +020014685 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014686 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014687 ctx.dict = args;
14688 else
14689 ctx.dict = NULL;
14690 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014691
Victor Stinnera47082312012-10-04 02:19:54 +020014692 while (--ctx.fmtcnt >= 0) {
14693 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014694 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014695
14696 nonfmtpos = ctx.fmtpos++;
14697 while (ctx.fmtcnt >= 0 &&
14698 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14699 ctx.fmtpos++;
14700 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014701 }
Victor Stinnera47082312012-10-04 02:19:54 +020014702 if (ctx.fmtcnt < 0) {
14703 ctx.fmtpos--;
14704 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014705 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014706
Victor Stinnercfc4c132013-04-03 01:48:39 +020014707 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14708 nonfmtpos, ctx.fmtpos) < 0)
14709 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014710 }
14711 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014712 ctx.fmtpos++;
14713 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014714 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014715 }
14716 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014717
Victor Stinnera47082312012-10-04 02:19:54 +020014718 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014719 PyErr_SetString(PyExc_TypeError,
14720 "not all arguments converted during string formatting");
14721 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014722 }
14723
Victor Stinnera47082312012-10-04 02:19:54 +020014724 if (ctx.args_owned) {
14725 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014726 }
Victor Stinnera47082312012-10-04 02:19:54 +020014727 Py_DECREF(ctx.fmtstr);
14728 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014729
Benjamin Peterson29060642009-01-31 22:14:21 +000014730 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014731 Py_DECREF(ctx.fmtstr);
14732 _PyUnicodeWriter_Dealloc(&ctx.writer);
14733 if (ctx.args_owned) {
14734 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014735 }
14736 return NULL;
14737}
14738
Jeremy Hylton938ace62002-07-17 16:30:39 +000014739static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014740unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14741
Tim Peters6d6c1a32001-08-02 04:15:00 +000014742static PyObject *
14743unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14744{
Benjamin Peterson29060642009-01-31 22:14:21 +000014745 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014746 static char *kwlist[] = {"object", "encoding", "errors", 0};
14747 char *encoding = NULL;
14748 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014749
Benjamin Peterson14339b62009-01-31 16:36:08 +000014750 if (type != &PyUnicode_Type)
14751 return unicode_subtype_new(type, args, kwds);
14752 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014753 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014754 return NULL;
14755 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014756 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014757 if (encoding == NULL && errors == NULL)
14758 return PyObject_Str(x);
14759 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014760 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014761}
14762
Guido van Rossume023fe02001-08-30 03:12:59 +000014763static PyObject *
14764unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14765{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014766 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014767 Py_ssize_t length, char_size;
14768 int share_wstr, share_utf8;
14769 unsigned int kind;
14770 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014771
Benjamin Peterson14339b62009-01-31 16:36:08 +000014772 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014773
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014774 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014775 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014776 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014777 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014778 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014779 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014780 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014781 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014782
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014783 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014784 if (self == NULL) {
14785 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014786 return NULL;
14787 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014788 kind = PyUnicode_KIND(unicode);
14789 length = PyUnicode_GET_LENGTH(unicode);
14790
14791 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014792#ifdef Py_DEBUG
14793 _PyUnicode_HASH(self) = -1;
14794#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014795 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014796#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014797 _PyUnicode_STATE(self).interned = 0;
14798 _PyUnicode_STATE(self).kind = kind;
14799 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014800 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014801 _PyUnicode_STATE(self).ready = 1;
14802 _PyUnicode_WSTR(self) = NULL;
14803 _PyUnicode_UTF8_LENGTH(self) = 0;
14804 _PyUnicode_UTF8(self) = NULL;
14805 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014806 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014807
14808 share_utf8 = 0;
14809 share_wstr = 0;
14810 if (kind == PyUnicode_1BYTE_KIND) {
14811 char_size = 1;
14812 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14813 share_utf8 = 1;
14814 }
14815 else if (kind == PyUnicode_2BYTE_KIND) {
14816 char_size = 2;
14817 if (sizeof(wchar_t) == 2)
14818 share_wstr = 1;
14819 }
14820 else {
14821 assert(kind == PyUnicode_4BYTE_KIND);
14822 char_size = 4;
14823 if (sizeof(wchar_t) == 4)
14824 share_wstr = 1;
14825 }
14826
14827 /* Ensure we won't overflow the length. */
14828 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14829 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014830 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014831 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014832 data = PyObject_MALLOC((length + 1) * char_size);
14833 if (data == NULL) {
14834 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014835 goto onError;
14836 }
14837
Victor Stinnerc3c74152011-10-02 20:39:55 +020014838 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014839 if (share_utf8) {
14840 _PyUnicode_UTF8_LENGTH(self) = length;
14841 _PyUnicode_UTF8(self) = data;
14842 }
14843 if (share_wstr) {
14844 _PyUnicode_WSTR_LENGTH(self) = length;
14845 _PyUnicode_WSTR(self) = (wchar_t *)data;
14846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014847
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014848 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014849 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014850 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014851#ifdef Py_DEBUG
14852 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14853#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014854 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014855 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014856
14857onError:
14858 Py_DECREF(unicode);
14859 Py_DECREF(self);
14860 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014861}
14862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014863PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014864"str(object='') -> str\n\
14865str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014866\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014867Create a new string object from the given object. If encoding or\n\
14868errors is specified, then the object must expose a data buffer\n\
14869that will be decoded using the given encoding and error handler.\n\
14870Otherwise, returns the result of object.__str__() (if defined)\n\
14871or repr(object).\n\
14872encoding defaults to sys.getdefaultencoding().\n\
14873errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014874
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014875static PyObject *unicode_iter(PyObject *seq);
14876
Guido van Rossumd57fd912000-03-10 22:53:23 +000014877PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014878 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014879 "str", /* tp_name */
14880 sizeof(PyUnicodeObject), /* tp_size */
14881 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014882 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014883 (destructor)unicode_dealloc, /* tp_dealloc */
14884 0, /* tp_print */
14885 0, /* tp_getattr */
14886 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014887 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014888 unicode_repr, /* tp_repr */
14889 &unicode_as_number, /* tp_as_number */
14890 &unicode_as_sequence, /* tp_as_sequence */
14891 &unicode_as_mapping, /* tp_as_mapping */
14892 (hashfunc) unicode_hash, /* tp_hash*/
14893 0, /* tp_call*/
14894 (reprfunc) unicode_str, /* tp_str */
14895 PyObject_GenericGetAttr, /* tp_getattro */
14896 0, /* tp_setattro */
14897 0, /* tp_as_buffer */
14898 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014899 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014900 unicode_doc, /* tp_doc */
14901 0, /* tp_traverse */
14902 0, /* tp_clear */
14903 PyUnicode_RichCompare, /* tp_richcompare */
14904 0, /* tp_weaklistoffset */
14905 unicode_iter, /* tp_iter */
14906 0, /* tp_iternext */
14907 unicode_methods, /* tp_methods */
14908 0, /* tp_members */
14909 0, /* tp_getset */
14910 &PyBaseObject_Type, /* tp_base */
14911 0, /* tp_dict */
14912 0, /* tp_descr_get */
14913 0, /* tp_descr_set */
14914 0, /* tp_dictoffset */
14915 0, /* tp_init */
14916 0, /* tp_alloc */
14917 unicode_new, /* tp_new */
14918 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014919};
14920
14921/* Initialize the Unicode implementation */
14922
Victor Stinner3a50e702011-10-18 21:21:00 +020014923int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014924{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014925 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014926 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014927 0x000A, /* LINE FEED */
14928 0x000D, /* CARRIAGE RETURN */
14929 0x001C, /* FILE SEPARATOR */
14930 0x001D, /* GROUP SEPARATOR */
14931 0x001E, /* RECORD SEPARATOR */
14932 0x0085, /* NEXT LINE */
14933 0x2028, /* LINE SEPARATOR */
14934 0x2029, /* PARAGRAPH SEPARATOR */
14935 };
14936
Fred Drakee4315f52000-05-09 19:53:39 +000014937 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014938 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014939 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014940 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014941 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014942
Guido van Rossumcacfc072002-05-24 19:01:59 +000014943 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014944 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014945
14946 /* initialize the linebreak bloom filter */
14947 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014948 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014949 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014950
Christian Heimes26532f72013-07-20 14:57:16 +020014951 if (PyType_Ready(&EncodingMapType) < 0)
14952 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014953
Benjamin Petersonc4311282012-10-30 23:21:10 -040014954 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14955 Py_FatalError("Can't initialize field name iterator type");
14956
14957 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14958 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014959
Victor Stinner3a50e702011-10-18 21:21:00 +020014960#ifdef HAVE_MBCS
14961 winver.dwOSVersionInfoSize = sizeof(winver);
14962 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14963 PyErr_SetFromWindowsErr(0);
14964 return -1;
14965 }
14966#endif
14967 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014968}
14969
14970/* Finalize the Unicode implementation */
14971
Christian Heimesa156e092008-02-16 07:38:31 +000014972int
14973PyUnicode_ClearFreeList(void)
14974{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014975 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014976}
14977
Guido van Rossumd57fd912000-03-10 22:53:23 +000014978void
Thomas Wouters78890102000-07-22 19:25:51 +000014979_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014980{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014981 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014982
Serhiy Storchaka05997252013-01-26 12:14:02 +020014983 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014984
Serhiy Storchaka05997252013-01-26 12:14:02 +020014985 for (i = 0; i < 256; i++)
14986 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014987 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014988 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014989}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014990
Walter Dörwald16807132007-05-25 13:52:07 +000014991void
14992PyUnicode_InternInPlace(PyObject **p)
14993{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014994 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014995 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014996#ifdef Py_DEBUG
14997 assert(s != NULL);
14998 assert(_PyUnicode_CHECK(s));
14999#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015000 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015001 return;
15002#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015003 /* If it's a subclass, we don't really know what putting
15004 it in the interned dict might do. */
15005 if (!PyUnicode_CheckExact(s))
15006 return;
15007 if (PyUnicode_CHECK_INTERNED(s))
15008 return;
15009 if (interned == NULL) {
15010 interned = PyDict_New();
15011 if (interned == NULL) {
15012 PyErr_Clear(); /* Don't leave an exception */
15013 return;
15014 }
15015 }
15016 /* It might be that the GetItem call fails even
15017 though the key is present in the dictionary,
15018 namely when this happens during a stack overflow. */
15019 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015020 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015021 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015022
Victor Stinnerf0335102013-04-14 19:13:03 +020015023 if (t) {
15024 Py_INCREF(t);
15025 Py_DECREF(*p);
15026 *p = t;
15027 return;
15028 }
Walter Dörwald16807132007-05-25 13:52:07 +000015029
Benjamin Peterson14339b62009-01-31 16:36:08 +000015030 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015031 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015032 PyErr_Clear();
15033 PyThreadState_GET()->recursion_critical = 0;
15034 return;
15035 }
15036 PyThreadState_GET()->recursion_critical = 0;
15037 /* The two references in interned are not counted by refcnt.
15038 The deallocator will take care of this */
15039 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015040 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015041}
15042
15043void
15044PyUnicode_InternImmortal(PyObject **p)
15045{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015046 PyUnicode_InternInPlace(p);
15047 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015048 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015049 Py_INCREF(*p);
15050 }
Walter Dörwald16807132007-05-25 13:52:07 +000015051}
15052
15053PyObject *
15054PyUnicode_InternFromString(const char *cp)
15055{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015056 PyObject *s = PyUnicode_FromString(cp);
15057 if (s == NULL)
15058 return NULL;
15059 PyUnicode_InternInPlace(&s);
15060 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015061}
15062
Alexander Belopolsky40018472011-02-26 01:02:56 +000015063void
15064_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015065{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015066 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015067 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015068 Py_ssize_t i, n;
15069 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015070
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 if (interned == NULL || !PyDict_Check(interned))
15072 return;
15073 keys = PyDict_Keys(interned);
15074 if (keys == NULL || !PyList_Check(keys)) {
15075 PyErr_Clear();
15076 return;
15077 }
Walter Dörwald16807132007-05-25 13:52:07 +000015078
Benjamin Peterson14339b62009-01-31 16:36:08 +000015079 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15080 detector, interned unicode strings are not forcibly deallocated;
15081 rather, we give them their stolen references back, and then clear
15082 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015083
Benjamin Peterson14339b62009-01-31 16:36:08 +000015084 n = PyList_GET_SIZE(keys);
15085 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015086 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015088 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015089 if (PyUnicode_READY(s) == -1) {
15090 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015091 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015092 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015093 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 case SSTATE_NOT_INTERNED:
15095 /* XXX Shouldn't happen */
15096 break;
15097 case SSTATE_INTERNED_IMMORTAL:
15098 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015099 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015100 break;
15101 case SSTATE_INTERNED_MORTAL:
15102 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015103 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015104 break;
15105 default:
15106 Py_FatalError("Inconsistent interned string state.");
15107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015108 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015109 }
15110 fprintf(stderr, "total size of all interned strings: "
15111 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15112 "mortal/immortal\n", mortal_size, immortal_size);
15113 Py_DECREF(keys);
15114 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015115 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015116}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015117
15118
15119/********************* Unicode Iterator **************************/
15120
15121typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015122 PyObject_HEAD
15123 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015124 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015125} unicodeiterobject;
15126
15127static void
15128unicodeiter_dealloc(unicodeiterobject *it)
15129{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015130 _PyObject_GC_UNTRACK(it);
15131 Py_XDECREF(it->it_seq);
15132 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015133}
15134
15135static int
15136unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15137{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015138 Py_VISIT(it->it_seq);
15139 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015140}
15141
15142static PyObject *
15143unicodeiter_next(unicodeiterobject *it)
15144{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015145 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015146
Benjamin Peterson14339b62009-01-31 16:36:08 +000015147 assert(it != NULL);
15148 seq = it->it_seq;
15149 if (seq == NULL)
15150 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015151 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015153 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15154 int kind = PyUnicode_KIND(seq);
15155 void *data = PyUnicode_DATA(seq);
15156 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15157 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015158 if (item != NULL)
15159 ++it->it_index;
15160 return item;
15161 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015162
Benjamin Peterson14339b62009-01-31 16:36:08 +000015163 Py_DECREF(seq);
15164 it->it_seq = NULL;
15165 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015166}
15167
15168static PyObject *
15169unicodeiter_len(unicodeiterobject *it)
15170{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015171 Py_ssize_t len = 0;
15172 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015173 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015174 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015175}
15176
15177PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15178
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015179static PyObject *
15180unicodeiter_reduce(unicodeiterobject *it)
15181{
15182 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015183 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015184 it->it_seq, it->it_index);
15185 } else {
15186 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15187 if (u == NULL)
15188 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015189 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015190 }
15191}
15192
15193PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15194
15195static PyObject *
15196unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15197{
15198 Py_ssize_t index = PyLong_AsSsize_t(state);
15199 if (index == -1 && PyErr_Occurred())
15200 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015201 if (it->it_seq != NULL) {
15202 if (index < 0)
15203 index = 0;
15204 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15205 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15206 it->it_index = index;
15207 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015208 Py_RETURN_NONE;
15209}
15210
15211PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15212
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015213static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015214 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015215 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015216 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15217 reduce_doc},
15218 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15219 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015220 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015221};
15222
15223PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015224 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15225 "str_iterator", /* tp_name */
15226 sizeof(unicodeiterobject), /* tp_basicsize */
15227 0, /* tp_itemsize */
15228 /* methods */
15229 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15230 0, /* tp_print */
15231 0, /* tp_getattr */
15232 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015233 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015234 0, /* tp_repr */
15235 0, /* tp_as_number */
15236 0, /* tp_as_sequence */
15237 0, /* tp_as_mapping */
15238 0, /* tp_hash */
15239 0, /* tp_call */
15240 0, /* tp_str */
15241 PyObject_GenericGetAttr, /* tp_getattro */
15242 0, /* tp_setattro */
15243 0, /* tp_as_buffer */
15244 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15245 0, /* tp_doc */
15246 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15247 0, /* tp_clear */
15248 0, /* tp_richcompare */
15249 0, /* tp_weaklistoffset */
15250 PyObject_SelfIter, /* tp_iter */
15251 (iternextfunc)unicodeiter_next, /* tp_iternext */
15252 unicodeiter_methods, /* tp_methods */
15253 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015254};
15255
15256static PyObject *
15257unicode_iter(PyObject *seq)
15258{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015260
Benjamin Peterson14339b62009-01-31 16:36:08 +000015261 if (!PyUnicode_Check(seq)) {
15262 PyErr_BadInternalCall();
15263 return NULL;
15264 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015265 if (PyUnicode_READY(seq) == -1)
15266 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015267 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15268 if (it == NULL)
15269 return NULL;
15270 it->it_index = 0;
15271 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015272 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 _PyObject_GC_TRACK(it);
15274 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015275}
15276
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015277
15278size_t
15279Py_UNICODE_strlen(const Py_UNICODE *u)
15280{
15281 int res = 0;
15282 while(*u++)
15283 res++;
15284 return res;
15285}
15286
15287Py_UNICODE*
15288Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15289{
15290 Py_UNICODE *u = s1;
15291 while ((*u++ = *s2++));
15292 return s1;
15293}
15294
15295Py_UNICODE*
15296Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15297{
15298 Py_UNICODE *u = s1;
15299 while ((*u++ = *s2++))
15300 if (n-- == 0)
15301 break;
15302 return s1;
15303}
15304
15305Py_UNICODE*
15306Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15307{
15308 Py_UNICODE *u1 = s1;
15309 u1 += Py_UNICODE_strlen(u1);
15310 Py_UNICODE_strcpy(u1, s2);
15311 return s1;
15312}
15313
15314int
15315Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15316{
15317 while (*s1 && *s2 && *s1 == *s2)
15318 s1++, s2++;
15319 if (*s1 && *s2)
15320 return (*s1 < *s2) ? -1 : +1;
15321 if (*s1)
15322 return 1;
15323 if (*s2)
15324 return -1;
15325 return 0;
15326}
15327
15328int
15329Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15330{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015331 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015332 for (; n != 0; n--) {
15333 u1 = *s1;
15334 u2 = *s2;
15335 if (u1 != u2)
15336 return (u1 < u2) ? -1 : +1;
15337 if (u1 == '\0')
15338 return 0;
15339 s1++;
15340 s2++;
15341 }
15342 return 0;
15343}
15344
15345Py_UNICODE*
15346Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15347{
15348 const Py_UNICODE *p;
15349 for (p = s; *p; p++)
15350 if (*p == c)
15351 return (Py_UNICODE*)p;
15352 return NULL;
15353}
15354
15355Py_UNICODE*
15356Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15357{
15358 const Py_UNICODE *p;
15359 p = s + Py_UNICODE_strlen(s);
15360 while (p != s) {
15361 p--;
15362 if (*p == c)
15363 return (Py_UNICODE*)p;
15364 }
15365 return NULL;
15366}
Victor Stinner331ea922010-08-10 16:37:20 +000015367
Victor Stinner71133ff2010-09-01 23:43:53 +000015368Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015369PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015370{
Victor Stinner577db2c2011-10-11 22:12:48 +020015371 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015372 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015373
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015374 if (!PyUnicode_Check(unicode)) {
15375 PyErr_BadArgument();
15376 return NULL;
15377 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015378 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015379 if (u == NULL)
15380 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015381 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015382 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015383 PyErr_NoMemory();
15384 return NULL;
15385 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015386 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015387 size *= sizeof(Py_UNICODE);
15388 copy = PyMem_Malloc(size);
15389 if (copy == NULL) {
15390 PyErr_NoMemory();
15391 return NULL;
15392 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015393 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015394 return copy;
15395}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015396
Georg Brandl66c221e2010-10-14 07:04:07 +000015397/* A _string module, to export formatter_parser and formatter_field_name_split
15398 to the string.Formatter class implemented in Python. */
15399
15400static PyMethodDef _string_methods[] = {
15401 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15402 METH_O, PyDoc_STR("split the argument as a field name")},
15403 {"formatter_parser", (PyCFunction) formatter_parser,
15404 METH_O, PyDoc_STR("parse the argument as a format string")},
15405 {NULL, NULL}
15406};
15407
15408static struct PyModuleDef _string_module = {
15409 PyModuleDef_HEAD_INIT,
15410 "_string",
15411 PyDoc_STR("string helper module"),
15412 0,
15413 _string_methods,
15414 NULL,
15415 NULL,
15416 NULL,
15417 NULL
15418};
15419
15420PyMODINIT_FUNC
15421PyInit__string(void)
15422{
15423 return PyModule_Create(&_string_module);
15424}
15425
15426
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015427#ifdef __cplusplus
15428}
15429#endif