blob: d0b285abac07d5f38cbb46c5641270b1710406fc [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"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070045#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000046
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000047#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000048#include <windows.h>
49#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000050
Larry Hastings61272b72014-01-07 12:41:53 -080051/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080052class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080053[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080054/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080055
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000056/* --- Globals ------------------------------------------------------------
57
Serhiy Storchaka05997252013-01-26 12:14:02 +020058NOTE: In the interpreter's initialization phase, some globals are currently
59 initialized dynamically as needed. In the process Unicode objects may
60 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200131 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200138 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200139 (!PyUnicode_IS_READY(op) || \
140 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
141
Victor Stinner910337b2011-10-03 03:20:16 +0200142/* Generic helper macro to convert characters of different types.
143 from_type and to_type have to be valid type names, begin and end
144 are pointers to the source characters which should be of type
145 "from_type *". to is a pointer of type "to_type *" and points to the
146 buffer where the result characters are written to. */
147#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
148 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100149 to_type *_to = (to_type *)(to); \
150 const from_type *_iter = (from_type *)(begin); \
151 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 Py_ssize_t n = (_end) - (_iter); \
153 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200154 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200155 while (_iter < (_unrolled_end)) { \
156 _to[0] = (to_type) _iter[0]; \
157 _to[1] = (to_type) _iter[1]; \
158 _to[2] = (to_type) _iter[2]; \
159 _to[3] = (to_type) _iter[3]; \
160 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200161 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200162 while (_iter < (_end)) \
163 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200165
Walter Dörwald16807132007-05-25 13:52:07 +0000166/* This dictionary holds all interned unicode strings. Note that references
167 to strings in this dictionary are *not* counted in the string's ob_refcnt.
168 When the interned string reaches a refcnt of 0 the string deallocation
169 function will delete the reference from this dictionary.
170
171 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000172 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000173*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200174static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000175
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000176/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200177static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200178
Serhiy Storchaka678db842013-01-26 12:16:36 +0200179#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200180 do { \
181 if (unicode_empty != NULL) \
182 Py_INCREF(unicode_empty); \
183 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200184 unicode_empty = PyUnicode_New(0, 0); \
185 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200190 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000191
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192#define _Py_RETURN_UNICODE_EMPTY() \
193 do { \
194 _Py_INCREF_UNICODE_EMPTY(); \
195 return unicode_empty; \
196 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000197
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200198/* Forward declaration */
199Py_LOCAL_INLINE(int)
200_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
201
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200202/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200203static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200204
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205/* Single character Unicode strings in the Latin-1 range are being
206 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000208
Christian Heimes190d79e2008-01-30 11:58:22 +0000209/* Fast detection of the most frequent whitespace characters */
210const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000212/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000213/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000214/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000215/* case 0x000C: * FORM FEED */
216/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000217 0, 1, 1, 1, 1, 1, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000219/* case 0x001C: * FILE SEPARATOR */
220/* case 0x001D: * GROUP SEPARATOR */
221/* case 0x001E: * RECORD SEPARATOR */
222/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000223 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000224/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 1, 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,
228 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000229
Benjamin Peterson14339b62009-01-31 16:36:08 +0000230 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,
237 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000238};
239
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200240/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200241static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200242static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100243static int unicode_modifiable(PyObject *unicode);
244
Victor Stinnerfe226c02011-10-03 03:52:20 +0200245
Alexander Belopolsky40018472011-02-26 01:02:56 +0000246static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100247_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200248static PyObject *
249_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
250static PyObject *
251_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
252
253static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000255 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100256 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000257 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
258
Alexander Belopolsky40018472011-02-26 01:02:56 +0000259static void
260raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300261 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100262 PyObject *unicode,
263 Py_ssize_t startpos, Py_ssize_t endpos,
264 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000265
Christian Heimes190d79e2008-01-30 11:58:22 +0000266/* Same for linebreaks */
267static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000270/* 0x000B, * LINE TABULATION */
271/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000272/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000273 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000274 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000275/* 0x001C, * FILE SEPARATOR */
276/* 0x001D, * GROUP SEPARATOR */
277/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000278 0, 0, 0, 0, 1, 1, 1, 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,
282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000283
Benjamin Peterson14339b62009-01-31 16:36:08 +0000284 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,
291 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000292};
293
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300294#include "clinic/unicodeobject.c.h"
295
Victor Stinner50149202015-09-22 00:26:54 +0200296typedef enum {
297 _Py_ERROR_UNKNOWN=0,
298 _Py_ERROR_STRICT,
299 _Py_ERROR_SURROGATEESCAPE,
300 _Py_ERROR_REPLACE,
301 _Py_ERROR_IGNORE,
302 _Py_ERROR_XMLCHARREFREPLACE,
303 _Py_ERROR_OTHER
304} _Py_error_handler;
305
306static _Py_error_handler
307get_error_handler(const char *errors)
308{
309 if (errors == NULL)
310 return _Py_ERROR_STRICT;
311 if (strcmp(errors, "strict") == 0)
312 return _Py_ERROR_STRICT;
313 if (strcmp(errors, "surrogateescape") == 0)
314 return _Py_ERROR_SURROGATEESCAPE;
315 if (strcmp(errors, "ignore") == 0)
316 return _Py_ERROR_IGNORE;
317 if (strcmp(errors, "replace") == 0)
318 return _Py_ERROR_REPLACE;
319 if (strcmp(errors, "xmlcharrefreplace") == 0)
320 return _Py_ERROR_XMLCHARREFREPLACE;
321 return _Py_ERROR_OTHER;
322}
323
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300324/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
325 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000326Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000327PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000328{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000329#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000330 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000331#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000332 /* This is actually an illegal character, so it should
333 not be passed to unichr. */
334 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000335#endif
336}
337
Victor Stinner910337b2011-10-03 03:20:16 +0200338#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200339int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100340_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200341{
342 PyASCIIObject *ascii;
343 unsigned int kind;
344
345 assert(PyUnicode_Check(op));
346
347 ascii = (PyASCIIObject *)op;
348 kind = ascii->state.kind;
349
Victor Stinnera3b334d2011-10-03 13:53:37 +0200350 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200351 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200352 assert(ascii->state.ready == 1);
353 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200354 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200355 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200356 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200357
Victor Stinnera41463c2011-10-04 01:05:08 +0200358 if (ascii->state.compact == 1) {
359 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200360 assert(kind == PyUnicode_1BYTE_KIND
361 || kind == PyUnicode_2BYTE_KIND
362 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200363 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200364 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200365 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100366 }
367 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200368 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
369
370 data = unicode->data.any;
371 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100372 assert(ascii->length == 0);
373 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 assert(ascii->state.compact == 0);
375 assert(ascii->state.ascii == 0);
376 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100377 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200378 assert(ascii->wstr != NULL);
379 assert(data == NULL);
380 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200381 }
382 else {
383 assert(kind == PyUnicode_1BYTE_KIND
384 || kind == PyUnicode_2BYTE_KIND
385 || kind == PyUnicode_4BYTE_KIND);
386 assert(ascii->state.compact == 0);
387 assert(ascii->state.ready == 1);
388 assert(data != NULL);
389 if (ascii->state.ascii) {
390 assert (compact->utf8 == data);
391 assert (compact->utf8_length == ascii->length);
392 }
393 else
394 assert (compact->utf8 != data);
395 }
396 }
397 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200398 if (
399#if SIZEOF_WCHAR_T == 2
400 kind == PyUnicode_2BYTE_KIND
401#else
402 kind == PyUnicode_4BYTE_KIND
403#endif
404 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200405 {
406 assert(ascii->wstr == data);
407 assert(compact->wstr_length == ascii->length);
408 } else
409 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200410 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200411
412 if (compact->utf8 == NULL)
413 assert(compact->utf8_length == 0);
414 if (ascii->wstr == NULL)
415 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200416 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200417 /* check that the best kind is used */
418 if (check_content && kind != PyUnicode_WCHAR_KIND)
419 {
420 Py_ssize_t i;
421 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200422 void *data;
423 Py_UCS4 ch;
424
425 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200426 for (i=0; i < ascii->length; i++)
427 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200428 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200429 if (ch > maxchar)
430 maxchar = ch;
431 }
432 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100433 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200434 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100435 assert(maxchar <= 255);
436 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200437 else
438 assert(maxchar < 128);
439 }
Victor Stinner77faf692011-11-20 18:56:05 +0100440 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200441 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100442 assert(maxchar <= 0xFFFF);
443 }
444 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200445 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100446 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100447 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200448 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200449 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400450 return 1;
451}
Victor Stinner910337b2011-10-03 03:20:16 +0200452#endif
453
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100454static PyObject*
455unicode_result_wchar(PyObject *unicode)
456{
457#ifndef Py_DEBUG
458 Py_ssize_t len;
459
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100460 len = _PyUnicode_WSTR_LENGTH(unicode);
461 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100462 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200463 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100464 }
465
466 if (len == 1) {
467 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100468 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100469 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
470 Py_DECREF(unicode);
471 return latin1_char;
472 }
473 }
474
475 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200476 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100477 return NULL;
478 }
479#else
Victor Stinneraa771272012-10-04 02:32:58 +0200480 assert(Py_REFCNT(unicode) == 1);
481
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100482 /* don't make the result ready in debug mode to ensure that the caller
483 makes the string ready before using it */
484 assert(_PyUnicode_CheckConsistency(unicode, 1));
485#endif
486 return unicode;
487}
488
489static PyObject*
490unicode_result_ready(PyObject *unicode)
491{
492 Py_ssize_t length;
493
494 length = PyUnicode_GET_LENGTH(unicode);
495 if (length == 0) {
496 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100497 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200498 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100499 }
500 return unicode_empty;
501 }
502
503 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200504 void *data = PyUnicode_DATA(unicode);
505 int kind = PyUnicode_KIND(unicode);
506 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100507 if (ch < 256) {
508 PyObject *latin1_char = unicode_latin1[ch];
509 if (latin1_char != NULL) {
510 if (unicode != latin1_char) {
511 Py_INCREF(latin1_char);
512 Py_DECREF(unicode);
513 }
514 return latin1_char;
515 }
516 else {
517 assert(_PyUnicode_CheckConsistency(unicode, 1));
518 Py_INCREF(unicode);
519 unicode_latin1[ch] = unicode;
520 return unicode;
521 }
522 }
523 }
524
525 assert(_PyUnicode_CheckConsistency(unicode, 1));
526 return unicode;
527}
528
529static PyObject*
530unicode_result(PyObject *unicode)
531{
532 assert(_PyUnicode_CHECK(unicode));
533 if (PyUnicode_IS_READY(unicode))
534 return unicode_result_ready(unicode);
535 else
536 return unicode_result_wchar(unicode);
537}
538
Victor Stinnerc4b49542011-12-11 22:44:26 +0100539static PyObject*
540unicode_result_unchanged(PyObject *unicode)
541{
542 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500543 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100544 return NULL;
545 Py_INCREF(unicode);
546 return unicode;
547 }
548 else
549 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100550 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100551}
552
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553/* --- Bloom Filters ----------------------------------------------------- */
554
555/* stuff to implement simple "bloom filters" for Unicode characters.
556 to keep things simple, we use a single bitmask, using the least 5
557 bits from each unicode characters as the bit index. */
558
559/* the linebreak mask is set up by Unicode_Init below */
560
Antoine Pitrouf068f942010-01-13 14:19:12 +0000561#if LONG_BIT >= 128
562#define BLOOM_WIDTH 128
563#elif LONG_BIT >= 64
564#define BLOOM_WIDTH 64
565#elif LONG_BIT >= 32
566#define BLOOM_WIDTH 32
567#else
568#error "LONG_BIT is smaller than 32"
569#endif
570
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571#define BLOOM_MASK unsigned long
572
Serhiy Storchaka05997252013-01-26 12:14:02 +0200573static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574
Antoine Pitrouf068f942010-01-13 14:19:12 +0000575#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000576
Benjamin Peterson29060642009-01-31 22:14:21 +0000577#define BLOOM_LINEBREAK(ch) \
578 ((ch) < 128U ? ascii_linebreak[(ch)] : \
579 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000580
Alexander Belopolsky40018472011-02-26 01:02:56 +0000581Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200582make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583{
Victor Stinnera85af502013-04-09 21:53:54 +0200584#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
585 do { \
586 TYPE *data = (TYPE *)PTR; \
587 TYPE *end = data + LEN; \
588 Py_UCS4 ch; \
589 for (; data != end; data++) { \
590 ch = *data; \
591 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
592 } \
593 break; \
594 } while (0)
595
Thomas Wouters477c8d52006-05-27 19:21:47 +0000596 /* calculate simple bloom-style bitmask for a given unicode string */
597
Antoine Pitrouf068f942010-01-13 14:19:12 +0000598 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599
600 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200601 switch (kind) {
602 case PyUnicode_1BYTE_KIND:
603 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
604 break;
605 case PyUnicode_2BYTE_KIND:
606 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
607 break;
608 case PyUnicode_4BYTE_KIND:
609 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
610 break;
611 default:
612 assert(0);
613 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000614 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200615
616#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617}
618
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200619/* Compilation of templated routines */
620
621#include "stringlib/asciilib.h"
622#include "stringlib/fastsearch.h"
623#include "stringlib/partition.h"
624#include "stringlib/split.h"
625#include "stringlib/count.h"
626#include "stringlib/find.h"
627#include "stringlib/find_max_char.h"
628#include "stringlib/localeutil.h"
629#include "stringlib/undef.h"
630
631#include "stringlib/ucs1lib.h"
632#include "stringlib/fastsearch.h"
633#include "stringlib/partition.h"
634#include "stringlib/split.h"
635#include "stringlib/count.h"
636#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300637#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200638#include "stringlib/find_max_char.h"
639#include "stringlib/localeutil.h"
640#include "stringlib/undef.h"
641
642#include "stringlib/ucs2lib.h"
643#include "stringlib/fastsearch.h"
644#include "stringlib/partition.h"
645#include "stringlib/split.h"
646#include "stringlib/count.h"
647#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300648#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200649#include "stringlib/find_max_char.h"
650#include "stringlib/localeutil.h"
651#include "stringlib/undef.h"
652
653#include "stringlib/ucs4lib.h"
654#include "stringlib/fastsearch.h"
655#include "stringlib/partition.h"
656#include "stringlib/split.h"
657#include "stringlib/count.h"
658#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300659#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200660#include "stringlib/find_max_char.h"
661#include "stringlib/localeutil.h"
662#include "stringlib/undef.h"
663
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200664#include "stringlib/unicodedefs.h"
665#include "stringlib/fastsearch.h"
666#include "stringlib/count.h"
667#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100668#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200669
Guido van Rossumd57fd912000-03-10 22:53:23 +0000670/* --- Unicode Object ----------------------------------------------------- */
671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200673fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200674
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200675Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200676 Py_ssize_t size, Py_UCS4 ch,
677 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200678{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200679 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
680
681 switch (kind) {
682 case PyUnicode_1BYTE_KIND:
683 {
684 Py_UCS1 ch1 = (Py_UCS1) ch;
685 if (ch1 == ch)
686 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
687 else
688 return -1;
689 }
690 case PyUnicode_2BYTE_KIND:
691 {
692 Py_UCS2 ch2 = (Py_UCS2) ch;
693 if (ch2 == ch)
694 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
695 else
696 return -1;
697 }
698 case PyUnicode_4BYTE_KIND:
699 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
700 default:
701 assert(0);
702 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200703 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200704}
705
Victor Stinnerafffce42012-10-03 23:03:17 +0200706#ifdef Py_DEBUG
707/* Fill the data of an Unicode string with invalid characters to detect bugs
708 earlier.
709
710 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
711 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
712 invalid character in Unicode 6.0. */
713static void
714unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
715{
716 int kind = PyUnicode_KIND(unicode);
717 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
718 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
719 if (length <= old_length)
720 return;
721 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
722}
723#endif
724
Victor Stinnerfe226c02011-10-03 03:52:20 +0200725static PyObject*
726resize_compact(PyObject *unicode, Py_ssize_t length)
727{
728 Py_ssize_t char_size;
729 Py_ssize_t struct_size;
730 Py_ssize_t new_size;
731 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100732 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200733#ifdef Py_DEBUG
734 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
735#endif
736
Victor Stinner79891572012-05-03 13:43:07 +0200737 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100739 assert(PyUnicode_IS_COMPACT(unicode));
740
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200741 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100742 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200743 struct_size = sizeof(PyASCIIObject);
744 else
745 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200746 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200747
Victor Stinnerfe226c02011-10-03 03:52:20 +0200748 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
749 PyErr_NoMemory();
750 return NULL;
751 }
752 new_size = (struct_size + (length + 1) * char_size);
753
Victor Stinner84def372011-12-11 20:04:56 +0100754 _Py_DEC_REFTOTAL;
755 _Py_ForgetReference(unicode);
756
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300757 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100758 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100759 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 PyErr_NoMemory();
761 return NULL;
762 }
Victor Stinner84def372011-12-11 20:04:56 +0100763 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100765
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200767 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100769 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200770 _PyUnicode_WSTR_LENGTH(unicode) = length;
771 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100772 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
773 PyObject_DEL(_PyUnicode_WSTR(unicode));
774 _PyUnicode_WSTR(unicode) = NULL;
775 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200776#ifdef Py_DEBUG
777 unicode_fill_invalid(unicode, old_length);
778#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200779 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
780 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200781 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200782 return unicode;
783}
784
Alexander Belopolsky40018472011-02-26 01:02:56 +0000785static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200786resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000787{
Victor Stinner95663112011-10-04 01:03:50 +0200788 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100789 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200790 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200791 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000792
Victor Stinnerfe226c02011-10-03 03:52:20 +0200793 if (PyUnicode_IS_READY(unicode)) {
794 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200795 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200796 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200797#ifdef Py_DEBUG
798 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
799#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200800
801 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200802 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200803 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
804 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200805
806 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
807 PyErr_NoMemory();
808 return -1;
809 }
810 new_size = (length + 1) * char_size;
811
Victor Stinner7a9105a2011-12-12 00:13:42 +0100812 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
813 {
814 PyObject_DEL(_PyUnicode_UTF8(unicode));
815 _PyUnicode_UTF8(unicode) = NULL;
816 _PyUnicode_UTF8_LENGTH(unicode) = 0;
817 }
818
Victor Stinnerfe226c02011-10-03 03:52:20 +0200819 data = (PyObject *)PyObject_REALLOC(data, new_size);
820 if (data == NULL) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200825 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200826 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200827 _PyUnicode_WSTR_LENGTH(unicode) = length;
828 }
829 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200830 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200831 _PyUnicode_UTF8_LENGTH(unicode) = length;
832 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200833 _PyUnicode_LENGTH(unicode) = length;
834 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200835#ifdef Py_DEBUG
836 unicode_fill_invalid(unicode, old_length);
837#endif
Victor Stinner95663112011-10-04 01:03:50 +0200838 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200839 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200840 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200841 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842 }
Victor Stinner95663112011-10-04 01:03:50 +0200843 assert(_PyUnicode_WSTR(unicode) != NULL);
844
845 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700846 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200847 PyErr_NoMemory();
848 return -1;
849 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100850 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200851 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100852 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200853 if (!wstr) {
854 PyErr_NoMemory();
855 return -1;
856 }
857 _PyUnicode_WSTR(unicode) = wstr;
858 _PyUnicode_WSTR(unicode)[length] = 0;
859 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200860 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000861 return 0;
862}
863
Victor Stinnerfe226c02011-10-03 03:52:20 +0200864static PyObject*
865resize_copy(PyObject *unicode, Py_ssize_t length)
866{
867 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100868 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200869 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100870
Benjamin Petersonbac79492012-01-14 13:34:47 -0500871 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100872 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200873
874 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
875 if (copy == NULL)
876 return NULL;
877
878 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200879 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200880 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200881 }
882 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200883 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100884
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200885 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200886 if (w == NULL)
887 return NULL;
888 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
889 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200890 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
891 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200892 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200893 }
894}
895
Guido van Rossumd57fd912000-03-10 22:53:23 +0000896/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000897 Ux0000 terminated; some code (e.g. new_identifier)
898 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000899
900 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000901 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000902
903*/
904
Alexander Belopolsky40018472011-02-26 01:02:56 +0000905static PyUnicodeObject *
906_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000907{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200908 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200909 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000910
Thomas Wouters477c8d52006-05-27 19:21:47 +0000911 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000912 if (length == 0 && unicode_empty != NULL) {
913 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200914 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000915 }
916
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000917 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700918 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000919 return (PyUnicodeObject *)PyErr_NoMemory();
920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200921 if (length < 0) {
922 PyErr_SetString(PyExc_SystemError,
923 "Negative size passed to _PyUnicode_New");
924 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000925 }
926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
928 if (unicode == NULL)
929 return NULL;
930 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100931
932 _PyUnicode_WSTR_LENGTH(unicode) = length;
933 _PyUnicode_HASH(unicode) = -1;
934 _PyUnicode_STATE(unicode).interned = 0;
935 _PyUnicode_STATE(unicode).kind = 0;
936 _PyUnicode_STATE(unicode).compact = 0;
937 _PyUnicode_STATE(unicode).ready = 0;
938 _PyUnicode_STATE(unicode).ascii = 0;
939 _PyUnicode_DATA_ANY(unicode) = NULL;
940 _PyUnicode_LENGTH(unicode) = 0;
941 _PyUnicode_UTF8(unicode) = NULL;
942 _PyUnicode_UTF8_LENGTH(unicode) = 0;
943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200944 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
945 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100946 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000947 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100948 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200950
Jeremy Hyltond8082792003-09-16 19:41:39 +0000951 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000952 * the caller fails before initializing str -- unicode_resize()
953 * reads str[0], and the Keep-Alive optimization can keep memory
954 * allocated for str alive across a call to unicode_dealloc(unicode).
955 * We don't want unicode_resize to read uninitialized memory in
956 * that case.
957 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 _PyUnicode_WSTR(unicode)[0] = 0;
959 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100960
Victor Stinner7931d9a2011-11-04 00:22:48 +0100961 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000962 return unicode;
963}
964
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965static const char*
966unicode_kind_name(PyObject *unicode)
967{
Victor Stinner42dfd712011-10-03 14:41:45 +0200968 /* don't check consistency: unicode_kind_name() is called from
969 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200970 if (!PyUnicode_IS_COMPACT(unicode))
971 {
972 if (!PyUnicode_IS_READY(unicode))
973 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600974 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200975 {
976 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200977 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200978 return "legacy ascii";
979 else
980 return "legacy latin1";
981 case PyUnicode_2BYTE_KIND:
982 return "legacy UCS2";
983 case PyUnicode_4BYTE_KIND:
984 return "legacy UCS4";
985 default:
986 return "<legacy invalid kind>";
987 }
988 }
989 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600990 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200991 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200992 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200993 return "ascii";
994 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200995 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200996 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200997 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200998 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200999 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001000 default:
1001 return "<invalid compact kind>";
1002 }
1003}
1004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001005#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006/* Functions wrapping macros for use in debugger */
1007char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001008 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001009}
1010
1011void *_PyUnicode_compact_data(void *unicode) {
1012 return _PyUnicode_COMPACT_DATA(unicode);
1013}
1014void *_PyUnicode_data(void *unicode){
1015 printf("obj %p\n", unicode);
1016 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1017 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1018 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1019 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1020 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1021 return PyUnicode_DATA(unicode);
1022}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001023
1024void
1025_PyUnicode_Dump(PyObject *op)
1026{
1027 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001028 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1029 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1030 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001031
Victor Stinnera849a4b2011-10-03 12:12:11 +02001032 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001033 {
1034 if (ascii->state.ascii)
1035 data = (ascii + 1);
1036 else
1037 data = (compact + 1);
1038 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001039 else
1040 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001041 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1042 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001043
Victor Stinnera849a4b2011-10-03 12:12:11 +02001044 if (ascii->wstr == data)
1045 printf("shared ");
1046 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001047
Victor Stinnera3b334d2011-10-03 13:53:37 +02001048 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001049 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001050 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1051 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001052 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1053 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001054 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001055 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001056}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057#endif
1058
1059PyObject *
1060PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1061{
1062 PyObject *obj;
1063 PyCompactUnicodeObject *unicode;
1064 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001065 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001066 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001067 Py_ssize_t char_size;
1068 Py_ssize_t struct_size;
1069
1070 /* Optimization for empty strings */
1071 if (size == 0 && unicode_empty != NULL) {
1072 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001073 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074 }
1075
Victor Stinner9e9d6892011-10-04 01:02:02 +02001076 is_ascii = 0;
1077 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001078 struct_size = sizeof(PyCompactUnicodeObject);
1079 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001080 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 char_size = 1;
1082 is_ascii = 1;
1083 struct_size = sizeof(PyASCIIObject);
1084 }
1085 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001086 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 char_size = 1;
1088 }
1089 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001090 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091 char_size = 2;
1092 if (sizeof(wchar_t) == 2)
1093 is_sharing = 1;
1094 }
1095 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001096 if (maxchar > MAX_UNICODE) {
1097 PyErr_SetString(PyExc_SystemError,
1098 "invalid maximum character passed to PyUnicode_New");
1099 return NULL;
1100 }
Victor Stinner8f825062012-04-27 13:55:39 +02001101 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001102 char_size = 4;
1103 if (sizeof(wchar_t) == 4)
1104 is_sharing = 1;
1105 }
1106
1107 /* Ensure we won't overflow the size. */
1108 if (size < 0) {
1109 PyErr_SetString(PyExc_SystemError,
1110 "Negative size passed to PyUnicode_New");
1111 return NULL;
1112 }
1113 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1114 return PyErr_NoMemory();
1115
1116 /* Duplicated allocation code from _PyObject_New() instead of a call to
1117 * PyObject_New() so we are able to allocate space for the object and
1118 * it's data buffer.
1119 */
1120 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1121 if (obj == NULL)
1122 return PyErr_NoMemory();
1123 obj = PyObject_INIT(obj, &PyUnicode_Type);
1124 if (obj == NULL)
1125 return NULL;
1126
1127 unicode = (PyCompactUnicodeObject *)obj;
1128 if (is_ascii)
1129 data = ((PyASCIIObject*)obj) + 1;
1130 else
1131 data = unicode + 1;
1132 _PyUnicode_LENGTH(unicode) = size;
1133 _PyUnicode_HASH(unicode) = -1;
1134 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001135 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001136 _PyUnicode_STATE(unicode).compact = 1;
1137 _PyUnicode_STATE(unicode).ready = 1;
1138 _PyUnicode_STATE(unicode).ascii = is_ascii;
1139 if (is_ascii) {
1140 ((char*)data)[size] = 0;
1141 _PyUnicode_WSTR(unicode) = NULL;
1142 }
Victor Stinner8f825062012-04-27 13:55:39 +02001143 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001144 ((char*)data)[size] = 0;
1145 _PyUnicode_WSTR(unicode) = NULL;
1146 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001148 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001149 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150 else {
1151 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001152 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001153 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001154 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001155 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156 ((Py_UCS4*)data)[size] = 0;
1157 if (is_sharing) {
1158 _PyUnicode_WSTR_LENGTH(unicode) = size;
1159 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1160 }
1161 else {
1162 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1163 _PyUnicode_WSTR(unicode) = NULL;
1164 }
1165 }
Victor Stinner8f825062012-04-27 13:55:39 +02001166#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001167 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001168#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001169 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170 return obj;
1171}
1172
1173#if SIZEOF_WCHAR_T == 2
1174/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1175 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001176 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001177
1178 This function assumes that unicode can hold one more code point than wstr
1179 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001180static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001181unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001182 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001183{
1184 const wchar_t *iter;
1185 Py_UCS4 *ucs4_out;
1186
Victor Stinner910337b2011-10-03 03:20:16 +02001187 assert(unicode != NULL);
1188 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001189 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1190 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1191
1192 for (iter = begin; iter < end; ) {
1193 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1194 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001195 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1196 && (iter+1) < end
1197 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198 {
Victor Stinner551ac952011-11-29 22:58:13 +01001199 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200 iter += 2;
1201 }
1202 else {
1203 *ucs4_out++ = *iter;
1204 iter++;
1205 }
1206 }
1207 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1208 _PyUnicode_GET_LENGTH(unicode)));
1209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210}
1211#endif
1212
Victor Stinnercd9950f2011-10-02 00:34:53 +02001213static int
Victor Stinner488fa492011-12-12 00:01:39 +01001214unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001215{
Victor Stinner488fa492011-12-12 00:01:39 +01001216 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001217 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001218 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001219 return -1;
1220 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001221 return 0;
1222}
1223
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001224static int
1225_copy_characters(PyObject *to, Py_ssize_t to_start,
1226 PyObject *from, Py_ssize_t from_start,
1227 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001229 unsigned int from_kind, to_kind;
1230 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231
Victor Stinneree4544c2012-05-09 22:24:08 +02001232 assert(0 <= how_many);
1233 assert(0 <= from_start);
1234 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001235 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001236 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001237 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238
Victor Stinnerd3f08822012-05-29 12:57:52 +02001239 assert(PyUnicode_Check(to));
1240 assert(PyUnicode_IS_READY(to));
1241 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1242
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001243 if (how_many == 0)
1244 return 0;
1245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001246 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001247 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001249 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001250
Victor Stinnerf1852262012-06-16 16:38:26 +02001251#ifdef Py_DEBUG
1252 if (!check_maxchar
1253 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1254 {
1255 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1256 Py_UCS4 ch;
1257 Py_ssize_t i;
1258 for (i=0; i < how_many; i++) {
1259 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1260 assert(ch <= to_maxchar);
1261 }
1262 }
1263#endif
1264
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001265 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001266 if (check_maxchar
1267 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1268 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001269 /* Writing Latin-1 characters into an ASCII string requires to
1270 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001271 Py_UCS4 max_char;
1272 max_char = ucs1lib_find_max_char(from_data,
1273 (Py_UCS1*)from_data + how_many);
1274 if (max_char >= 128)
1275 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001276 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001277 Py_MEMCPY((char*)to_data + to_kind * to_start,
1278 (char*)from_data + from_kind * from_start,
1279 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001280 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001281 else if (from_kind == PyUnicode_1BYTE_KIND
1282 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001283 {
1284 _PyUnicode_CONVERT_BYTES(
1285 Py_UCS1, Py_UCS2,
1286 PyUnicode_1BYTE_DATA(from) + from_start,
1287 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1288 PyUnicode_2BYTE_DATA(to) + to_start
1289 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001290 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001291 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001292 && to_kind == PyUnicode_4BYTE_KIND)
1293 {
1294 _PyUnicode_CONVERT_BYTES(
1295 Py_UCS1, Py_UCS4,
1296 PyUnicode_1BYTE_DATA(from) + from_start,
1297 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1298 PyUnicode_4BYTE_DATA(to) + to_start
1299 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001300 }
1301 else if (from_kind == PyUnicode_2BYTE_KIND
1302 && to_kind == PyUnicode_4BYTE_KIND)
1303 {
1304 _PyUnicode_CONVERT_BYTES(
1305 Py_UCS2, Py_UCS4,
1306 PyUnicode_2BYTE_DATA(from) + from_start,
1307 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1308 PyUnicode_4BYTE_DATA(to) + to_start
1309 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001310 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001311 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001312 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1313
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001314 if (!check_maxchar) {
1315 if (from_kind == PyUnicode_2BYTE_KIND
1316 && to_kind == PyUnicode_1BYTE_KIND)
1317 {
1318 _PyUnicode_CONVERT_BYTES(
1319 Py_UCS2, Py_UCS1,
1320 PyUnicode_2BYTE_DATA(from) + from_start,
1321 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1322 PyUnicode_1BYTE_DATA(to) + to_start
1323 );
1324 }
1325 else if (from_kind == PyUnicode_4BYTE_KIND
1326 && to_kind == PyUnicode_1BYTE_KIND)
1327 {
1328 _PyUnicode_CONVERT_BYTES(
1329 Py_UCS4, Py_UCS1,
1330 PyUnicode_4BYTE_DATA(from) + from_start,
1331 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1332 PyUnicode_1BYTE_DATA(to) + to_start
1333 );
1334 }
1335 else if (from_kind == PyUnicode_4BYTE_KIND
1336 && to_kind == PyUnicode_2BYTE_KIND)
1337 {
1338 _PyUnicode_CONVERT_BYTES(
1339 Py_UCS4, Py_UCS2,
1340 PyUnicode_4BYTE_DATA(from) + from_start,
1341 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1342 PyUnicode_2BYTE_DATA(to) + to_start
1343 );
1344 }
1345 else {
1346 assert(0);
1347 return -1;
1348 }
1349 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001350 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001351 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001352 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001353 Py_ssize_t i;
1354
Victor Stinnera0702ab2011-09-29 14:14:38 +02001355 for (i=0; i < how_many; i++) {
1356 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001357 if (ch > to_maxchar)
1358 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001359 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1360 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001361 }
1362 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001363 return 0;
1364}
1365
Victor Stinnerd3f08822012-05-29 12:57:52 +02001366void
1367_PyUnicode_FastCopyCharacters(
1368 PyObject *to, Py_ssize_t to_start,
1369 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001370{
1371 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1372}
1373
1374Py_ssize_t
1375PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1376 PyObject *from, Py_ssize_t from_start,
1377 Py_ssize_t how_many)
1378{
1379 int err;
1380
1381 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1382 PyErr_BadInternalCall();
1383 return -1;
1384 }
1385
Benjamin Petersonbac79492012-01-14 13:34:47 -05001386 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001387 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001388 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001389 return -1;
1390
Victor Stinnerd3f08822012-05-29 12:57:52 +02001391 if (from_start < 0) {
1392 PyErr_SetString(PyExc_IndexError, "string index out of range");
1393 return -1;
1394 }
1395 if (to_start < 0) {
1396 PyErr_SetString(PyExc_IndexError, "string index out of range");
1397 return -1;
1398 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001399 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1400 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1401 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001402 "Cannot write %zi characters at %zi "
1403 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001404 how_many, to_start, PyUnicode_GET_LENGTH(to));
1405 return -1;
1406 }
1407
1408 if (how_many == 0)
1409 return 0;
1410
Victor Stinner488fa492011-12-12 00:01:39 +01001411 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001412 return -1;
1413
1414 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1415 if (err) {
1416 PyErr_Format(PyExc_SystemError,
1417 "Cannot copy %s characters "
1418 "into a string of %s characters",
1419 unicode_kind_name(from),
1420 unicode_kind_name(to));
1421 return -1;
1422 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001423 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424}
1425
Victor Stinner17222162011-09-28 22:15:37 +02001426/* Find the maximum code point and count the number of surrogate pairs so a
1427 correct string length can be computed before converting a string to UCS4.
1428 This function counts single surrogates as a character and not as a pair.
1429
1430 Return 0 on success, or -1 on error. */
1431static int
1432find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1433 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001434{
1435 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001436 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437
Victor Stinnerc53be962011-10-02 21:33:54 +02001438 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439 *num_surrogates = 0;
1440 *maxchar = 0;
1441
1442 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001444 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1445 && (iter+1) < end
1446 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1447 {
1448 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1449 ++(*num_surrogates);
1450 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001451 }
1452 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001454 {
1455 ch = *iter;
1456 iter++;
1457 }
1458 if (ch > *maxchar) {
1459 *maxchar = ch;
1460 if (*maxchar > MAX_UNICODE) {
1461 PyErr_Format(PyExc_ValueError,
1462 "character U+%x is not in range [U+0000; U+10ffff]",
1463 ch);
1464 return -1;
1465 }
1466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001467 }
1468 return 0;
1469}
1470
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001471int
1472_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473{
1474 wchar_t *end;
1475 Py_UCS4 maxchar = 0;
1476 Py_ssize_t num_surrogates;
1477#if SIZEOF_WCHAR_T == 2
1478 Py_ssize_t length_wo_surrogates;
1479#endif
1480
Georg Brandl7597add2011-10-05 16:36:47 +02001481 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001482 strings were created using _PyObject_New() and where no canonical
1483 representation (the str field) has been set yet aka strings
1484 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001485 assert(_PyUnicode_CHECK(unicode));
1486 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001488 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001489 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001490 /* Actually, it should neither be interned nor be anything else: */
1491 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001493 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001494 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001495 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001497
1498 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001499 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1500 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001501 PyErr_NoMemory();
1502 return -1;
1503 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001504 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505 _PyUnicode_WSTR(unicode), end,
1506 PyUnicode_1BYTE_DATA(unicode));
1507 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1508 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1509 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1510 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001511 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001512 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001513 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001514 }
1515 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001516 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001517 _PyUnicode_UTF8(unicode) = NULL;
1518 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001519 }
1520 PyObject_FREE(_PyUnicode_WSTR(unicode));
1521 _PyUnicode_WSTR(unicode) = NULL;
1522 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1523 }
1524 /* In this case we might have to convert down from 4-byte native
1525 wchar_t to 2-byte unicode. */
1526 else if (maxchar < 65536) {
1527 assert(num_surrogates == 0 &&
1528 "FindMaxCharAndNumSurrogatePairs() messed up");
1529
Victor Stinner506f5922011-09-28 22:34:18 +02001530#if SIZEOF_WCHAR_T == 2
1531 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001532 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001533 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1534 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1535 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001536 _PyUnicode_UTF8(unicode) = NULL;
1537 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001538#else
1539 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001540 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001541 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001542 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001543 PyErr_NoMemory();
1544 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001545 }
Victor Stinner506f5922011-09-28 22:34:18 +02001546 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1547 _PyUnicode_WSTR(unicode), end,
1548 PyUnicode_2BYTE_DATA(unicode));
1549 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1550 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1551 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001552 _PyUnicode_UTF8(unicode) = NULL;
1553 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001554 PyObject_FREE(_PyUnicode_WSTR(unicode));
1555 _PyUnicode_WSTR(unicode) = NULL;
1556 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1557#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001558 }
1559 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1560 else {
1561#if SIZEOF_WCHAR_T == 2
1562 /* in case the native representation is 2-bytes, we need to allocate a
1563 new normalized 4-byte version. */
1564 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001565 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1566 PyErr_NoMemory();
1567 return -1;
1568 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001569 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1570 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001571 PyErr_NoMemory();
1572 return -1;
1573 }
1574 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1575 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001576 _PyUnicode_UTF8(unicode) = NULL;
1577 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001578 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1579 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001580 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001581 PyObject_FREE(_PyUnicode_WSTR(unicode));
1582 _PyUnicode_WSTR(unicode) = NULL;
1583 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1584#else
1585 assert(num_surrogates == 0);
1586
Victor Stinnerc3c74152011-10-02 20:39:55 +02001587 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001589 _PyUnicode_UTF8(unicode) = NULL;
1590 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001591 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1592#endif
1593 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1594 }
1595 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001596 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597 return 0;
1598}
1599
Alexander Belopolsky40018472011-02-26 01:02:56 +00001600static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001601unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001602{
Walter Dörwald16807132007-05-25 13:52:07 +00001603 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001604 case SSTATE_NOT_INTERNED:
1605 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001606
Benjamin Peterson29060642009-01-31 22:14:21 +00001607 case SSTATE_INTERNED_MORTAL:
1608 /* revive dead object temporarily for DelItem */
1609 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001610 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001611 Py_FatalError(
1612 "deletion of interned string failed");
1613 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001614
Benjamin Peterson29060642009-01-31 22:14:21 +00001615 case SSTATE_INTERNED_IMMORTAL:
1616 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001617
Benjamin Peterson29060642009-01-31 22:14:21 +00001618 default:
1619 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001620 }
1621
Victor Stinner03490912011-10-03 23:45:12 +02001622 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001624 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001625 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001626 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1627 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001629 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001630}
1631
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001632#ifdef Py_DEBUG
1633static int
1634unicode_is_singleton(PyObject *unicode)
1635{
1636 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1637 if (unicode == unicode_empty)
1638 return 1;
1639 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1640 {
1641 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1642 if (ch < 256 && unicode_latin1[ch] == unicode)
1643 return 1;
1644 }
1645 return 0;
1646}
1647#endif
1648
Alexander Belopolsky40018472011-02-26 01:02:56 +00001649static int
Victor Stinner488fa492011-12-12 00:01:39 +01001650unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001651{
Victor Stinner488fa492011-12-12 00:01:39 +01001652 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001653 if (Py_REFCNT(unicode) != 1)
1654 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001655 if (_PyUnicode_HASH(unicode) != -1)
1656 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001657 if (PyUnicode_CHECK_INTERNED(unicode))
1658 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001659 if (!PyUnicode_CheckExact(unicode))
1660 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001661#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001662 /* singleton refcount is greater than 1 */
1663 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001664#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001665 return 1;
1666}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001667
Victor Stinnerfe226c02011-10-03 03:52:20 +02001668static int
1669unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1670{
1671 PyObject *unicode;
1672 Py_ssize_t old_length;
1673
1674 assert(p_unicode != NULL);
1675 unicode = *p_unicode;
1676
1677 assert(unicode != NULL);
1678 assert(PyUnicode_Check(unicode));
1679 assert(0 <= length);
1680
Victor Stinner910337b2011-10-03 03:20:16 +02001681 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001682 old_length = PyUnicode_WSTR_LENGTH(unicode);
1683 else
1684 old_length = PyUnicode_GET_LENGTH(unicode);
1685 if (old_length == length)
1686 return 0;
1687
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001688 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001689 _Py_INCREF_UNICODE_EMPTY();
1690 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001691 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001692 Py_DECREF(*p_unicode);
1693 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001694 return 0;
1695 }
1696
Victor Stinner488fa492011-12-12 00:01:39 +01001697 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001698 PyObject *copy = resize_copy(unicode, length);
1699 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001700 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001701 Py_DECREF(*p_unicode);
1702 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001703 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001704 }
1705
Victor Stinnerfe226c02011-10-03 03:52:20 +02001706 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001707 PyObject *new_unicode = resize_compact(unicode, length);
1708 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001709 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001710 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001711 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001712 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001713 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001714}
1715
Alexander Belopolsky40018472011-02-26 01:02:56 +00001716int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001717PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001718{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001719 PyObject *unicode;
1720 if (p_unicode == NULL) {
1721 PyErr_BadInternalCall();
1722 return -1;
1723 }
1724 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001725 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001726 {
1727 PyErr_BadInternalCall();
1728 return -1;
1729 }
1730 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001731}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001732
Victor Stinnerc5166102012-02-22 13:55:02 +01001733/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001734
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001735 WARNING: The function doesn't copy the terminating null character and
1736 doesn't check the maximum character (may write a latin1 character in an
1737 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001738static void
1739unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1740 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001741{
1742 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1743 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001744 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001745
1746 switch (kind) {
1747 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001748 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001749#ifdef Py_DEBUG
1750 if (PyUnicode_IS_ASCII(unicode)) {
1751 Py_UCS4 maxchar = ucs1lib_find_max_char(
1752 (const Py_UCS1*)str,
1753 (const Py_UCS1*)str + len);
1754 assert(maxchar < 128);
1755 }
1756#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001757 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001758 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001759 }
1760 case PyUnicode_2BYTE_KIND: {
1761 Py_UCS2 *start = (Py_UCS2 *)data + index;
1762 Py_UCS2 *ucs2 = start;
1763 assert(index <= PyUnicode_GET_LENGTH(unicode));
1764
Victor Stinner184252a2012-06-16 02:57:41 +02001765 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001766 *ucs2 = (Py_UCS2)*str;
1767
1768 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001769 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001770 }
1771 default: {
1772 Py_UCS4 *start = (Py_UCS4 *)data + index;
1773 Py_UCS4 *ucs4 = start;
1774 assert(kind == PyUnicode_4BYTE_KIND);
1775 assert(index <= PyUnicode_GET_LENGTH(unicode));
1776
Victor Stinner184252a2012-06-16 02:57:41 +02001777 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001778 *ucs4 = (Py_UCS4)*str;
1779
1780 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001781 }
1782 }
1783}
1784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001785static PyObject*
1786get_latin1_char(unsigned char ch)
1787{
Victor Stinnera464fc12011-10-02 20:39:30 +02001788 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001789 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001790 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 if (!unicode)
1792 return NULL;
1793 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001794 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001795 unicode_latin1[ch] = unicode;
1796 }
1797 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001798 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001799}
1800
Victor Stinner985a82a2014-01-03 12:53:47 +01001801static PyObject*
1802unicode_char(Py_UCS4 ch)
1803{
1804 PyObject *unicode;
1805
1806 assert(ch <= MAX_UNICODE);
1807
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001808 if (ch < 256)
1809 return get_latin1_char(ch);
1810
Victor Stinner985a82a2014-01-03 12:53:47 +01001811 unicode = PyUnicode_New(1, ch);
1812 if (unicode == NULL)
1813 return NULL;
1814 switch (PyUnicode_KIND(unicode)) {
1815 case PyUnicode_1BYTE_KIND:
1816 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1817 break;
1818 case PyUnicode_2BYTE_KIND:
1819 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1820 break;
1821 default:
1822 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1823 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1824 }
1825 assert(_PyUnicode_CheckConsistency(unicode, 1));
1826 return unicode;
1827}
1828
Alexander Belopolsky40018472011-02-26 01:02:56 +00001829PyObject *
1830PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001831{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001832 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 Py_UCS4 maxchar = 0;
1834 Py_ssize_t num_surrogates;
1835
1836 if (u == NULL)
1837 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001838
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001839 /* If the Unicode data is known at construction time, we can apply
1840 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001841
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001842 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001843 if (size == 0)
1844 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001846 /* Single character Unicode objects in the Latin-1 range are
1847 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001848 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 return get_latin1_char((unsigned char)*u);
1850
1851 /* If not empty and not single character, copy the Unicode data
1852 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001853 if (find_maxchar_surrogates(u, u + size,
1854 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001855 return NULL;
1856
Victor Stinner8faf8212011-12-08 22:14:11 +01001857 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001858 if (!unicode)
1859 return NULL;
1860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001861 switch (PyUnicode_KIND(unicode)) {
1862 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001863 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001864 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1865 break;
1866 case PyUnicode_2BYTE_KIND:
1867#if Py_UNICODE_SIZE == 2
1868 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1869#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001870 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001871 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1872#endif
1873 break;
1874 case PyUnicode_4BYTE_KIND:
1875#if SIZEOF_WCHAR_T == 2
1876 /* This is the only case which has to process surrogates, thus
1877 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001878 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001879#else
1880 assert(num_surrogates == 0);
1881 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1882#endif
1883 break;
1884 default:
1885 assert(0 && "Impossible state");
1886 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001887
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001888 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001889}
1890
Alexander Belopolsky40018472011-02-26 01:02:56 +00001891PyObject *
1892PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001893{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001894 if (size < 0) {
1895 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001896 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001897 return NULL;
1898 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001899 if (u != NULL)
1900 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1901 else
1902 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001903}
1904
Alexander Belopolsky40018472011-02-26 01:02:56 +00001905PyObject *
1906PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001907{
1908 size_t size = strlen(u);
1909 if (size > PY_SSIZE_T_MAX) {
1910 PyErr_SetString(PyExc_OverflowError, "input too long");
1911 return NULL;
1912 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001913 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001914}
1915
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001916PyObject *
1917_PyUnicode_FromId(_Py_Identifier *id)
1918{
1919 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001920 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1921 strlen(id->string),
1922 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001923 if (!id->object)
1924 return NULL;
1925 PyUnicode_InternInPlace(&id->object);
1926 assert(!id->next);
1927 id->next = static_strings;
1928 static_strings = id;
1929 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001930 return id->object;
1931}
1932
1933void
1934_PyUnicode_ClearStaticStrings()
1935{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001936 _Py_Identifier *tmp, *s = static_strings;
1937 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001938 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001939 tmp = s->next;
1940 s->next = NULL;
1941 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001942 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001943 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001944}
1945
Benjamin Peterson0df54292012-03-26 14:50:32 -04001946/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001947
Victor Stinnerd3f08822012-05-29 12:57:52 +02001948PyObject*
1949_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001950{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001951 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001952 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001953 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001954#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001955 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001956#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001957 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001958 }
Victor Stinner785938e2011-12-11 20:09:03 +01001959 unicode = PyUnicode_New(size, 127);
1960 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001961 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001962 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1963 assert(_PyUnicode_CheckConsistency(unicode, 1));
1964 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001965}
1966
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001967static Py_UCS4
1968kind_maxchar_limit(unsigned int kind)
1969{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001970 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001971 case PyUnicode_1BYTE_KIND:
1972 return 0x80;
1973 case PyUnicode_2BYTE_KIND:
1974 return 0x100;
1975 case PyUnicode_4BYTE_KIND:
1976 return 0x10000;
1977 default:
1978 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001979 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001980 }
1981}
1982
Victor Stinnere6abb482012-05-02 01:15:40 +02001983Py_LOCAL_INLINE(Py_UCS4)
1984align_maxchar(Py_UCS4 maxchar)
1985{
1986 if (maxchar <= 127)
1987 return 127;
1988 else if (maxchar <= 255)
1989 return 255;
1990 else if (maxchar <= 65535)
1991 return 65535;
1992 else
1993 return MAX_UNICODE;
1994}
1995
Victor Stinner702c7342011-10-05 13:50:52 +02001996static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001997_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001998{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002000 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002001
Serhiy Storchaka678db842013-01-26 12:16:36 +02002002 if (size == 0)
2003 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002004 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002005 if (size == 1)
2006 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002007
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002008 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002009 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 if (!res)
2011 return NULL;
2012 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002013 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002015}
2016
Victor Stinnere57b1c02011-09-28 22:20:48 +02002017static PyObject*
2018_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019{
2020 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002021 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002022
Serhiy Storchaka678db842013-01-26 12:16:36 +02002023 if (size == 0)
2024 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002025 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002026 if (size == 1)
2027 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002028
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002029 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002030 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002031 if (!res)
2032 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002033 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002035 else {
2036 _PyUnicode_CONVERT_BYTES(
2037 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2038 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002039 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 return res;
2041}
2042
Victor Stinnere57b1c02011-09-28 22:20:48 +02002043static PyObject*
2044_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002045{
2046 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002047 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002048
Serhiy Storchaka678db842013-01-26 12:16:36 +02002049 if (size == 0)
2050 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002051 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002052 if (size == 1)
2053 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002054
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002055 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002056 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 if (!res)
2058 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002059 if (max_char < 256)
2060 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2061 PyUnicode_1BYTE_DATA(res));
2062 else if (max_char < 0x10000)
2063 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2064 PyUnicode_2BYTE_DATA(res));
2065 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002067 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002068 return res;
2069}
2070
2071PyObject*
2072PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2073{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002074 if (size < 0) {
2075 PyErr_SetString(PyExc_ValueError, "size must be positive");
2076 return NULL;
2077 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002078 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002079 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002080 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002082 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002083 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002084 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002085 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002086 PyErr_SetString(PyExc_SystemError, "invalid kind");
2087 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002089}
2090
Victor Stinnerece58de2012-04-23 23:36:38 +02002091Py_UCS4
2092_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2093{
2094 enum PyUnicode_Kind kind;
2095 void *startptr, *endptr;
2096
2097 assert(PyUnicode_IS_READY(unicode));
2098 assert(0 <= start);
2099 assert(end <= PyUnicode_GET_LENGTH(unicode));
2100 assert(start <= end);
2101
2102 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2103 return PyUnicode_MAX_CHAR_VALUE(unicode);
2104
2105 if (start == end)
2106 return 127;
2107
Victor Stinner94d558b2012-04-27 22:26:58 +02002108 if (PyUnicode_IS_ASCII(unicode))
2109 return 127;
2110
Victor Stinnerece58de2012-04-23 23:36:38 +02002111 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002112 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002113 endptr = (char *)startptr + end * kind;
2114 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002115 switch(kind) {
2116 case PyUnicode_1BYTE_KIND:
2117 return ucs1lib_find_max_char(startptr, endptr);
2118 case PyUnicode_2BYTE_KIND:
2119 return ucs2lib_find_max_char(startptr, endptr);
2120 case PyUnicode_4BYTE_KIND:
2121 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002122 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002123 assert(0);
2124 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002125 }
2126}
2127
Victor Stinner25a4b292011-10-06 12:31:55 +02002128/* Ensure that a string uses the most efficient storage, if it is not the
2129 case: create a new string with of the right kind. Write NULL into *p_unicode
2130 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002131static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002132unicode_adjust_maxchar(PyObject **p_unicode)
2133{
2134 PyObject *unicode, *copy;
2135 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002136 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002137 unsigned int kind;
2138
2139 assert(p_unicode != NULL);
2140 unicode = *p_unicode;
2141 assert(PyUnicode_IS_READY(unicode));
2142 if (PyUnicode_IS_ASCII(unicode))
2143 return;
2144
2145 len = PyUnicode_GET_LENGTH(unicode);
2146 kind = PyUnicode_KIND(unicode);
2147 if (kind == PyUnicode_1BYTE_KIND) {
2148 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002149 max_char = ucs1lib_find_max_char(u, u + len);
2150 if (max_char >= 128)
2151 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002152 }
2153 else if (kind == PyUnicode_2BYTE_KIND) {
2154 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002155 max_char = ucs2lib_find_max_char(u, u + len);
2156 if (max_char >= 256)
2157 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002158 }
2159 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002160 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002161 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002162 max_char = ucs4lib_find_max_char(u, u + len);
2163 if (max_char >= 0x10000)
2164 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002165 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002166 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002167 if (copy != NULL)
2168 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002169 Py_DECREF(unicode);
2170 *p_unicode = copy;
2171}
2172
Victor Stinner034f6cf2011-09-30 02:26:44 +02002173PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002174_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002175{
Victor Stinner87af4f22011-11-21 23:03:47 +01002176 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002177 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002178
Victor Stinner034f6cf2011-09-30 02:26:44 +02002179 if (!PyUnicode_Check(unicode)) {
2180 PyErr_BadInternalCall();
2181 return NULL;
2182 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002183 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002184 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002185
Victor Stinner87af4f22011-11-21 23:03:47 +01002186 length = PyUnicode_GET_LENGTH(unicode);
2187 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002188 if (!copy)
2189 return NULL;
2190 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2191
Victor Stinner87af4f22011-11-21 23:03:47 +01002192 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2193 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002194 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002195 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002196}
2197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199/* Widen Unicode objects to larger buffers. Don't write terminating null
2200 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201
2202void*
2203_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2204{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002205 Py_ssize_t len;
2206 void *result;
2207 unsigned int skind;
2208
Benjamin Petersonbac79492012-01-14 13:34:47 -05002209 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 return NULL;
2211
2212 len = PyUnicode_GET_LENGTH(s);
2213 skind = PyUnicode_KIND(s);
2214 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002215 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 return NULL;
2217 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002218 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002220 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002221 if (!result)
2222 return PyErr_NoMemory();
2223 assert(skind == PyUnicode_1BYTE_KIND);
2224 _PyUnicode_CONVERT_BYTES(
2225 Py_UCS1, Py_UCS2,
2226 PyUnicode_1BYTE_DATA(s),
2227 PyUnicode_1BYTE_DATA(s) + len,
2228 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002230 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002231 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002232 if (!result)
2233 return PyErr_NoMemory();
2234 if (skind == PyUnicode_2BYTE_KIND) {
2235 _PyUnicode_CONVERT_BYTES(
2236 Py_UCS2, Py_UCS4,
2237 PyUnicode_2BYTE_DATA(s),
2238 PyUnicode_2BYTE_DATA(s) + len,
2239 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002241 else {
2242 assert(skind == PyUnicode_1BYTE_KIND);
2243 _PyUnicode_CONVERT_BYTES(
2244 Py_UCS1, Py_UCS4,
2245 PyUnicode_1BYTE_DATA(s),
2246 PyUnicode_1BYTE_DATA(s) + len,
2247 result);
2248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002249 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002250 default:
2251 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252 }
Victor Stinner01698042011-10-04 00:04:26 +02002253 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002254 return NULL;
2255}
2256
2257static Py_UCS4*
2258as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2259 int copy_null)
2260{
2261 int kind;
2262 void *data;
2263 Py_ssize_t len, targetlen;
2264 if (PyUnicode_READY(string) == -1)
2265 return NULL;
2266 kind = PyUnicode_KIND(string);
2267 data = PyUnicode_DATA(string);
2268 len = PyUnicode_GET_LENGTH(string);
2269 targetlen = len;
2270 if (copy_null)
2271 targetlen++;
2272 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002273 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 if (!target) {
2275 PyErr_NoMemory();
2276 return NULL;
2277 }
2278 }
2279 else {
2280 if (targetsize < targetlen) {
2281 PyErr_Format(PyExc_SystemError,
2282 "string is longer than the buffer");
2283 if (copy_null && 0 < targetsize)
2284 target[0] = 0;
2285 return NULL;
2286 }
2287 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002288 if (kind == PyUnicode_1BYTE_KIND) {
2289 Py_UCS1 *start = (Py_UCS1 *) data;
2290 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002292 else if (kind == PyUnicode_2BYTE_KIND) {
2293 Py_UCS2 *start = (Py_UCS2 *) data;
2294 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2295 }
2296 else {
2297 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002298 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300 if (copy_null)
2301 target[len] = 0;
2302 return target;
2303}
2304
2305Py_UCS4*
2306PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2307 int copy_null)
2308{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002309 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310 PyErr_BadInternalCall();
2311 return NULL;
2312 }
2313 return as_ucs4(string, target, targetsize, copy_null);
2314}
2315
2316Py_UCS4*
2317PyUnicode_AsUCS4Copy(PyObject *string)
2318{
2319 return as_ucs4(string, NULL, 0, 1);
2320}
2321
2322#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002323
Alexander Belopolsky40018472011-02-26 01:02:56 +00002324PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002325PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002326{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002327 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002328 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002329 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002330 PyErr_BadInternalCall();
2331 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002332 }
2333
Martin v. Löwis790465f2008-04-05 20:41:37 +00002334 if (size == -1) {
2335 size = wcslen(w);
2336 }
2337
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002338 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002339}
2340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002341#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002342
Victor Stinner15a11362012-10-06 23:48:20 +02002343/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002344 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2345 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2346#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002347
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002348static int
2349unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2350 Py_ssize_t width, Py_ssize_t precision)
2351{
2352 Py_ssize_t length, fill, arglen;
2353 Py_UCS4 maxchar;
2354
2355 if (PyUnicode_READY(str) == -1)
2356 return -1;
2357
2358 length = PyUnicode_GET_LENGTH(str);
2359 if ((precision == -1 || precision >= length)
2360 && width <= length)
2361 return _PyUnicodeWriter_WriteStr(writer, str);
2362
2363 if (precision != -1)
2364 length = Py_MIN(precision, length);
2365
2366 arglen = Py_MAX(length, width);
2367 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2368 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2369 else
2370 maxchar = writer->maxchar;
2371
2372 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2373 return -1;
2374
2375 if (width > length) {
2376 fill = width - length;
2377 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2378 return -1;
2379 writer->pos += fill;
2380 }
2381
2382 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2383 str, 0, length);
2384 writer->pos += length;
2385 return 0;
2386}
2387
2388static int
2389unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2390 Py_ssize_t width, Py_ssize_t precision)
2391{
2392 /* UTF-8 */
2393 Py_ssize_t length;
2394 PyObject *unicode;
2395 int res;
2396
2397 length = strlen(str);
2398 if (precision != -1)
2399 length = Py_MIN(length, precision);
2400 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2401 if (unicode == NULL)
2402 return -1;
2403
2404 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2405 Py_DECREF(unicode);
2406 return res;
2407}
2408
Victor Stinner96865452011-03-01 23:44:09 +00002409static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002410unicode_fromformat_arg(_PyUnicodeWriter *writer,
2411 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002412{
Victor Stinnere215d962012-10-06 23:03:36 +02002413 const char *p;
2414 Py_ssize_t len;
2415 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002416 Py_ssize_t width;
2417 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002418 int longflag;
2419 int longlongflag;
2420 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002421 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002422
2423 p = f;
2424 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002425 zeropad = 0;
2426 if (*f == '0') {
2427 zeropad = 1;
2428 f++;
2429 }
Victor Stinner96865452011-03-01 23:44:09 +00002430
2431 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002432 width = -1;
2433 if (Py_ISDIGIT((unsigned)*f)) {
2434 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002435 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002436 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002437 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002438 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002440 return NULL;
2441 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002442 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002443 f++;
2444 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002445 }
2446 precision = -1;
2447 if (*f == '.') {
2448 f++;
2449 if (Py_ISDIGIT((unsigned)*f)) {
2450 precision = (*f - '0');
2451 f++;
2452 while (Py_ISDIGIT((unsigned)*f)) {
2453 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2454 PyErr_SetString(PyExc_ValueError,
2455 "precision too big");
2456 return NULL;
2457 }
2458 precision = (precision * 10) + (*f - '0');
2459 f++;
2460 }
2461 }
Victor Stinner96865452011-03-01 23:44:09 +00002462 if (*f == '%') {
2463 /* "%.3%s" => f points to "3" */
2464 f--;
2465 }
2466 }
2467 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002468 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002469 f--;
2470 }
Victor Stinner96865452011-03-01 23:44:09 +00002471
2472 /* Handle %ld, %lu, %lld and %llu. */
2473 longflag = 0;
2474 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002475 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002476 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002477 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002478 longflag = 1;
2479 ++f;
2480 }
2481#ifdef HAVE_LONG_LONG
2482 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002483 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002484 longlongflag = 1;
2485 f += 2;
2486 }
2487#endif
2488 }
2489 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002490 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002491 size_tflag = 1;
2492 ++f;
2493 }
Victor Stinnere215d962012-10-06 23:03:36 +02002494
2495 if (f[1] == '\0')
2496 writer->overallocate = 0;
2497
2498 switch (*f) {
2499 case 'c':
2500 {
2501 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002502 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002503 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002504 "character argument not in range(0x110000)");
2505 return NULL;
2506 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002507 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002508 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002509 break;
2510 }
2511
2512 case 'i':
2513 case 'd':
2514 case 'u':
2515 case 'x':
2516 {
2517 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002518 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002519 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002520
2521 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002522 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002523 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002524 va_arg(*vargs, unsigned long));
2525#ifdef HAVE_LONG_LONG
2526 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002527 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002528 va_arg(*vargs, unsigned PY_LONG_LONG));
2529#endif
2530 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002531 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002532 va_arg(*vargs, size_t));
2533 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002534 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002535 va_arg(*vargs, unsigned int));
2536 }
2537 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002538 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002539 }
2540 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002541 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002542 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002543 va_arg(*vargs, long));
2544#ifdef HAVE_LONG_LONG
2545 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002546 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002547 va_arg(*vargs, PY_LONG_LONG));
2548#endif
2549 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002550 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002551 va_arg(*vargs, Py_ssize_t));
2552 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002553 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002554 va_arg(*vargs, int));
2555 }
2556 assert(len >= 0);
2557
Victor Stinnere215d962012-10-06 23:03:36 +02002558 if (precision < len)
2559 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002560
2561 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002562 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2563 return NULL;
2564
Victor Stinnere215d962012-10-06 23:03:36 +02002565 if (width > precision) {
2566 Py_UCS4 fillchar;
2567 fill = width - precision;
2568 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002569 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2570 return NULL;
2571 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002572 }
Victor Stinner15a11362012-10-06 23:48:20 +02002573 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002574 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002575 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2576 return NULL;
2577 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002578 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579
Victor Stinner4a587072013-11-19 12:54:53 +01002580 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2581 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002582 break;
2583 }
2584
2585 case 'p':
2586 {
2587 char number[MAX_LONG_LONG_CHARS];
2588
2589 len = sprintf(number, "%p", va_arg(*vargs, void*));
2590 assert(len >= 0);
2591
2592 /* %p is ill-defined: ensure leading 0x. */
2593 if (number[1] == 'X')
2594 number[1] = 'x';
2595 else if (number[1] != 'x') {
2596 memmove(number + 2, number,
2597 strlen(number) + 1);
2598 number[0] = '0';
2599 number[1] = 'x';
2600 len += 2;
2601 }
2602
Victor Stinner4a587072013-11-19 12:54:53 +01002603 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002604 return NULL;
2605 break;
2606 }
2607
2608 case 's':
2609 {
2610 /* UTF-8 */
2611 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002612 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002613 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002614 break;
2615 }
2616
2617 case 'U':
2618 {
2619 PyObject *obj = va_arg(*vargs, PyObject *);
2620 assert(obj && _PyUnicode_CHECK(obj));
2621
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002622 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002623 return NULL;
2624 break;
2625 }
2626
2627 case 'V':
2628 {
2629 PyObject *obj = va_arg(*vargs, PyObject *);
2630 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002631 if (obj) {
2632 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002633 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002634 return NULL;
2635 }
2636 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002637 assert(str != NULL);
2638 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002639 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002640 }
2641 break;
2642 }
2643
2644 case 'S':
2645 {
2646 PyObject *obj = va_arg(*vargs, PyObject *);
2647 PyObject *str;
2648 assert(obj);
2649 str = PyObject_Str(obj);
2650 if (!str)
2651 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002652 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002653 Py_DECREF(str);
2654 return NULL;
2655 }
2656 Py_DECREF(str);
2657 break;
2658 }
2659
2660 case 'R':
2661 {
2662 PyObject *obj = va_arg(*vargs, PyObject *);
2663 PyObject *repr;
2664 assert(obj);
2665 repr = PyObject_Repr(obj);
2666 if (!repr)
2667 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002668 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002669 Py_DECREF(repr);
2670 return NULL;
2671 }
2672 Py_DECREF(repr);
2673 break;
2674 }
2675
2676 case 'A':
2677 {
2678 PyObject *obj = va_arg(*vargs, PyObject *);
2679 PyObject *ascii;
2680 assert(obj);
2681 ascii = PyObject_ASCII(obj);
2682 if (!ascii)
2683 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002684 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002685 Py_DECREF(ascii);
2686 return NULL;
2687 }
2688 Py_DECREF(ascii);
2689 break;
2690 }
2691
2692 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002693 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002694 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002695 break;
2696
2697 default:
2698 /* if we stumble upon an unknown formatting code, copy the rest
2699 of the format string to the output string. (we cannot just
2700 skip the code, since there's no way to know what's in the
2701 argument list) */
2702 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002703 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002704 return NULL;
2705 f = p+len;
2706 return f;
2707 }
2708
2709 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002710 return f;
2711}
2712
Walter Dörwaldd2034312007-05-18 16:29:38 +00002713PyObject *
2714PyUnicode_FromFormatV(const char *format, va_list vargs)
2715{
Victor Stinnere215d962012-10-06 23:03:36 +02002716 va_list vargs2;
2717 const char *f;
2718 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002719
Victor Stinner8f674cc2013-04-17 23:02:17 +02002720 _PyUnicodeWriter_Init(&writer);
2721 writer.min_length = strlen(format) + 100;
2722 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002723
2724 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2725 Copy it to be able to pass a reference to a subfunction. */
2726 Py_VA_COPY(vargs2, vargs);
2727
2728 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002729 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002730 f = unicode_fromformat_arg(&writer, f, &vargs2);
2731 if (f == NULL)
2732 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002733 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002734 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002735 const char *p;
2736 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002737
Victor Stinnere215d962012-10-06 23:03:36 +02002738 p = f;
2739 do
2740 {
2741 if ((unsigned char)*p > 127) {
2742 PyErr_Format(PyExc_ValueError,
2743 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2744 "string, got a non-ASCII byte: 0x%02x",
2745 (unsigned char)*p);
2746 return NULL;
2747 }
2748 p++;
2749 }
2750 while (*p != '\0' && *p != '%');
2751 len = p - f;
2752
2753 if (*p == '\0')
2754 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002755
2756 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002757 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002758
2759 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002760 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 }
Victor Stinnere215d962012-10-06 23:03:36 +02002762 return _PyUnicodeWriter_Finish(&writer);
2763
2764 fail:
2765 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002766 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002767}
2768
Walter Dörwaldd2034312007-05-18 16:29:38 +00002769PyObject *
2770PyUnicode_FromFormat(const char *format, ...)
2771{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002772 PyObject* ret;
2773 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002774
2775#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002776 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002777#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002778 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002779#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 ret = PyUnicode_FromFormatV(format, vargs);
2781 va_end(vargs);
2782 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002783}
2784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002785#ifdef HAVE_WCHAR_H
2786
Victor Stinner5593d8a2010-10-02 11:11:27 +00002787/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2788 convert a Unicode object to a wide character string.
2789
Victor Stinnerd88d9832011-09-06 02:00:05 +02002790 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002791 character) required to convert the unicode object. Ignore size argument.
2792
Victor Stinnerd88d9832011-09-06 02:00:05 +02002793 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002795 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002796static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002797unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002798 wchar_t *w,
2799 Py_ssize_t size)
2800{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002801 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 const wchar_t *wstr;
2803
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002804 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805 if (wstr == NULL)
2806 return -1;
2807
Victor Stinner5593d8a2010-10-02 11:11:27 +00002808 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002809 if (size > res)
2810 size = res + 1;
2811 else
2812 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002814 return res;
2815 }
2816 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002817 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002818}
2819
2820Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002821PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002822 wchar_t *w,
2823 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002824{
2825 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002826 PyErr_BadInternalCall();
2827 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002828 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002829 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002830}
2831
Victor Stinner137c34c2010-09-29 10:25:54 +00002832wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002833PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002834 Py_ssize_t *size)
2835{
2836 wchar_t* buffer;
2837 Py_ssize_t buflen;
2838
2839 if (unicode == NULL) {
2840 PyErr_BadInternalCall();
2841 return NULL;
2842 }
2843
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002844 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 if (buflen == -1)
2846 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002847 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002848 if (buffer == NULL) {
2849 PyErr_NoMemory();
2850 return NULL;
2851 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002852 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002853 if (buflen == -1) {
2854 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002856 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002857 if (size != NULL)
2858 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002859 return buffer;
2860}
2861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002862#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002863
Alexander Belopolsky40018472011-02-26 01:02:56 +00002864PyObject *
2865PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002866{
Victor Stinner8faf8212011-12-08 22:14:11 +01002867 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002868 PyErr_SetString(PyExc_ValueError,
2869 "chr() arg not in range(0x110000)");
2870 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002871 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002872
Victor Stinner985a82a2014-01-03 12:53:47 +01002873 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002874}
2875
Alexander Belopolsky40018472011-02-26 01:02:56 +00002876PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002877PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002878{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002879 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002880 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002881 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002882 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002883 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002884 Py_INCREF(obj);
2885 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002886 }
2887 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 /* For a Unicode subtype that's not a Unicode object,
2889 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002890 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002891 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002892 PyErr_Format(PyExc_TypeError,
2893 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002894 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002895 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002896}
2897
Alexander Belopolsky40018472011-02-26 01:02:56 +00002898PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002899PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002900 const char *encoding,
2901 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002902{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002903 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002904 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002905
Guido van Rossumd57fd912000-03-10 22:53:23 +00002906 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002907 PyErr_BadInternalCall();
2908 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002909 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002910
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002911 /* Decoding bytes objects is the most common case and should be fast */
2912 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002913 if (PyBytes_GET_SIZE(obj) == 0)
2914 _Py_RETURN_UNICODE_EMPTY();
2915 v = PyUnicode_Decode(
2916 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2917 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002918 return v;
2919 }
2920
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002921 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002922 PyErr_SetString(PyExc_TypeError,
2923 "decoding str is not supported");
2924 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002925 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002926
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002927 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2928 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2929 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002930 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002931 Py_TYPE(obj)->tp_name);
2932 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002933 }
Tim Petersced69f82003-09-16 20:30:58 +00002934
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002935 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002936 PyBuffer_Release(&buffer);
2937 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002938 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002939
Serhiy Storchaka05997252013-01-26 12:14:02 +02002940 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002941 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002942 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002943}
2944
Victor Stinner600d3be2010-06-10 12:00:55 +00002945/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002946 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2947 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002948int
2949_Py_normalize_encoding(const char *encoding,
2950 char *lower,
2951 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002953 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002954 char *l;
2955 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002956
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002957 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002958 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002959 if (lower_len < 6)
2960 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002961 strcpy(lower, "utf-8");
2962 return 1;
2963 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002964 e = encoding;
2965 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002966 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002967 while (*e) {
2968 if (l == l_end)
2969 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002970 if (Py_ISUPPER(*e)) {
2971 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002972 }
2973 else if (*e == '_') {
2974 *l++ = '-';
2975 e++;
2976 }
2977 else {
2978 *l++ = *e++;
2979 }
2980 }
2981 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002982 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002983}
2984
Alexander Belopolsky40018472011-02-26 01:02:56 +00002985PyObject *
2986PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002987 Py_ssize_t size,
2988 const char *encoding,
2989 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002990{
2991 PyObject *buffer = NULL, *unicode;
2992 Py_buffer info;
2993 char lower[11]; /* Enough for any encoding shortcut */
2994
Fred Drakee4315f52000-05-09 19:53:39 +00002995 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002996 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002997 if ((strcmp(lower, "utf-8") == 0) ||
2998 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002999 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003000 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003001 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003002 (strcmp(lower, "iso-8859-1") == 0) ||
3003 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003004 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003005#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003006 else if (strcmp(lower, "mbcs") == 0)
3007 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003008#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003009 else if (strcmp(lower, "ascii") == 0)
3010 return PyUnicode_DecodeASCII(s, size, errors);
3011 else if (strcmp(lower, "utf-16") == 0)
3012 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3013 else if (strcmp(lower, "utf-32") == 0)
3014 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3015 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003016
3017 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003018 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003019 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003020 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003021 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003022 if (buffer == NULL)
3023 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003024 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 if (unicode == NULL)
3026 goto onError;
3027 if (!PyUnicode_Check(unicode)) {
3028 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003029 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3030 "use codecs.decode() to decode to arbitrary types",
3031 encoding,
3032 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003033 Py_DECREF(unicode);
3034 goto onError;
3035 }
3036 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003037 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003038
Benjamin Peterson29060642009-01-31 22:14:21 +00003039 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003040 Py_XDECREF(buffer);
3041 return NULL;
3042}
3043
Alexander Belopolsky40018472011-02-26 01:02:56 +00003044PyObject *
3045PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003046 const char *encoding,
3047 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003048{
3049 PyObject *v;
3050
3051 if (!PyUnicode_Check(unicode)) {
3052 PyErr_BadArgument();
3053 goto onError;
3054 }
3055
3056 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003057 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003058
3059 /* Decode via the codec registry */
3060 v = PyCodec_Decode(unicode, encoding, errors);
3061 if (v == NULL)
3062 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003063 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003064
Benjamin Peterson29060642009-01-31 22:14:21 +00003065 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003066 return NULL;
3067}
3068
Alexander Belopolsky40018472011-02-26 01:02:56 +00003069PyObject *
3070PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003071 const char *encoding,
3072 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003073{
3074 PyObject *v;
3075
3076 if (!PyUnicode_Check(unicode)) {
3077 PyErr_BadArgument();
3078 goto onError;
3079 }
3080
3081 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003082 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003083
3084 /* Decode via the codec registry */
3085 v = PyCodec_Decode(unicode, encoding, errors);
3086 if (v == NULL)
3087 goto onError;
3088 if (!PyUnicode_Check(v)) {
3089 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003090 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3091 "use codecs.decode() to decode to arbitrary types",
3092 encoding,
3093 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003094 Py_DECREF(v);
3095 goto onError;
3096 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003097 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003098
Benjamin Peterson29060642009-01-31 22:14:21 +00003099 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003100 return NULL;
3101}
3102
Alexander Belopolsky40018472011-02-26 01:02:56 +00003103PyObject *
3104PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003105 Py_ssize_t size,
3106 const char *encoding,
3107 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003108{
3109 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003110
Guido van Rossumd57fd912000-03-10 22:53:23 +00003111 unicode = PyUnicode_FromUnicode(s, size);
3112 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003114 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3115 Py_DECREF(unicode);
3116 return v;
3117}
3118
Alexander Belopolsky40018472011-02-26 01:02:56 +00003119PyObject *
3120PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003121 const char *encoding,
3122 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003123{
3124 PyObject *v;
3125
3126 if (!PyUnicode_Check(unicode)) {
3127 PyErr_BadArgument();
3128 goto onError;
3129 }
3130
3131 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003132 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003133
3134 /* Encode via the codec registry */
3135 v = PyCodec_Encode(unicode, encoding, errors);
3136 if (v == NULL)
3137 goto onError;
3138 return v;
3139
Benjamin Peterson29060642009-01-31 22:14:21 +00003140 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003141 return NULL;
3142}
3143
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003144static size_t
3145wcstombs_errorpos(const wchar_t *wstr)
3146{
3147 size_t len;
3148#if SIZEOF_WCHAR_T == 2
3149 wchar_t buf[3];
3150#else
3151 wchar_t buf[2];
3152#endif
3153 char outbuf[MB_LEN_MAX];
3154 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003155
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003156#if SIZEOF_WCHAR_T == 2
3157 buf[2] = 0;
3158#else
3159 buf[1] = 0;
3160#endif
3161 start = wstr;
3162 while (*wstr != L'\0')
3163 {
3164 previous = wstr;
3165#if SIZEOF_WCHAR_T == 2
3166 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3167 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3168 {
3169 buf[0] = wstr[0];
3170 buf[1] = wstr[1];
3171 wstr += 2;
3172 }
3173 else {
3174 buf[0] = *wstr;
3175 buf[1] = 0;
3176 wstr++;
3177 }
3178#else
3179 buf[0] = *wstr;
3180 wstr++;
3181#endif
3182 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003183 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003184 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003185 }
3186
3187 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003188 return 0;
3189}
3190
Victor Stinner1b579672011-12-17 05:47:23 +01003191static int
3192locale_error_handler(const char *errors, int *surrogateescape)
3193{
Victor Stinner50149202015-09-22 00:26:54 +02003194 _Py_error_handler error_handler = get_error_handler(errors);
3195 switch (error_handler)
3196 {
3197 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003198 *surrogateescape = 0;
3199 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003200 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003201 *surrogateescape = 1;
3202 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003203 default:
3204 PyErr_Format(PyExc_ValueError,
3205 "only 'strict' and 'surrogateescape' error handlers "
3206 "are supported, not '%s'",
3207 errors);
3208 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003209 }
Victor Stinner1b579672011-12-17 05:47:23 +01003210}
3211
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003212PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003213PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003214{
3215 Py_ssize_t wlen, wlen2;
3216 wchar_t *wstr;
3217 PyObject *bytes = NULL;
3218 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003219 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003220 PyObject *exc;
3221 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003222 int surrogateescape;
3223
3224 if (locale_error_handler(errors, &surrogateescape) < 0)
3225 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003226
3227 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3228 if (wstr == NULL)
3229 return NULL;
3230
3231 wlen2 = wcslen(wstr);
3232 if (wlen2 != wlen) {
3233 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003234 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003235 return NULL;
3236 }
3237
3238 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003239 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003240 char *str;
3241
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003242 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003243 if (str == NULL) {
3244 if (error_pos == (size_t)-1) {
3245 PyErr_NoMemory();
3246 PyMem_Free(wstr);
3247 return NULL;
3248 }
3249 else {
3250 goto encode_error;
3251 }
3252 }
3253 PyMem_Free(wstr);
3254
3255 bytes = PyBytes_FromString(str);
3256 PyMem_Free(str);
3257 }
3258 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003259 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003260 size_t len, len2;
3261
3262 len = wcstombs(NULL, wstr, 0);
3263 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003264 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003265 goto encode_error;
3266 }
3267
3268 bytes = PyBytes_FromStringAndSize(NULL, len);
3269 if (bytes == NULL) {
3270 PyMem_Free(wstr);
3271 return NULL;
3272 }
3273
3274 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3275 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003276 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 goto encode_error;
3278 }
3279 PyMem_Free(wstr);
3280 }
3281 return bytes;
3282
3283encode_error:
3284 errmsg = strerror(errno);
3285 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003286
3287 if (error_pos == (size_t)-1)
3288 error_pos = wcstombs_errorpos(wstr);
3289
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 PyMem_Free(wstr);
3291 Py_XDECREF(bytes);
3292
Victor Stinner2f197072011-12-17 07:08:30 +01003293 if (errmsg != NULL) {
3294 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003295 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003296 if (wstr != NULL) {
3297 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003298 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003299 } else
3300 errmsg = NULL;
3301 }
3302 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003303 reason = PyUnicode_FromString(
3304 "wcstombs() encountered an unencodable "
3305 "wide character");
3306 if (reason == NULL)
3307 return NULL;
3308
3309 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3310 "locale", unicode,
3311 (Py_ssize_t)error_pos,
3312 (Py_ssize_t)(error_pos+1),
3313 reason);
3314 Py_DECREF(reason);
3315 if (exc != NULL) {
3316 PyCodec_StrictErrors(exc);
3317 Py_XDECREF(exc);
3318 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003319 return NULL;
3320}
3321
Victor Stinnerad158722010-10-27 00:25:46 +00003322PyObject *
3323PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003324{
Victor Stinner99b95382011-07-04 14:23:54 +02003325#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003326 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003327#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003328 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003329#else
Victor Stinner793b5312011-04-27 00:24:21 +02003330 PyInterpreterState *interp = PyThreadState_GET()->interp;
3331 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3332 cannot use it to encode and decode filenames before it is loaded. Load
3333 the Python codec requires to encode at least its own filename. Use the C
3334 version of the locale codec until the codec registry is initialized and
3335 the Python codec is loaded.
3336
3337 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3338 cannot only rely on it: check also interp->fscodec_initialized for
3339 subinterpreters. */
3340 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003341 return PyUnicode_AsEncodedString(unicode,
3342 Py_FileSystemDefaultEncoding,
3343 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003344 }
3345 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003346 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003347 }
Victor Stinnerad158722010-10-27 00:25:46 +00003348#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003349}
3350
Alexander Belopolsky40018472011-02-26 01:02:56 +00003351PyObject *
3352PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003353 const char *encoding,
3354 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003355{
3356 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003357 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003358
Guido van Rossumd57fd912000-03-10 22:53:23 +00003359 if (!PyUnicode_Check(unicode)) {
3360 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003361 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003362 }
Fred Drakee4315f52000-05-09 19:53:39 +00003363
Fred Drakee4315f52000-05-09 19:53:39 +00003364 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003365 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003366 if ((strcmp(lower, "utf-8") == 0) ||
3367 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003368 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003369 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003370 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003371 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003372 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003373 }
Victor Stinner37296e82010-06-10 13:36:23 +00003374 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003375 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003376 (strcmp(lower, "iso-8859-1") == 0) ||
3377 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003378 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003379#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003380 else if (strcmp(lower, "mbcs") == 0)
3381 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003382#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003383 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003384 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003385 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003386
3387 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003388 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003389 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003390 return NULL;
3391
3392 /* The normal path */
3393 if (PyBytes_Check(v))
3394 return v;
3395
3396 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003397 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003398 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003399 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003400
3401 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003402 "encoder %s returned bytearray instead of bytes; "
3403 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003404 encoding);
3405 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003406 Py_DECREF(v);
3407 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003408 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003409
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003410 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3411 Py_DECREF(v);
3412 return b;
3413 }
3414
3415 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003416 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3417 "use codecs.encode() to encode to arbitrary types",
3418 encoding,
3419 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003420 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003421 return NULL;
3422}
3423
Alexander Belopolsky40018472011-02-26 01:02:56 +00003424PyObject *
3425PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003426 const char *encoding,
3427 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003428{
3429 PyObject *v;
3430
3431 if (!PyUnicode_Check(unicode)) {
3432 PyErr_BadArgument();
3433 goto onError;
3434 }
3435
3436 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003437 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438
3439 /* Encode via the codec registry */
3440 v = PyCodec_Encode(unicode, encoding, errors);
3441 if (v == NULL)
3442 goto onError;
3443 if (!PyUnicode_Check(v)) {
3444 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003445 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3446 "use codecs.encode() to encode to arbitrary types",
3447 encoding,
3448 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003449 Py_DECREF(v);
3450 goto onError;
3451 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003452 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003453
Benjamin Peterson29060642009-01-31 22:14:21 +00003454 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003455 return NULL;
3456}
3457
Victor Stinner2f197072011-12-17 07:08:30 +01003458static size_t
3459mbstowcs_errorpos(const char *str, size_t len)
3460{
3461#ifdef HAVE_MBRTOWC
3462 const char *start = str;
3463 mbstate_t mbs;
3464 size_t converted;
3465 wchar_t ch;
3466
3467 memset(&mbs, 0, sizeof mbs);
3468 while (len)
3469 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003470 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003471 if (converted == 0)
3472 /* Reached end of string */
3473 break;
3474 if (converted == (size_t)-1 || converted == (size_t)-2) {
3475 /* Conversion error or incomplete character */
3476 return str - start;
3477 }
3478 else {
3479 str += converted;
3480 len -= converted;
3481 }
3482 }
3483 /* failed to find the undecodable byte sequence */
3484 return 0;
3485#endif
3486 return 0;
3487}
3488
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003489PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003490PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003491 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003492{
3493 wchar_t smallbuf[256];
3494 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3495 wchar_t *wstr;
3496 size_t wlen, wlen2;
3497 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003498 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003499 size_t error_pos;
3500 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003501 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3502 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003503
3504 if (locale_error_handler(errors, &surrogateescape) < 0)
3505 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003507 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3508 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003509 return NULL;
3510 }
3511
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003512 if (surrogateescape) {
3513 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003514 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003515 if (wstr == NULL) {
3516 if (wlen == (size_t)-1)
3517 PyErr_NoMemory();
3518 else
3519 PyErr_SetFromErrno(PyExc_OSError);
3520 return NULL;
3521 }
3522
3523 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003524 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003525 }
3526 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003527 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003528#ifndef HAVE_BROKEN_MBSTOWCS
3529 wlen = mbstowcs(NULL, str, 0);
3530#else
3531 wlen = len;
3532#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003533 if (wlen == (size_t)-1)
3534 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003535 if (wlen+1 <= smallbuf_len) {
3536 wstr = smallbuf;
3537 }
3538 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003539 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003540 if (!wstr)
3541 return PyErr_NoMemory();
3542 }
3543
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003544 wlen2 = mbstowcs(wstr, str, wlen+1);
3545 if (wlen2 == (size_t)-1) {
3546 if (wstr != smallbuf)
3547 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003548 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549 }
3550#ifdef HAVE_BROKEN_MBSTOWCS
3551 assert(wlen2 == wlen);
3552#endif
3553 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3554 if (wstr != smallbuf)
3555 PyMem_Free(wstr);
3556 }
3557 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003558
3559decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003560 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003561 errmsg = strerror(errno);
3562 assert(errmsg != NULL);
3563
3564 error_pos = mbstowcs_errorpos(str, len);
3565 if (errmsg != NULL) {
3566 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003567 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003568 if (wstr != NULL) {
3569 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003570 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003571 }
Victor Stinner2f197072011-12-17 07:08:30 +01003572 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003573 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003574 reason = PyUnicode_FromString(
3575 "mbstowcs() encountered an invalid multibyte sequence");
3576 if (reason == NULL)
3577 return NULL;
3578
3579 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3580 "locale", str, len,
3581 (Py_ssize_t)error_pos,
3582 (Py_ssize_t)(error_pos+1),
3583 reason);
3584 Py_DECREF(reason);
3585 if (exc != NULL) {
3586 PyCodec_StrictErrors(exc);
3587 Py_XDECREF(exc);
3588 }
3589 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003590}
3591
3592PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003593PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003594{
3595 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003596 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003597}
3598
3599
3600PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003601PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003602 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003603 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3604}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003605
Christian Heimes5894ba72007-11-04 11:43:14 +00003606PyObject*
3607PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3608{
Victor Stinner99b95382011-07-04 14:23:54 +02003609#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003610 return PyUnicode_DecodeMBCS(s, size, NULL);
3611#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003612 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003613#else
Victor Stinner793b5312011-04-27 00:24:21 +02003614 PyInterpreterState *interp = PyThreadState_GET()->interp;
3615 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3616 cannot use it to encode and decode filenames before it is loaded. Load
3617 the Python codec requires to encode at least its own filename. Use the C
3618 version of the locale codec until the codec registry is initialized and
3619 the Python codec is loaded.
3620
3621 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3622 cannot only rely on it: check also interp->fscodec_initialized for
3623 subinterpreters. */
3624 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003625 return PyUnicode_Decode(s, size,
3626 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003627 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003628 }
3629 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003630 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003631 }
Victor Stinnerad158722010-10-27 00:25:46 +00003632#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003633}
3634
Martin v. Löwis011e8422009-05-05 04:43:17 +00003635
3636int
3637PyUnicode_FSConverter(PyObject* arg, void* addr)
3638{
3639 PyObject *output = NULL;
3640 Py_ssize_t size;
3641 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003642 if (arg == NULL) {
3643 Py_DECREF(*(PyObject**)addr);
3644 return 1;
3645 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003646 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003647 output = arg;
3648 Py_INCREF(output);
3649 }
3650 else {
3651 arg = PyUnicode_FromObject(arg);
3652 if (!arg)
3653 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003654 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003655 Py_DECREF(arg);
3656 if (!output)
3657 return 0;
3658 if (!PyBytes_Check(output)) {
3659 Py_DECREF(output);
3660 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3661 return 0;
3662 }
3663 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003664 size = PyBytes_GET_SIZE(output);
3665 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003666 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003667 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003668 Py_DECREF(output);
3669 return 0;
3670 }
3671 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003672 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003673}
3674
3675
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003676int
3677PyUnicode_FSDecoder(PyObject* arg, void* addr)
3678{
3679 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003680 if (arg == NULL) {
3681 Py_DECREF(*(PyObject**)addr);
3682 return 1;
3683 }
3684 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003685 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003686 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003687 output = arg;
3688 Py_INCREF(output);
3689 }
3690 else {
3691 arg = PyBytes_FromObject(arg);
3692 if (!arg)
3693 return 0;
3694 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3695 PyBytes_GET_SIZE(arg));
3696 Py_DECREF(arg);
3697 if (!output)
3698 return 0;
3699 if (!PyUnicode_Check(output)) {
3700 Py_DECREF(output);
3701 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3702 return 0;
3703 }
3704 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003705 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003706 Py_DECREF(output);
3707 return 0;
3708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003709 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003710 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003711 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003712 Py_DECREF(output);
3713 return 0;
3714 }
3715 *(PyObject**)addr = output;
3716 return Py_CLEANUP_SUPPORTED;
3717}
3718
3719
Martin v. Löwis5b222132007-06-10 09:51:05 +00003720char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003721PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003722{
Christian Heimesf3863112007-11-22 07:46:41 +00003723 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003724
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003725 if (!PyUnicode_Check(unicode)) {
3726 PyErr_BadArgument();
3727 return NULL;
3728 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003729 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003730 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003731
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003732 if (PyUnicode_UTF8(unicode) == NULL) {
3733 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003734 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3735 if (bytes == NULL)
3736 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003737 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3738 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003739 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003740 Py_DECREF(bytes);
3741 return NULL;
3742 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003743 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3744 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3745 PyBytes_AS_STRING(bytes),
3746 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003747 Py_DECREF(bytes);
3748 }
3749
3750 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003751 *psize = PyUnicode_UTF8_LENGTH(unicode);
3752 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003753}
3754
3755char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003757{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003758 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3759}
3760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761Py_UNICODE *
3762PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3763{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764 const unsigned char *one_byte;
3765#if SIZEOF_WCHAR_T == 4
3766 const Py_UCS2 *two_bytes;
3767#else
3768 const Py_UCS4 *four_bytes;
3769 const Py_UCS4 *ucs4_end;
3770 Py_ssize_t num_surrogates;
3771#endif
3772 wchar_t *w;
3773 wchar_t *wchar_end;
3774
3775 if (!PyUnicode_Check(unicode)) {
3776 PyErr_BadArgument();
3777 return NULL;
3778 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003779 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003781 assert(_PyUnicode_KIND(unicode) != 0);
3782 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003783
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003784 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003786 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3787 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788 num_surrogates = 0;
3789
3790 for (; four_bytes < ucs4_end; ++four_bytes) {
3791 if (*four_bytes > 0xFFFF)
3792 ++num_surrogates;
3793 }
3794
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003795 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3796 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3797 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798 PyErr_NoMemory();
3799 return NULL;
3800 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003801 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003802
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003803 w = _PyUnicode_WSTR(unicode);
3804 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3805 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003806 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3807 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003808 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003809 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003810 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3811 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 }
3813 else
3814 *w = *four_bytes;
3815
3816 if (w > wchar_end) {
3817 assert(0 && "Miscalculated string end");
3818 }
3819 }
3820 *w = 0;
3821#else
3822 /* sizeof(wchar_t) == 4 */
3823 Py_FatalError("Impossible unicode object state, wstr and str "
3824 "should share memory already.");
3825 return NULL;
3826#endif
3827 }
3828 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003829 if ((size_t)_PyUnicode_LENGTH(unicode) >
3830 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3831 PyErr_NoMemory();
3832 return NULL;
3833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3835 (_PyUnicode_LENGTH(unicode) + 1));
3836 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003837 PyErr_NoMemory();
3838 return NULL;
3839 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3841 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3842 w = _PyUnicode_WSTR(unicode);
3843 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003845 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3846 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003847 for (; w < wchar_end; ++one_byte, ++w)
3848 *w = *one_byte;
3849 /* null-terminate the wstr */
3850 *w = 0;
3851 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003852 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003853#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003854 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 for (; w < wchar_end; ++two_bytes, ++w)
3856 *w = *two_bytes;
3857 /* null-terminate the wstr */
3858 *w = 0;
3859#else
3860 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003861 PyObject_FREE(_PyUnicode_WSTR(unicode));
3862 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863 Py_FatalError("Impossible unicode object state, wstr "
3864 "and str should share memory already.");
3865 return NULL;
3866#endif
3867 }
3868 else {
3869 assert(0 && "This should never happen.");
3870 }
3871 }
3872 }
3873 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003874 *size = PyUnicode_WSTR_LENGTH(unicode);
3875 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003876}
3877
Alexander Belopolsky40018472011-02-26 01:02:56 +00003878Py_UNICODE *
3879PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003880{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003882}
3883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884
Alexander Belopolsky40018472011-02-26 01:02:56 +00003885Py_ssize_t
3886PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003887{
3888 if (!PyUnicode_Check(unicode)) {
3889 PyErr_BadArgument();
3890 goto onError;
3891 }
3892 return PyUnicode_GET_SIZE(unicode);
3893
Benjamin Peterson29060642009-01-31 22:14:21 +00003894 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003895 return -1;
3896}
3897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003898Py_ssize_t
3899PyUnicode_GetLength(PyObject *unicode)
3900{
Victor Stinner07621332012-06-16 04:53:46 +02003901 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 PyErr_BadArgument();
3903 return -1;
3904 }
Victor Stinner07621332012-06-16 04:53:46 +02003905 if (PyUnicode_READY(unicode) == -1)
3906 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003907 return PyUnicode_GET_LENGTH(unicode);
3908}
3909
3910Py_UCS4
3911PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3912{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003913 void *data;
3914 int kind;
3915
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003916 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3917 PyErr_BadArgument();
3918 return (Py_UCS4)-1;
3919 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003920 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003921 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003922 return (Py_UCS4)-1;
3923 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003924 data = PyUnicode_DATA(unicode);
3925 kind = PyUnicode_KIND(unicode);
3926 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003927}
3928
3929int
3930PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3931{
3932 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003933 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934 return -1;
3935 }
Victor Stinner488fa492011-12-12 00:01:39 +01003936 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003937 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003938 PyErr_SetString(PyExc_IndexError, "string index out of range");
3939 return -1;
3940 }
Victor Stinner488fa492011-12-12 00:01:39 +01003941 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003942 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003943 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3944 PyErr_SetString(PyExc_ValueError, "character out of range");
3945 return -1;
3946 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003947 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3948 index, ch);
3949 return 0;
3950}
3951
Alexander Belopolsky40018472011-02-26 01:02:56 +00003952const char *
3953PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003954{
Victor Stinner42cb4622010-09-01 19:39:01 +00003955 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003956}
3957
Victor Stinner554f3f02010-06-16 23:33:54 +00003958/* create or adjust a UnicodeDecodeError */
3959static void
3960make_decode_exception(PyObject **exceptionObject,
3961 const char *encoding,
3962 const char *input, Py_ssize_t length,
3963 Py_ssize_t startpos, Py_ssize_t endpos,
3964 const char *reason)
3965{
3966 if (*exceptionObject == NULL) {
3967 *exceptionObject = PyUnicodeDecodeError_Create(
3968 encoding, input, length, startpos, endpos, reason);
3969 }
3970 else {
3971 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3972 goto onError;
3973 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3974 goto onError;
3975 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3976 goto onError;
3977 }
3978 return;
3979
3980onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003981 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003982}
3983
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003984#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003985/* error handling callback helper:
3986 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003987 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003988 and adjust various state variables.
3989 return 0 on success, -1 on error
3990*/
3991
Alexander Belopolsky40018472011-02-26 01:02:56 +00003992static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003993unicode_decode_call_errorhandler_wchar(
3994 const char *errors, PyObject **errorHandler,
3995 const char *encoding, const char *reason,
3996 const char **input, const char **inend, Py_ssize_t *startinpos,
3997 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3998 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003999{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004000 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004001
4002 PyObject *restuple = NULL;
4003 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004004 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004005 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004006 Py_ssize_t requiredsize;
4007 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004008 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004009 wchar_t *repwstr;
4010 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4013 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004014
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004015 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004016 *errorHandler = PyCodec_LookupError(errors);
4017 if (*errorHandler == NULL)
4018 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004019 }
4020
Victor Stinner554f3f02010-06-16 23:33:54 +00004021 make_decode_exception(exceptionObject,
4022 encoding,
4023 *input, *inend - *input,
4024 *startinpos, *endinpos,
4025 reason);
4026 if (*exceptionObject == NULL)
4027 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004028
4029 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4030 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004031 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004032 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004033 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004034 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004035 }
4036 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004038
4039 /* Copy back the bytes variables, which might have been modified by the
4040 callback */
4041 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4042 if (!inputobj)
4043 goto onError;
4044 if (!PyBytes_Check(inputobj)) {
4045 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4046 }
4047 *input = PyBytes_AS_STRING(inputobj);
4048 insize = PyBytes_GET_SIZE(inputobj);
4049 *inend = *input + insize;
4050 /* we can DECREF safely, as the exception has another reference,
4051 so the object won't go away. */
4052 Py_DECREF(inputobj);
4053
4054 if (newpos<0)
4055 newpos = insize+newpos;
4056 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004057 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004058 goto onError;
4059 }
4060
4061 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4062 if (repwstr == NULL)
4063 goto onError;
4064 /* need more space? (at least enough for what we
4065 have+the replacement+the rest of the string (starting
4066 at the new input position), so we won't have to check space
4067 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004068 requiredsize = *outpos;
4069 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4070 goto overflow;
4071 requiredsize += repwlen;
4072 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4073 goto overflow;
4074 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004075 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004076 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004077 requiredsize = 2*outsize;
4078 if (unicode_resize(output, requiredsize) < 0)
4079 goto onError;
4080 }
4081 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4082 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004083 *endinpos = newpos;
4084 *inptr = *input + newpos;
4085
4086 /* we made it! */
4087 Py_XDECREF(restuple);
4088 return 0;
4089
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004090 overflow:
4091 PyErr_SetString(PyExc_OverflowError,
4092 "decoded result is too long for a Python string");
4093
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004094 onError:
4095 Py_XDECREF(restuple);
4096 return -1;
4097}
4098#endif /* HAVE_MBCS */
4099
4100static int
4101unicode_decode_call_errorhandler_writer(
4102 const char *errors, PyObject **errorHandler,
4103 const char *encoding, const char *reason,
4104 const char **input, const char **inend, Py_ssize_t *startinpos,
4105 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4106 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4107{
4108 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4109
4110 PyObject *restuple = NULL;
4111 PyObject *repunicode = NULL;
4112 Py_ssize_t insize;
4113 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004114 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004115 PyObject *inputobj = NULL;
4116
4117 if (*errorHandler == NULL) {
4118 *errorHandler = PyCodec_LookupError(errors);
4119 if (*errorHandler == NULL)
4120 goto onError;
4121 }
4122
4123 make_decode_exception(exceptionObject,
4124 encoding,
4125 *input, *inend - *input,
4126 *startinpos, *endinpos,
4127 reason);
4128 if (*exceptionObject == NULL)
4129 goto onError;
4130
4131 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4132 if (restuple == NULL)
4133 goto onError;
4134 if (!PyTuple_Check(restuple)) {
4135 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4136 goto onError;
4137 }
4138 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004139 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004140
4141 /* Copy back the bytes variables, which might have been modified by the
4142 callback */
4143 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4144 if (!inputobj)
4145 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004146 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004147 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004148 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004149 *input = PyBytes_AS_STRING(inputobj);
4150 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004151 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004152 /* we can DECREF safely, as the exception has another reference,
4153 so the object won't go away. */
4154 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004155
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004156 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004157 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004158 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004159 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004160 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004161 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004162
Victor Stinner8f674cc2013-04-17 23:02:17 +02004163 if (PyUnicode_READY(repunicode) < 0)
4164 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004165 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004166 if (replen > 1) {
4167 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004168 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004169 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4170 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4171 goto onError;
4172 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004173 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004174 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004175
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004176 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004177 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004178
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004179 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004180 Py_XDECREF(restuple);
4181 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004182
Benjamin Peterson29060642009-01-31 22:14:21 +00004183 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004184 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004185 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004186}
4187
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004188/* --- UTF-7 Codec -------------------------------------------------------- */
4189
Antoine Pitrou244651a2009-05-04 18:56:13 +00004190/* See RFC2152 for details. We encode conservatively and decode liberally. */
4191
4192/* Three simple macros defining base-64. */
4193
4194/* Is c a base-64 character? */
4195
4196#define IS_BASE64(c) \
4197 (((c) >= 'A' && (c) <= 'Z') || \
4198 ((c) >= 'a' && (c) <= 'z') || \
4199 ((c) >= '0' && (c) <= '9') || \
4200 (c) == '+' || (c) == '/')
4201
4202/* given that c is a base-64 character, what is its base-64 value? */
4203
4204#define FROM_BASE64(c) \
4205 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4206 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4207 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4208 (c) == '+' ? 62 : 63)
4209
4210/* What is the base-64 character of the bottom 6 bits of n? */
4211
4212#define TO_BASE64(n) \
4213 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4214
4215/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4216 * decoded as itself. We are permissive on decoding; the only ASCII
4217 * byte not decoding to itself is the + which begins a base64
4218 * string. */
4219
4220#define DECODE_DIRECT(c) \
4221 ((c) <= 127 && (c) != '+')
4222
4223/* The UTF-7 encoder treats ASCII characters differently according to
4224 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4225 * the above). See RFC2152. This array identifies these different
4226 * sets:
4227 * 0 : "Set D"
4228 * alphanumeric and '(),-./:?
4229 * 1 : "Set O"
4230 * !"#$%&*;<=>@[]^_`{|}
4231 * 2 : "whitespace"
4232 * ht nl cr sp
4233 * 3 : special (must be base64 encoded)
4234 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4235 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004236
Tim Petersced69f82003-09-16 20:30:58 +00004237static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004238char utf7_category[128] = {
4239/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4240 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4241/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4242 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4243/* sp ! " # $ % & ' ( ) * + , - . / */
4244 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4245/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4246 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4247/* @ A B C D E F G H I J K L M N O */
4248 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4249/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4250 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4251/* ` a b c d e f g h i j k l m n o */
4252 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4253/* p q r s t u v w x y z { | } ~ del */
4254 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004255};
4256
Antoine Pitrou244651a2009-05-04 18:56:13 +00004257/* ENCODE_DIRECT: this character should be encoded as itself. The
4258 * answer depends on whether we are encoding set O as itself, and also
4259 * on whether we are encoding whitespace as itself. RFC2152 makes it
4260 * clear that the answers to these questions vary between
4261 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004262
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263#define ENCODE_DIRECT(c, directO, directWS) \
4264 ((c) < 128 && (c) > 0 && \
4265 ((utf7_category[(c)] == 0) || \
4266 (directWS && (utf7_category[(c)] == 2)) || \
4267 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004268
Alexander Belopolsky40018472011-02-26 01:02:56 +00004269PyObject *
4270PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004271 Py_ssize_t size,
4272 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004273{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004274 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4275}
4276
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277/* The decoder. The only state we preserve is our read position,
4278 * i.e. how many characters we have consumed. So if we end in the
4279 * middle of a shift sequence we have to back off the read position
4280 * and the output to the beginning of the sequence, otherwise we lose
4281 * all the shift state (seen bits, number of bits seen, high
4282 * surrogate). */
4283
Alexander Belopolsky40018472011-02-26 01:02:56 +00004284PyObject *
4285PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004286 Py_ssize_t size,
4287 const char *errors,
4288 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004289{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004290 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004291 Py_ssize_t startinpos;
4292 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004294 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004295 const char *errmsg = "";
4296 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004297 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004298 unsigned int base64bits = 0;
4299 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004300 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004301 PyObject *errorHandler = NULL;
4302 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004303
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004304 if (size == 0) {
4305 if (consumed)
4306 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004307 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004308 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004309
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004310 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004311 _PyUnicodeWriter_Init(&writer);
4312 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313
4314 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004315 e = s + size;
4316
4317 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004318 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004319 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004320 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004321
Antoine Pitrou244651a2009-05-04 18:56:13 +00004322 if (inShift) { /* in a base-64 section */
4323 if (IS_BASE64(ch)) { /* consume a base-64 character */
4324 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4325 base64bits += 6;
4326 s++;
4327 if (base64bits >= 16) {
4328 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004329 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004330 base64bits -= 16;
4331 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004332 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 if (surrogate) {
4334 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004335 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4336 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004337 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004338 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004339 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004340 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004341 }
4342 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004343 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004344 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 }
4347 }
Victor Stinner551ac952011-11-29 22:58:13 +01004348 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349 /* first surrogate */
4350 surrogate = outCh;
4351 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004353 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004354 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 }
4356 }
4357 }
4358 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359 inShift = 0;
4360 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004362 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004363 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004364 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004365 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004366 if (base64bits > 0) { /* left-over bits */
4367 if (base64bits >= 6) {
4368 /* We've seen at least one base-64 character */
4369 errmsg = "partial character in shift sequence";
4370 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004372 else {
4373 /* Some bits remain; they should be zero */
4374 if (base64buffer != 0) {
4375 errmsg = "non-zero padding bits in shift sequence";
4376 goto utf7Error;
4377 }
4378 }
4379 }
4380 if (ch != '-') {
4381 /* '-' is absorbed; other terminating
4382 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004383 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004384 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 }
4387 }
4388 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004389 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004390 s++; /* consume '+' */
4391 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004392 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004393 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004394 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395 }
4396 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004397 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004398 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004399 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004400 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 }
4402 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004404 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004405 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004406 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 else {
4409 startinpos = s-starts;
4410 s++;
4411 errmsg = "unexpected special character";
4412 goto utf7Error;
4413 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004416 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004417 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 errors, &errorHandler,
4419 "utf7", errmsg,
4420 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004422 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004423 }
4424
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 /* end of string */
4426
4427 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4428 /* if we're in an inconsistent state, that's an error */
4429 if (surrogate ||
4430 (base64bits >= 6) ||
4431 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004433 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 errors, &errorHandler,
4435 "utf7", "unterminated shift sequence",
4436 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004437 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 goto onError;
4439 if (s < e)
4440 goto restart;
4441 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004442 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443
4444 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004445 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004447 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004448 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004449 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004450 writer.kind, writer.data, shiftOutStart);
4451 Py_XDECREF(errorHandler);
4452 Py_XDECREF(exc);
4453 _PyUnicodeWriter_Dealloc(&writer);
4454 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004455 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004456 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 }
4458 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004459 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004460 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004461 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004462
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004463 Py_XDECREF(errorHandler);
4464 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004465 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466
Benjamin Peterson29060642009-01-31 22:14:21 +00004467 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004468 Py_XDECREF(errorHandler);
4469 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 return NULL;
4472}
4473
4474
Alexander Belopolsky40018472011-02-26 01:02:56 +00004475PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004476_PyUnicode_EncodeUTF7(PyObject *str,
4477 int base64SetO,
4478 int base64WhiteSpace,
4479 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004481 int kind;
4482 void *data;
4483 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004484 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004486 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 unsigned int base64bits = 0;
4488 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489 char * out;
4490 char * start;
4491
Benjamin Petersonbac79492012-01-14 13:34:47 -05004492 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004493 return NULL;
4494 kind = PyUnicode_KIND(str);
4495 data = PyUnicode_DATA(str);
4496 len = PyUnicode_GET_LENGTH(str);
4497
4498 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004499 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004501 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004502 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004503 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004504 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 if (v == NULL)
4506 return NULL;
4507
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004508 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004509 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004510 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 if (inShift) {
4513 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4514 /* shifting out */
4515 if (base64bits) { /* output remaining bits */
4516 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4517 base64buffer = 0;
4518 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519 }
4520 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521 /* Characters not in the BASE64 set implicitly unshift the sequence
4522 so no '-' is required, except if the character is itself a '-' */
4523 if (IS_BASE64(ch) || ch == '-') {
4524 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 *out++ = (char) ch;
4527 }
4528 else {
4529 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004530 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004531 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004532 else { /* not in a shift sequence */
4533 if (ch == '+') {
4534 *out++ = '+';
4535 *out++ = '-';
4536 }
4537 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4538 *out++ = (char) ch;
4539 }
4540 else {
4541 *out++ = '+';
4542 inShift = 1;
4543 goto encode_char;
4544 }
4545 }
4546 continue;
4547encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004548 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004549 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004550
Antoine Pitrou244651a2009-05-04 18:56:13 +00004551 /* code first surrogate */
4552 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004553 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 while (base64bits >= 6) {
4555 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4556 base64bits -= 6;
4557 }
4558 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004559 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004560 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561 base64bits += 16;
4562 base64buffer = (base64buffer << 16) | ch;
4563 while (base64bits >= 6) {
4564 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4565 base64bits -= 6;
4566 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004567 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 if (base64bits)
4569 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4570 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004571 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004572 if (_PyBytes_Resize(&v, out - start) < 0)
4573 return NULL;
4574 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004575}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004576PyObject *
4577PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4578 Py_ssize_t size,
4579 int base64SetO,
4580 int base64WhiteSpace,
4581 const char *errors)
4582{
4583 PyObject *result;
4584 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4585 if (tmp == NULL)
4586 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004587 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004588 base64WhiteSpace, errors);
4589 Py_DECREF(tmp);
4590 return result;
4591}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593#undef IS_BASE64
4594#undef FROM_BASE64
4595#undef TO_BASE64
4596#undef DECODE_DIRECT
4597#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598
Guido van Rossumd57fd912000-03-10 22:53:23 +00004599/* --- UTF-8 Codec -------------------------------------------------------- */
4600
Alexander Belopolsky40018472011-02-26 01:02:56 +00004601PyObject *
4602PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004603 Py_ssize_t size,
4604 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004605{
Walter Dörwald69652032004-09-07 20:24:22 +00004606 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4607}
4608
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004609#include "stringlib/asciilib.h"
4610#include "stringlib/codecs.h"
4611#include "stringlib/undef.h"
4612
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004613#include "stringlib/ucs1lib.h"
4614#include "stringlib/codecs.h"
4615#include "stringlib/undef.h"
4616
4617#include "stringlib/ucs2lib.h"
4618#include "stringlib/codecs.h"
4619#include "stringlib/undef.h"
4620
4621#include "stringlib/ucs4lib.h"
4622#include "stringlib/codecs.h"
4623#include "stringlib/undef.h"
4624
Antoine Pitrouab868312009-01-10 15:40:25 +00004625/* Mask to quickly check whether a C 'long' contains a
4626 non-ASCII, UTF8-encoded char. */
4627#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004628# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004629#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004630# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004631#else
4632# error C 'long' size should be either 4 or 8!
4633#endif
4634
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004635static Py_ssize_t
4636ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004637{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004638 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004639 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004640
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004641 /*
4642 * Issue #17237: m68k is a bit different from most architectures in
4643 * that objects do not use "natural alignment" - for example, int and
4644 * long are only aligned at 2-byte boundaries. Therefore the assert()
4645 * won't work; also, tests have shown that skipping the "optimised
4646 * version" will even speed up m68k.
4647 */
4648#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004649#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004650 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4651 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004652 /* Fast path, see in STRINGLIB(utf8_decode) for
4653 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004654 /* Help allocation */
4655 const char *_p = p;
4656 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 while (_p < aligned_end) {
4658 unsigned long value = *(const unsigned long *) _p;
4659 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004660 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661 *((unsigned long *)q) = value;
4662 _p += SIZEOF_LONG;
4663 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004664 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004665 p = _p;
4666 while (p < end) {
4667 if ((unsigned char)*p & 0x80)
4668 break;
4669 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004670 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004671 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004672 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004673#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004674#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675 while (p < end) {
4676 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4677 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004678 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004679 /* Help allocation */
4680 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004681 while (_p < aligned_end) {
4682 unsigned long value = *(unsigned long *) _p;
4683 if (value & ASCII_CHAR_MASK)
4684 break;
4685 _p += SIZEOF_LONG;
4686 }
4687 p = _p;
4688 if (_p == end)
4689 break;
4690 }
4691 if ((unsigned char)*p & 0x80)
4692 break;
4693 ++p;
4694 }
4695 memcpy(dest, start, p - start);
4696 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697}
Antoine Pitrouab868312009-01-10 15:40:25 +00004698
Victor Stinner785938e2011-12-11 20:09:03 +01004699PyObject *
4700PyUnicode_DecodeUTF8Stateful(const char *s,
4701 Py_ssize_t size,
4702 const char *errors,
4703 Py_ssize_t *consumed)
4704{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004705 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004706 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004707 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004708
4709 Py_ssize_t startinpos;
4710 Py_ssize_t endinpos;
4711 const char *errmsg = "";
4712 PyObject *errorHandler = NULL;
4713 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004714
4715 if (size == 0) {
4716 if (consumed)
4717 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004718 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004719 }
4720
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004721 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4722 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004723 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 *consumed = 1;
4725 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004726 }
4727
Victor Stinner8f674cc2013-04-17 23:02:17 +02004728 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004729 writer.min_length = size;
4730 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004731 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004732
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004733 writer.pos = ascii_decode(s, end, writer.data);
4734 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004735 while (s < end) {
4736 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004737 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004738 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004739 if (PyUnicode_IS_ASCII(writer.buffer))
4740 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004742 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004743 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004744 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 } else {
4746 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004747 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748 }
4749
4750 switch (ch) {
4751 case 0:
4752 if (s == end || consumed)
4753 goto End;
4754 errmsg = "unexpected end of data";
4755 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004756 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004757 break;
4758 case 1:
4759 errmsg = "invalid start byte";
4760 startinpos = s - starts;
4761 endinpos = startinpos + 1;
4762 break;
4763 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004764 case 3:
4765 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 errmsg = "invalid continuation byte";
4767 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004768 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004769 break;
4770 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004771 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 goto onError;
4773 continue;
4774 }
4775
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004776 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777 errors, &errorHandler,
4778 "utf-8", errmsg,
4779 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004780 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004781 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004782 }
4783
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004784End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004785 if (consumed)
4786 *consumed = s - starts;
4787
4788 Py_XDECREF(errorHandler);
4789 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004790 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791
4792onError:
4793 Py_XDECREF(errorHandler);
4794 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004795 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004797}
4798
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004799#ifdef __APPLE__
4800
4801/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004802 used to decode the command line arguments on Mac OS X.
4803
4804 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004805 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004806
4807wchar_t*
4808_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4809{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004810 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 wchar_t *unicode;
4812 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004813
4814 /* Note: size will always be longer than the resulting Unicode
4815 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004816 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004818 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004819 if (!unicode)
4820 return NULL;
4821
4822 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004823 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004824 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004827#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004830 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004831#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004832 if (ch > 0xFF) {
4833#if SIZEOF_WCHAR_T == 4
4834 assert(0);
4835#else
4836 assert(Py_UNICODE_IS_SURROGATE(ch));
4837 /* compute and append the two surrogates: */
4838 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4839 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4840#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004841 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004842 else {
4843 if (!ch && s == e)
4844 break;
4845 /* surrogateescape */
4846 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4847 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850 return unicode;
4851}
4852
4853#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004855/* Primary internal function which creates utf8 encoded bytes objects.
4856
4857 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004858 and allocate exactly as much space needed at the end. Else allocate the
4859 maximum possible needed (4 result bytes per Unicode character), and return
4860 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004861*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004862PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004863_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004864{
Victor Stinner6099a032011-12-18 14:22:26 +01004865 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004866 void *data;
4867 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004869 if (!PyUnicode_Check(unicode)) {
4870 PyErr_BadArgument();
4871 return NULL;
4872 }
4873
4874 if (PyUnicode_READY(unicode) == -1)
4875 return NULL;
4876
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004877 if (PyUnicode_UTF8(unicode))
4878 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4879 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880
4881 kind = PyUnicode_KIND(unicode);
4882 data = PyUnicode_DATA(unicode);
4883 size = PyUnicode_GET_LENGTH(unicode);
4884
Benjamin Petersonead6b532011-12-20 17:23:42 -06004885 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004886 default:
4887 assert(0);
4888 case PyUnicode_1BYTE_KIND:
4889 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4890 assert(!PyUnicode_IS_ASCII(unicode));
4891 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4892 case PyUnicode_2BYTE_KIND:
4893 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4894 case PyUnicode_4BYTE_KIND:
4895 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004896 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004897}
4898
Alexander Belopolsky40018472011-02-26 01:02:56 +00004899PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004900PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4901 Py_ssize_t size,
4902 const char *errors)
4903{
4904 PyObject *v, *unicode;
4905
4906 unicode = PyUnicode_FromUnicode(s, size);
4907 if (unicode == NULL)
4908 return NULL;
4909 v = _PyUnicode_AsUTF8String(unicode, errors);
4910 Py_DECREF(unicode);
4911 return v;
4912}
4913
4914PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004915PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004916{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004917 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004918}
4919
Walter Dörwald41980ca2007-08-16 21:55:45 +00004920/* --- UTF-32 Codec ------------------------------------------------------- */
4921
4922PyObject *
4923PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004924 Py_ssize_t size,
4925 const char *errors,
4926 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004927{
4928 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4929}
4930
4931PyObject *
4932PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004933 Py_ssize_t size,
4934 const char *errors,
4935 int *byteorder,
4936 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937{
4938 const char *starts = s;
4939 Py_ssize_t startinpos;
4940 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004941 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004942 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004943 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004944 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004945 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004946 PyObject *errorHandler = NULL;
4947 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004948
Walter Dörwald41980ca2007-08-16 21:55:45 +00004949 q = (unsigned char *)s;
4950 e = q + size;
4951
4952 if (byteorder)
4953 bo = *byteorder;
4954
4955 /* Check for BOM marks (U+FEFF) in the input and adjust current
4956 byte order setting accordingly. In native mode, the leading BOM
4957 mark is skipped, in all other modes, it is copied to the output
4958 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004959 if (bo == 0 && size >= 4) {
4960 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4961 if (bom == 0x0000FEFF) {
4962 bo = -1;
4963 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004964 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004965 else if (bom == 0xFFFE0000) {
4966 bo = 1;
4967 q += 4;
4968 }
4969 if (byteorder)
4970 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971 }
4972
Victor Stinnere64322e2012-10-30 23:12:47 +01004973 if (q == e) {
4974 if (consumed)
4975 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004976 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 }
4978
Victor Stinnere64322e2012-10-30 23:12:47 +01004979#ifdef WORDS_BIGENDIAN
4980 le = bo < 0;
4981#else
4982 le = bo <= 0;
4983#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004984 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004985
Victor Stinner8f674cc2013-04-17 23:02:17 +02004986 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004987 writer.min_length = (e - q + 3) / 4;
4988 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004989 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004990
Victor Stinnere64322e2012-10-30 23:12:47 +01004991 while (1) {
4992 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004993 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004994
Victor Stinnere64322e2012-10-30 23:12:47 +01004995 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004996 enum PyUnicode_Kind kind = writer.kind;
4997 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004998 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004999 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005000 if (le) {
5001 do {
5002 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5003 if (ch > maxch)
5004 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005005 if (kind != PyUnicode_1BYTE_KIND &&
5006 Py_UNICODE_IS_SURROGATE(ch))
5007 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005009 q += 4;
5010 } while (q <= last);
5011 }
5012 else {
5013 do {
5014 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5015 if (ch > maxch)
5016 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005017 if (kind != PyUnicode_1BYTE_KIND &&
5018 Py_UNICODE_IS_SURROGATE(ch))
5019 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005020 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 q += 4;
5022 } while (q <= last);
5023 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005024 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005025 }
5026
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005027 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005028 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005029 startinpos = ((const char *)q) - starts;
5030 endinpos = startinpos + 4;
5031 }
5032 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005033 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005034 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005035 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005037 startinpos = ((const char *)q) - starts;
5038 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005040 else {
5041 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005042 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005043 goto onError;
5044 q += 4;
5045 continue;
5046 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005047 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 startinpos = ((const char *)q) - starts;
5049 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005050 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005051
5052 /* The remaining input chars are ignored if the callback
5053 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005054 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005056 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005058 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005059 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060 }
5061
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064
Walter Dörwald41980ca2007-08-16 21:55:45 +00005065 Py_XDECREF(errorHandler);
5066 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005067 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005068
Benjamin Peterson29060642009-01-31 22:14:21 +00005069 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005070 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 Py_XDECREF(errorHandler);
5072 Py_XDECREF(exc);
5073 return NULL;
5074}
5075
5076PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005077_PyUnicode_EncodeUTF32(PyObject *str,
5078 const char *errors,
5079 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005081 enum PyUnicode_Kind kind;
5082 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005083 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005084 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005085 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005086#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005087 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005089 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005090#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005091 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005092 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005093 PyObject *errorHandler = NULL;
5094 PyObject *exc = NULL;
5095 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005097 if (!PyUnicode_Check(str)) {
5098 PyErr_BadArgument();
5099 return NULL;
5100 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005101 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005102 return NULL;
5103 kind = PyUnicode_KIND(str);
5104 data = PyUnicode_DATA(str);
5105 len = PyUnicode_GET_LENGTH(str);
5106
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005107 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005108 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005109 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005110 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005111 if (v == NULL)
5112 return NULL;
5113
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005114 /* output buffer is 4-bytes aligned */
5115 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5116 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005118 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005119 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005120 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005122 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005123 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005124 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005125 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005126 else
5127 encoding = "utf-32";
5128
5129 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005130 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5131 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005132 }
5133
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005134 pos = 0;
5135 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005136 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005137
5138 if (kind == PyUnicode_2BYTE_KIND) {
5139 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5140 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005141 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005142 else {
5143 assert(kind == PyUnicode_4BYTE_KIND);
5144 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5145 &out, native_ordering);
5146 }
5147 if (pos == len)
5148 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005149
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005150 rep = unicode_encode_call_errorhandler(
5151 errors, &errorHandler,
5152 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005153 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005154 if (!rep)
5155 goto error;
5156
5157 if (PyBytes_Check(rep)) {
5158 repsize = PyBytes_GET_SIZE(rep);
5159 if (repsize & 3) {
5160 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005161 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005162 "surrogates not allowed");
5163 goto error;
5164 }
5165 moreunits = repsize / 4;
5166 }
5167 else {
5168 assert(PyUnicode_Check(rep));
5169 if (PyUnicode_READY(rep) < 0)
5170 goto error;
5171 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5172 if (!PyUnicode_IS_ASCII(rep)) {
5173 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005174 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005175 "surrogates not allowed");
5176 goto error;
5177 }
5178 }
5179
5180 /* four bytes are reserved for each surrogate */
5181 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005182 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005183 Py_ssize_t morebytes = 4 * (moreunits - 1);
5184 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5185 /* integer overflow */
5186 PyErr_NoMemory();
5187 goto error;
5188 }
5189 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5190 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005191 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005192 }
5193
5194 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005195 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5196 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005197 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005198 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005199 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5200 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 }
5202
5203 Py_CLEAR(rep);
5204 }
5205
5206 /* Cut back to size actually needed. This is necessary for, for example,
5207 encoding of a string containing isolated surrogates and the 'ignore'
5208 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005209 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005210 if (nsize != PyBytes_GET_SIZE(v))
5211 _PyBytes_Resize(&v, nsize);
5212 Py_XDECREF(errorHandler);
5213 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005214 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005215 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005216 error:
5217 Py_XDECREF(rep);
5218 Py_XDECREF(errorHandler);
5219 Py_XDECREF(exc);
5220 Py_XDECREF(v);
5221 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005222}
5223
Alexander Belopolsky40018472011-02-26 01:02:56 +00005224PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005225PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5226 Py_ssize_t size,
5227 const char *errors,
5228 int byteorder)
5229{
5230 PyObject *result;
5231 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5232 if (tmp == NULL)
5233 return NULL;
5234 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5235 Py_DECREF(tmp);
5236 return result;
5237}
5238
5239PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005240PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005241{
Victor Stinnerb960b342011-11-20 19:12:52 +01005242 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005243}
5244
Guido van Rossumd57fd912000-03-10 22:53:23 +00005245/* --- UTF-16 Codec ------------------------------------------------------- */
5246
Tim Peters772747b2001-08-09 22:21:55 +00005247PyObject *
5248PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005249 Py_ssize_t size,
5250 const char *errors,
5251 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005252{
Walter Dörwald69652032004-09-07 20:24:22 +00005253 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5254}
5255
5256PyObject *
5257PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005258 Py_ssize_t size,
5259 const char *errors,
5260 int *byteorder,
5261 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005262{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005263 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005264 Py_ssize_t startinpos;
5265 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005266 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005267 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005268 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005269 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005270 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005271 PyObject *errorHandler = NULL;
5272 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005273 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005274
Tim Peters772747b2001-08-09 22:21:55 +00005275 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005276 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005277
5278 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005279 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005281 /* Check for BOM marks (U+FEFF) in the input and adjust current
5282 byte order setting accordingly. In native mode, the leading BOM
5283 mark is skipped, in all other modes, it is copied to the output
5284 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005285 if (bo == 0 && size >= 2) {
5286 const Py_UCS4 bom = (q[1] << 8) | q[0];
5287 if (bom == 0xFEFF) {
5288 q += 2;
5289 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005290 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005291 else if (bom == 0xFFFE) {
5292 q += 2;
5293 bo = 1;
5294 }
5295 if (byteorder)
5296 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005297 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005298
Antoine Pitrou63065d72012-05-15 23:48:04 +02005299 if (q == e) {
5300 if (consumed)
5301 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005302 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005303 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005304
Christian Heimes743e0cd2012-10-17 23:52:17 +02005305#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005306 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005307 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005308#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005309 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005310 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005311#endif
Tim Peters772747b2001-08-09 22:21:55 +00005312
Antoine Pitrou63065d72012-05-15 23:48:04 +02005313 /* Note: size will always be longer than the resulting Unicode
5314 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005315 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005316 writer.min_length = (e - q + 1) / 2;
5317 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005318 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319
Antoine Pitrou63065d72012-05-15 23:48:04 +02005320 while (1) {
5321 Py_UCS4 ch = 0;
5322 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005323 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005324 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005325 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005327 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328 native_ordering);
5329 else
5330 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005331 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005332 native_ordering);
5333 } else if (kind == PyUnicode_2BYTE_KIND) {
5334 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005336 native_ordering);
5337 } else {
5338 assert(kind == PyUnicode_4BYTE_KIND);
5339 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005340 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005341 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005342 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005343 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005344
Antoine Pitrou63065d72012-05-15 23:48:04 +02005345 switch (ch)
5346 {
5347 case 0:
5348 /* remaining byte at the end? (size should be even) */
5349 if (q == e || consumed)
5350 goto End;
5351 errmsg = "truncated data";
5352 startinpos = ((const char *)q) - starts;
5353 endinpos = ((const char *)e) - starts;
5354 break;
5355 /* The remaining input chars are ignored if the callback
5356 chooses to skip the input */
5357 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005358 q -= 2;
5359 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005360 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005361 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005362 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 endinpos = ((const char *)e) - starts;
5364 break;
5365 case 2:
5366 errmsg = "illegal encoding";
5367 startinpos = ((const char *)q) - 2 - starts;
5368 endinpos = startinpos + 2;
5369 break;
5370 case 3:
5371 errmsg = "illegal UTF-16 surrogate";
5372 startinpos = ((const char *)q) - 4 - starts;
5373 endinpos = startinpos + 2;
5374 break;
5375 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005376 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005377 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 continue;
5379 }
5380
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005381 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005382 errors,
5383 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005384 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005385 &starts,
5386 (const char **)&e,
5387 &startinpos,
5388 &endinpos,
5389 &exc,
5390 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005391 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005392 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005393 }
5394
Antoine Pitrou63065d72012-05-15 23:48:04 +02005395End:
Walter Dörwald69652032004-09-07 20:24:22 +00005396 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005397 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005398
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005399 Py_XDECREF(errorHandler);
5400 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005401 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005402
Benjamin Peterson29060642009-01-31 22:14:21 +00005403 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005404 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005405 Py_XDECREF(errorHandler);
5406 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005407 return NULL;
5408}
5409
Tim Peters772747b2001-08-09 22:21:55 +00005410PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005411_PyUnicode_EncodeUTF16(PyObject *str,
5412 const char *errors,
5413 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005414{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005415 enum PyUnicode_Kind kind;
5416 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005417 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005418 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005419 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005420 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005421#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005422 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005423#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005424 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005425#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005426 const char *encoding;
5427 Py_ssize_t nsize, pos;
5428 PyObject *errorHandler = NULL;
5429 PyObject *exc = NULL;
5430 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005431
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005432 if (!PyUnicode_Check(str)) {
5433 PyErr_BadArgument();
5434 return NULL;
5435 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005436 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005437 return NULL;
5438 kind = PyUnicode_KIND(str);
5439 data = PyUnicode_DATA(str);
5440 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005441
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005442 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005443 if (kind == PyUnicode_4BYTE_KIND) {
5444 const Py_UCS4 *in = (const Py_UCS4 *)data;
5445 const Py_UCS4 *end = in + len;
5446 while (in < end)
5447 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005448 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005449 }
5450 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005451 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005452 nsize = len + pairs + (byteorder == 0);
5453 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005454 if (v == NULL)
5455 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005457 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005458 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005461 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005462 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005463 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005464
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005465 if (kind == PyUnicode_1BYTE_KIND) {
5466 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5467 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005468 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005469
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 if (byteorder < 0)
5471 encoding = "utf-16-le";
5472 else if (byteorder > 0)
5473 encoding = "utf-16-be";
5474 else
5475 encoding = "utf-16";
5476
5477 pos = 0;
5478 while (pos < len) {
5479 Py_ssize_t repsize, moreunits;
5480
5481 if (kind == PyUnicode_2BYTE_KIND) {
5482 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5483 &out, native_ordering);
5484 }
5485 else {
5486 assert(kind == PyUnicode_4BYTE_KIND);
5487 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5488 &out, native_ordering);
5489 }
5490 if (pos == len)
5491 break;
5492
5493 rep = unicode_encode_call_errorhandler(
5494 errors, &errorHandler,
5495 encoding, "surrogates not allowed",
5496 str, &exc, pos, pos + 1, &pos);
5497 if (!rep)
5498 goto error;
5499
5500 if (PyBytes_Check(rep)) {
5501 repsize = PyBytes_GET_SIZE(rep);
5502 if (repsize & 1) {
5503 raise_encode_exception(&exc, encoding,
5504 str, pos - 1, pos,
5505 "surrogates not allowed");
5506 goto error;
5507 }
5508 moreunits = repsize / 2;
5509 }
5510 else {
5511 assert(PyUnicode_Check(rep));
5512 if (PyUnicode_READY(rep) < 0)
5513 goto error;
5514 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5515 if (!PyUnicode_IS_ASCII(rep)) {
5516 raise_encode_exception(&exc, encoding,
5517 str, pos - 1, pos,
5518 "surrogates not allowed");
5519 goto error;
5520 }
5521 }
5522
5523 /* two bytes are reserved for each surrogate */
5524 if (moreunits > 1) {
5525 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5526 Py_ssize_t morebytes = 2 * (moreunits - 1);
5527 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5528 /* integer overflow */
5529 PyErr_NoMemory();
5530 goto error;
5531 }
5532 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5533 goto error;
5534 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5535 }
5536
5537 if (PyBytes_Check(rep)) {
5538 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5539 out += moreunits;
5540 } else /* rep is unicode */ {
5541 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5542 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5543 &out, native_ordering);
5544 }
5545
5546 Py_CLEAR(rep);
5547 }
5548
5549 /* Cut back to size actually needed. This is necessary for, for example,
5550 encoding of a string containing isolated surrogates and the 'ignore' handler
5551 is used. */
5552 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5553 if (nsize != PyBytes_GET_SIZE(v))
5554 _PyBytes_Resize(&v, nsize);
5555 Py_XDECREF(errorHandler);
5556 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005557 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005558 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005559 error:
5560 Py_XDECREF(rep);
5561 Py_XDECREF(errorHandler);
5562 Py_XDECREF(exc);
5563 Py_XDECREF(v);
5564 return NULL;
5565#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566}
5567
Alexander Belopolsky40018472011-02-26 01:02:56 +00005568PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005569PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5570 Py_ssize_t size,
5571 const char *errors,
5572 int byteorder)
5573{
5574 PyObject *result;
5575 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5576 if (tmp == NULL)
5577 return NULL;
5578 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5579 Py_DECREF(tmp);
5580 return result;
5581}
5582
5583PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005584PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005585{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005586 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005587}
5588
5589/* --- Unicode Escape Codec ----------------------------------------------- */
5590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005591/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5592 if all the escapes in the string make it still a valid ASCII string.
5593 Returns -1 if any escapes were found which cause the string to
5594 pop out of ASCII range. Otherwise returns the length of the
5595 required buffer to hold the string.
5596 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005597static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005598length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5599{
5600 const unsigned char *p = (const unsigned char *)s;
5601 const unsigned char *end = p + size;
5602 Py_ssize_t length = 0;
5603
5604 if (size < 0)
5605 return -1;
5606
5607 for (; p < end; ++p) {
5608 if (*p > 127) {
5609 /* Non-ASCII */
5610 return -1;
5611 }
5612 else if (*p != '\\') {
5613 /* Normal character */
5614 ++length;
5615 }
5616 else {
5617 /* Backslash-escape, check next char */
5618 ++p;
5619 /* Escape sequence reaches till end of string or
5620 non-ASCII follow-up. */
5621 if (p >= end || *p > 127)
5622 return -1;
5623 switch (*p) {
5624 case '\n':
5625 /* backslash + \n result in zero characters */
5626 break;
5627 case '\\': case '\'': case '\"':
5628 case 'b': case 'f': case 't':
5629 case 'n': case 'r': case 'v': case 'a':
5630 ++length;
5631 break;
5632 case '0': case '1': case '2': case '3':
5633 case '4': case '5': case '6': case '7':
5634 case 'x': case 'u': case 'U': case 'N':
5635 /* these do not guarantee ASCII characters */
5636 return -1;
5637 default:
5638 /* count the backslash + the other character */
5639 length += 2;
5640 }
5641 }
5642 }
5643 return length;
5644}
5645
Fredrik Lundh06d12682001-01-24 07:59:11 +00005646static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005647
Alexander Belopolsky40018472011-02-26 01:02:56 +00005648PyObject *
5649PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005650 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005651 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005653 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005654 Py_ssize_t startinpos;
5655 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005656 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005657 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005658 char* message;
5659 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005660 PyObject *errorHandler = NULL;
5661 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005662 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005663
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005664 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005665 if (len == 0)
5666 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005667
5668 /* After length_of_escaped_ascii_string() there are two alternatives,
5669 either the string is pure ASCII with named escapes like \n, etc.
5670 and we determined it's exact size (common case)
5671 or it contains \x, \u, ... escape sequences. then we create a
5672 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005673 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005674 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005675 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005676 }
5677 else {
5678 /* Escaped strings will always be longer than the resulting
5679 Unicode string, so we start with size here and then reduce the
5680 length after conversion to the true value.
5681 (but if the error callback returns a long replacement string
5682 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005683 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005684 }
5685
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005687 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005689
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 while (s < end) {
5691 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005692 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005693 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694
5695 /* Non-escape characters are interpreted as Unicode ordinals */
5696 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005697 x = (unsigned char)*s;
5698 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005699 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005700 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701 continue;
5702 }
5703
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005704 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005705 /* \ - Escapes */
5706 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005707 c = *s++;
5708 if (s > end)
5709 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005711 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005712
Benjamin Peterson29060642009-01-31 22:14:21 +00005713 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005714#define WRITECHAR(ch) \
5715 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005716 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005717 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005718 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005719
Guido van Rossumd57fd912000-03-10 22:53:23 +00005720 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005721 case '\\': WRITECHAR('\\'); break;
5722 case '\'': WRITECHAR('\''); break;
5723 case '\"': WRITECHAR('\"'); break;
5724 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005725 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005726 case 'f': WRITECHAR('\014'); break;
5727 case 't': WRITECHAR('\t'); break;
5728 case 'n': WRITECHAR('\n'); break;
5729 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005730 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005731 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005732 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005733 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 case '0': case '1': case '2': case '3':
5737 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005738 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005739 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005740 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005741 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005742 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005743 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005744 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005745 break;
5746
Benjamin Peterson29060642009-01-31 22:14:21 +00005747 /* hex escapes */
5748 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005750 digits = 2;
5751 message = "truncated \\xXX escape";
5752 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005756 digits = 4;
5757 message = "truncated \\uXXXX escape";
5758 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759
Benjamin Peterson29060642009-01-31 22:14:21 +00005760 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005761 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005762 digits = 8;
5763 message = "truncated \\UXXXXXXXX escape";
5764 hexescape:
5765 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005766 if (end - s < digits) {
5767 /* count only hex digits */
5768 for (; s < end; ++s) {
5769 c = (unsigned char)*s;
5770 if (!Py_ISXDIGIT(c))
5771 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005772 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005773 goto error;
5774 }
5775 for (; digits--; ++s) {
5776 c = (unsigned char)*s;
5777 if (!Py_ISXDIGIT(c))
5778 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005779 chr = (chr<<4) & ~0xF;
5780 if (c >= '0' && c <= '9')
5781 chr += c - '0';
5782 else if (c >= 'a' && c <= 'f')
5783 chr += 10 + c - 'a';
5784 else
5785 chr += 10 + c - 'A';
5786 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005787 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005788 /* _decoding_error will have already written into the
5789 target buffer. */
5790 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005791 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005792 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005793 message = "illegal Unicode character";
5794 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005795 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005796 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 break;
5798
Benjamin Peterson29060642009-01-31 22:14:21 +00005799 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005800 case 'N':
5801 message = "malformed \\N character escape";
5802 if (ucnhash_CAPI == NULL) {
5803 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005804 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5805 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005806 if (ucnhash_CAPI == NULL)
5807 goto ucnhashError;
5808 }
5809 if (*s == '{') {
5810 const char *start = s+1;
5811 /* look for the closing brace */
5812 while (*s != '}' && s < end)
5813 s++;
5814 if (s > start && s < end && *s == '}') {
5815 /* found a name. look it up in the unicode database */
5816 message = "unknown Unicode character name";
5817 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005818 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005819 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005820 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005821 goto store;
5822 }
5823 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005824 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005825
5826 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005827 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005828 message = "\\ at end of string";
5829 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005831 }
5832 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005833 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005834 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005835 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005836 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005837 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005838 continue;
5839
5840 error:
5841 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005842 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005843 errors, &errorHandler,
5844 "unicodeescape", message,
5845 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005846 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005847 goto onError;
5848 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005850#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005851
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005852 Py_XDECREF(errorHandler);
5853 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005854 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005855
Benjamin Peterson29060642009-01-31 22:14:21 +00005856 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005857 PyErr_SetString(
5858 PyExc_UnicodeError,
5859 "\\N escapes not supported (can't load unicodedata module)"
5860 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005861 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005862 Py_XDECREF(errorHandler);
5863 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005864 return NULL;
5865
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005867 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005868 Py_XDECREF(errorHandler);
5869 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 return NULL;
5871}
5872
5873/* Return a Unicode-Escape string version of the Unicode object.
5874
5875 If quotes is true, the string is enclosed in u"" or u'' quotes as
5876 appropriate.
5877
5878*/
5879
Alexander Belopolsky40018472011-02-26 01:02:56 +00005880PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005881PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005883 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005884 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005886 int kind;
5887 void *data;
5888 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889
Ezio Melottie7f90372012-10-05 03:33:31 +03005890 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005891 escape.
5892
Ezio Melottie7f90372012-10-05 03:33:31 +03005893 For UCS1 strings it's '\xxx', 4 bytes per source character.
5894 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5895 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005896 */
5897
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005898 if (!PyUnicode_Check(unicode)) {
5899 PyErr_BadArgument();
5900 return NULL;
5901 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005902 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005903 return NULL;
5904 len = PyUnicode_GET_LENGTH(unicode);
5905 kind = PyUnicode_KIND(unicode);
5906 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005907 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005908 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5909 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5910 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5911 }
5912
5913 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005914 return PyBytes_FromStringAndSize(NULL, 0);
5915
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005917 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005918
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005919 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005920 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005922 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 if (repr == NULL)
5924 return NULL;
5925
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005926 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005928 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005929 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005930
Walter Dörwald79e913e2007-05-12 11:08:06 +00005931 /* Escape backslashes */
5932 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 *p++ = '\\';
5934 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005935 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005936 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005937
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005938 /* Map 21-bit characters to '\U00xxxxxx' */
5939 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005940 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005941 *p++ = '\\';
5942 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005943 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5944 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5945 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5946 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5947 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5948 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5949 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5950 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005952 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005953
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005955 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005956 *p++ = '\\';
5957 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005958 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5959 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5960 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5961 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005963
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005964 /* Map special whitespace to '\t', \n', '\r' */
5965 else if (ch == '\t') {
5966 *p++ = '\\';
5967 *p++ = 't';
5968 }
5969 else if (ch == '\n') {
5970 *p++ = '\\';
5971 *p++ = 'n';
5972 }
5973 else if (ch == '\r') {
5974 *p++ = '\\';
5975 *p++ = 'r';
5976 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005977
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005978 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005979 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005981 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005982 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5983 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005984 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005985
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986 /* Copy everything else as-is */
5987 else
5988 *p++ = (char) ch;
5989 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005991 assert(p - PyBytes_AS_STRING(repr) > 0);
5992 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5993 return NULL;
5994 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995}
5996
Alexander Belopolsky40018472011-02-26 01:02:56 +00005997PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005998PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5999 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006001 PyObject *result;
6002 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6003 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006005 result = PyUnicode_AsUnicodeEscapeString(tmp);
6006 Py_DECREF(tmp);
6007 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008}
6009
6010/* --- Raw Unicode Escape Codec ------------------------------------------- */
6011
Alexander Belopolsky40018472011-02-26 01:02:56 +00006012PyObject *
6013PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006014 Py_ssize_t size,
6015 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006017 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006018 Py_ssize_t startinpos;
6019 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006020 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021 const char *end;
6022 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006023 PyObject *errorHandler = NULL;
6024 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006025
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006026 if (size == 0)
6027 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006028
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 /* Escaped strings will always be longer than the resulting
6030 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006031 length after conversion to the true value. (But decoding error
6032 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006033 _PyUnicodeWriter_Init(&writer);
6034 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006035
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 end = s + size;
6037 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 unsigned char c;
6039 Py_UCS4 x;
6040 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006041 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042
Benjamin Peterson29060642009-01-31 22:14:21 +00006043 /* Non-escape characters are interpreted as Unicode ordinals */
6044 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006045 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006046 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006047 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006049 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 startinpos = s-starts;
6051
6052 /* \u-escapes are only interpreted iff the number of leading
6053 backslashes if odd */
6054 bs = s;
6055 for (;s < end;) {
6056 if (*s != '\\')
6057 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006058 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006059 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006060 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 }
6062 if (((s - bs) & 1) == 0 ||
6063 s >= end ||
6064 (*s != 'u' && *s != 'U')) {
6065 continue;
6066 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006067 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006068 count = *s=='u' ? 4 : 8;
6069 s++;
6070
6071 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006072 for (x = 0, i = 0; i < count; ++i, ++s) {
6073 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006074 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006076 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 errors, &errorHandler,
6078 "rawunicodeescape", "truncated \\uXXXX",
6079 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006080 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 goto onError;
6082 goto nextByte;
6083 }
6084 x = (x<<4) & ~0xF;
6085 if (c >= '0' && c <= '9')
6086 x += c - '0';
6087 else if (c >= 'a' && c <= 'f')
6088 x += 10 + c - 'a';
6089 else
6090 x += 10 + c - 'A';
6091 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006092 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006093 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006094 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006095 }
6096 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006097 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006098 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006099 errors, &errorHandler,
6100 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006101 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006102 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006104 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 nextByte:
6106 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006108 Py_XDECREF(errorHandler);
6109 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006110 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006111
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006113 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006114 Py_XDECREF(errorHandler);
6115 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116 return NULL;
6117}
6118
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119
Alexander Belopolsky40018472011-02-26 01:02:56 +00006120PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006121PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006123 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006124 char *p;
6125 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 Py_ssize_t expandsize, pos;
6127 int kind;
6128 void *data;
6129 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006131 if (!PyUnicode_Check(unicode)) {
6132 PyErr_BadArgument();
6133 return NULL;
6134 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006135 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006136 return NULL;
6137 kind = PyUnicode_KIND(unicode);
6138 data = PyUnicode_DATA(unicode);
6139 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006140 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6141 bytes, and 1 byte characters 4. */
6142 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006143
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006144 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006146
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148 if (repr == NULL)
6149 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006151 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006153 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154 for (pos = 0; pos < len; pos++) {
6155 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 /* Map 32-bit characters to '\Uxxxxxxxx' */
6157 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006158 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006159 *p++ = '\\';
6160 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006161 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6162 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6163 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6164 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6165 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6166 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6167 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6168 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006169 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006170 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006172 *p++ = '\\';
6173 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006174 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6175 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6176 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6177 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 /* Copy everything else as-is */
6180 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181 *p++ = (char) ch;
6182 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006183
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006184 assert(p > q);
6185 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006186 return NULL;
6187 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188}
6189
Alexander Belopolsky40018472011-02-26 01:02:56 +00006190PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6192 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006194 PyObject *result;
6195 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6196 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006197 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006198 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6199 Py_DECREF(tmp);
6200 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006201}
6202
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006203/* --- Unicode Internal Codec ------------------------------------------- */
6204
Alexander Belopolsky40018472011-02-26 01:02:56 +00006205PyObject *
6206_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006207 Py_ssize_t size,
6208 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006209{
6210 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006211 Py_ssize_t startinpos;
6212 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006213 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006214 const char *end;
6215 const char *reason;
6216 PyObject *errorHandler = NULL;
6217 PyObject *exc = NULL;
6218
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006219 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006220 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006221 1))
6222 return NULL;
6223
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006224 if (size == 0)
6225 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006226
Victor Stinner8f674cc2013-04-17 23:02:17 +02006227 _PyUnicodeWriter_Init(&writer);
6228 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6229 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006231 }
6232 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006233
Victor Stinner8f674cc2013-04-17 23:02:17 +02006234 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006235 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006236 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006237 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006238 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006239 endinpos = end-starts;
6240 reason = "truncated input";
6241 goto error;
6242 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006243 /* We copy the raw representation one byte at a time because the
6244 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006245 ((char *) &uch)[0] = s[0];
6246 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006247#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006248 ((char *) &uch)[2] = s[2];
6249 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006250#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006251 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006252#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006253 /* We have to sanity check the raw data, otherwise doom looms for
6254 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006255 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006256 endinpos = s - starts + Py_UNICODE_SIZE;
6257 reason = "illegal code point (> 0x10FFFF)";
6258 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006259 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006260#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006261 s += Py_UNICODE_SIZE;
6262#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006263 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006264 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006265 Py_UNICODE uch2;
6266 ((char *) &uch2)[0] = s[0];
6267 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006268 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006269 {
Victor Stinner551ac952011-11-29 22:58:13 +01006270 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006271 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006272 }
6273 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006274#endif
6275
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006276 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006277 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006278 continue;
6279
6280 error:
6281 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006282 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006283 errors, &errorHandler,
6284 "unicode_internal", reason,
6285 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006286 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006287 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006288 }
6289
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006290 Py_XDECREF(errorHandler);
6291 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006292 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293
Benjamin Peterson29060642009-01-31 22:14:21 +00006294 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006295 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 Py_XDECREF(errorHandler);
6297 Py_XDECREF(exc);
6298 return NULL;
6299}
6300
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301/* --- Latin-1 Codec ------------------------------------------------------ */
6302
Alexander Belopolsky40018472011-02-26 01:02:56 +00006303PyObject *
6304PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006305 Py_ssize_t size,
6306 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006309 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310}
6311
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006313static void
6314make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006315 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006316 PyObject *unicode,
6317 Py_ssize_t startpos, Py_ssize_t endpos,
6318 const char *reason)
6319{
6320 if (*exceptionObject == NULL) {
6321 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006322 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006323 encoding, unicode, startpos, endpos, reason);
6324 }
6325 else {
6326 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6327 goto onError;
6328 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6329 goto onError;
6330 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6331 goto onError;
6332 return;
6333 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006334 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006335 }
6336}
6337
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006338/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006339static void
6340raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006341 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006342 PyObject *unicode,
6343 Py_ssize_t startpos, Py_ssize_t endpos,
6344 const char *reason)
6345{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006346 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006347 encoding, unicode, startpos, endpos, reason);
6348 if (*exceptionObject != NULL)
6349 PyCodec_StrictErrors(*exceptionObject);
6350}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006351
6352/* error handling callback helper:
6353 build arguments, call the callback and check the arguments,
6354 put the result into newpos and return the replacement string, which
6355 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006356static PyObject *
6357unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006358 PyObject **errorHandler,
6359 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006360 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006361 Py_ssize_t startpos, Py_ssize_t endpos,
6362 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006363{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006364 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006365 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366 PyObject *restuple;
6367 PyObject *resunicode;
6368
6369 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006372 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 }
6374
Benjamin Petersonbac79492012-01-14 13:34:47 -05006375 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006376 return NULL;
6377 len = PyUnicode_GET_LENGTH(unicode);
6378
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006379 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006380 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006382 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006383
6384 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006385 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006389 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 Py_DECREF(restuple);
6391 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006392 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006393 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006394 &resunicode, newpos)) {
6395 Py_DECREF(restuple);
6396 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006398 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6399 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6400 Py_DECREF(restuple);
6401 return NULL;
6402 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006403 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006404 *newpos = len + *newpos;
6405 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006406 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006407 Py_DECREF(restuple);
6408 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006409 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006410 Py_INCREF(resunicode);
6411 Py_DECREF(restuple);
6412 return resunicode;
6413}
6414
Alexander Belopolsky40018472011-02-26 01:02:56 +00006415static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006416unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006417 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006418 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 /* input state */
6421 Py_ssize_t pos=0, size;
6422 int kind;
6423 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 /* output object */
6425 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 /* pointer into the output */
6427 char *str;
6428 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006429 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006430 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6431 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006432 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006434 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435
Benjamin Petersonbac79492012-01-14 13:34:47 -05006436 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006437 return NULL;
6438 size = PyUnicode_GET_LENGTH(unicode);
6439 kind = PyUnicode_KIND(unicode);
6440 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 /* allocate enough for a simple encoding without
6442 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006443 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006444 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006445 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006446 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006447 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006448 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 ressize = size;
6450
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006451 while (pos < size) {
6452 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453
Benjamin Peterson29060642009-01-31 22:14:21 +00006454 /* can we encode this? */
6455 if (c<limit) {
6456 /* no overflow check, because we know that the space is enough */
6457 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006458 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006460 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 Py_ssize_t requiredsize;
6462 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006465 Py_ssize_t collstart = pos;
6466 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006468
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006469 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006471
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006473 if (error_handler == _Py_ERROR_UNKNOWN)
6474 error_handler = get_error_handler(errors);
6475
6476 switch (error_handler) {
6477 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006478 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006480
6481 case _Py_ERROR_REPLACE:
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006482 while (collstart++ < collend)
Victor Stinner50149202015-09-22 00:26:54 +02006483 *str++ = '?';
6484 /* fall through */
6485 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006486 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 break;
Victor Stinner50149202015-09-22 00:26:54 +02006488
6489 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006491 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006492 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006493 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006494 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006495 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006497 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006498 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006499 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006500 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006501 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006503 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006505 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006507 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006508 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006509 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006510 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006511 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006512 if (requiredsize > PY_SSIZE_T_MAX - incr)
6513 goto overflow;
6514 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006516 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6517 goto overflow;
6518 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006520 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 requiredsize = 2*ressize;
6522 if (_PyBytes_Resize(&res, requiredsize))
6523 goto onError;
6524 str = PyBytes_AS_STRING(res) + respos;
6525 ressize = requiredsize;
6526 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 /* generate replacement */
6528 for (i = collstart; i < collend; ++i) {
6529 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006530 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 break;
Victor Stinner50149202015-09-22 00:26:54 +02006533
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 default:
Victor Stinner50149202015-09-22 00:26:54 +02006535 repunicode = unicode_encode_call_errorhandler(errors, &error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 encoding, reason, unicode, &exc,
6537 collstart, collend, &newpos);
6538 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006539 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006541 if (PyBytes_Check(repunicode)) {
6542 /* Directly copy bytes result to output. */
6543 repsize = PyBytes_Size(repunicode);
6544 if (repsize > 1) {
6545 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006546 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006547 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6548 Py_DECREF(repunicode);
6549 goto overflow;
6550 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006551 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6552 Py_DECREF(repunicode);
6553 goto onError;
6554 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006555 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006556 ressize += repsize-1;
6557 }
6558 memcpy(str, PyBytes_AsString(repunicode), repsize);
6559 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006560 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006561 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006562 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006563 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 /* need more space? (at least enough for what we
6565 have+the replacement+the rest of the string, so
6566 we won't have to check space for encodable characters) */
6567 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006568 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006569 requiredsize = respos;
6570 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6571 goto overflow;
6572 requiredsize += repsize;
6573 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6574 goto overflow;
6575 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006577 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 requiredsize = 2*ressize;
6579 if (_PyBytes_Resize(&res, requiredsize)) {
6580 Py_DECREF(repunicode);
6581 goto onError;
6582 }
6583 str = PyBytes_AS_STRING(res) + respos;
6584 ressize = requiredsize;
6585 }
6586 /* check if there is anything unencodable in the replacement
6587 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006588 for (i = 0; repsize-->0; ++i, ++str) {
6589 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006591 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 Py_DECREF(repunicode);
6594 goto onError;
6595 }
6596 *str = (char)c;
6597 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006599 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006600 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006601 }
6602 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006603 /* Resize if we allocated to much */
6604 size = str - PyBytes_AS_STRING(res);
6605 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006606 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006607 if (_PyBytes_Resize(&res, size) < 0)
6608 goto onError;
6609 }
6610
Victor Stinner50149202015-09-22 00:26:54 +02006611 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006612 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006613 return res;
6614
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006615 overflow:
6616 PyErr_SetString(PyExc_OverflowError,
6617 "encoded result is too long for a Python string");
6618
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006619 onError:
6620 Py_XDECREF(res);
Victor Stinner50149202015-09-22 00:26:54 +02006621 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006622 Py_XDECREF(exc);
6623 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006624}
6625
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006626/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006627PyObject *
6628PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006629 Py_ssize_t size,
6630 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006632 PyObject *result;
6633 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6634 if (unicode == NULL)
6635 return NULL;
6636 result = unicode_encode_ucs1(unicode, errors, 256);
6637 Py_DECREF(unicode);
6638 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006639}
6640
Alexander Belopolsky40018472011-02-26 01:02:56 +00006641PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006642_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643{
6644 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 PyErr_BadArgument();
6646 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006647 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006648 if (PyUnicode_READY(unicode) == -1)
6649 return NULL;
6650 /* Fast path: if it is a one-byte string, construct
6651 bytes object directly. */
6652 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6653 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6654 PyUnicode_GET_LENGTH(unicode));
6655 /* Non-Latin-1 characters present. Defer to above function to
6656 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006658}
6659
6660PyObject*
6661PyUnicode_AsLatin1String(PyObject *unicode)
6662{
6663 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006664}
6665
6666/* --- 7-bit ASCII Codec -------------------------------------------------- */
6667
Alexander Belopolsky40018472011-02-26 01:02:56 +00006668PyObject *
6669PyUnicode_DecodeASCII(const char *s,
6670 Py_ssize_t size,
6671 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006672{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006674 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006675 int kind;
6676 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006677 Py_ssize_t startinpos;
6678 Py_ssize_t endinpos;
6679 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006681 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006683 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006684
Guido van Rossumd57fd912000-03-10 22:53:23 +00006685 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006686 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006687
Guido van Rossumd57fd912000-03-10 22:53:23 +00006688 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006689 if (size == 1 && (unsigned char)s[0] < 128)
6690 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006691
Victor Stinner8f674cc2013-04-17 23:02:17 +02006692 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006693 writer.min_length = size;
6694 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006695 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006696
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006698 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006699 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006700 writer.pos = outpos;
6701 if (writer.pos == size)
6702 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006703
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006704 s += writer.pos;
6705 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006707 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006709 PyUnicode_WRITE(kind, data, writer.pos, c);
6710 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006712 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006714
6715 /* byte outsize range 0x00..0x7f: call the error handler */
6716
6717 if (error_handler == _Py_ERROR_UNKNOWN)
6718 error_handler = get_error_handler(errors);
6719
6720 switch (error_handler)
6721 {
6722 case _Py_ERROR_REPLACE:
6723 case _Py_ERROR_SURROGATEESCAPE:
6724 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006725 but we may switch to UCS2 at the first write */
6726 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6727 goto onError;
6728 kind = writer.kind;
6729 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006730
6731 if (error_handler == _Py_ERROR_REPLACE)
6732 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6733 else
6734 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6735 writer.pos++;
6736 ++s;
6737 break;
6738
6739 case _Py_ERROR_IGNORE:
6740 ++s;
6741 break;
6742
6743 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 startinpos = s-starts;
6745 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006746 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006747 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 "ascii", "ordinal not in range(128)",
6749 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006750 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006752 kind = writer.kind;
6753 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006755 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006756 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006757 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006758 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006759
Benjamin Peterson29060642009-01-31 22:14:21 +00006760 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006761 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006762 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006763 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764 return NULL;
6765}
6766
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006767/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006768PyObject *
6769PyUnicode_EncodeASCII(const Py_UNICODE *p,
6770 Py_ssize_t size,
6771 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006773 PyObject *result;
6774 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6775 if (unicode == NULL)
6776 return NULL;
6777 result = unicode_encode_ucs1(unicode, errors, 128);
6778 Py_DECREF(unicode);
6779 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006780}
6781
Alexander Belopolsky40018472011-02-26 01:02:56 +00006782PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006783_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784{
6785 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006786 PyErr_BadArgument();
6787 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006789 if (PyUnicode_READY(unicode) == -1)
6790 return NULL;
6791 /* Fast path: if it is an ASCII-only string, construct bytes object
6792 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006793 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006794 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6795 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006796 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006797}
6798
6799PyObject *
6800PyUnicode_AsASCIIString(PyObject *unicode)
6801{
6802 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006803}
6804
Victor Stinner99b95382011-07-04 14:23:54 +02006805#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006806
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006807/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006808
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006809#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006810#define NEED_RETRY
6811#endif
6812
Victor Stinner3a50e702011-10-18 21:21:00 +02006813#ifndef WC_ERR_INVALID_CHARS
6814# define WC_ERR_INVALID_CHARS 0x0080
6815#endif
6816
6817static char*
6818code_page_name(UINT code_page, PyObject **obj)
6819{
6820 *obj = NULL;
6821 if (code_page == CP_ACP)
6822 return "mbcs";
6823 if (code_page == CP_UTF7)
6824 return "CP_UTF7";
6825 if (code_page == CP_UTF8)
6826 return "CP_UTF8";
6827
6828 *obj = PyBytes_FromFormat("cp%u", code_page);
6829 if (*obj == NULL)
6830 return NULL;
6831 return PyBytes_AS_STRING(*obj);
6832}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006833
Victor Stinner3a50e702011-10-18 21:21:00 +02006834static DWORD
6835decode_code_page_flags(UINT code_page)
6836{
6837 if (code_page == CP_UTF7) {
6838 /* The CP_UTF7 decoder only supports flags=0 */
6839 return 0;
6840 }
6841 else
6842 return MB_ERR_INVALID_CHARS;
6843}
6844
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006845/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006846 * Decode a byte string from a Windows code page into unicode object in strict
6847 * mode.
6848 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006849 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6850 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006851 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006852static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006853decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006854 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006855 const char *in,
6856 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857{
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006859 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006860 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006861
6862 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006863 assert(insize > 0);
6864 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6865 if (outsize <= 0)
6866 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006867
6868 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006869 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006870 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006871 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006872 if (*v == NULL)
6873 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006874 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875 }
6876 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006877 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006878 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006879 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006881 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006882 }
6883
6884 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6886 if (outsize <= 0)
6887 goto error;
6888 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006889
Victor Stinner3a50e702011-10-18 21:21:00 +02006890error:
6891 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6892 return -2;
6893 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006894 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006895}
6896
Victor Stinner3a50e702011-10-18 21:21:00 +02006897/*
6898 * Decode a byte string from a code page into unicode object with an error
6899 * handler.
6900 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006901 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 * UnicodeDecodeError exception and returns -1 on error.
6903 */
6904static int
6905decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006906 PyObject **v,
6907 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006908 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006909{
6910 const char *startin = in;
6911 const char *endin = in + size;
6912 const DWORD flags = decode_code_page_flags(code_page);
6913 /* Ideally, we should get reason from FormatMessage. This is the Windows
6914 2000 English version of the message. */
6915 const char *reason = "No mapping for the Unicode character exists "
6916 "in the target code page.";
6917 /* each step cannot decode more than 1 character, but a character can be
6918 represented as a surrogate pair */
6919 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006920 int insize;
6921 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006922 PyObject *errorHandler = NULL;
6923 PyObject *exc = NULL;
6924 PyObject *encoding_obj = NULL;
6925 char *encoding;
6926 DWORD err;
6927 int ret = -1;
6928
6929 assert(size > 0);
6930
6931 encoding = code_page_name(code_page, &encoding_obj);
6932 if (encoding == NULL)
6933 return -1;
6934
Victor Stinner7d00cc12014-03-17 23:08:06 +01006935 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006936 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6937 UnicodeDecodeError. */
6938 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6939 if (exc != NULL) {
6940 PyCodec_StrictErrors(exc);
6941 Py_CLEAR(exc);
6942 }
6943 goto error;
6944 }
6945
6946 if (*v == NULL) {
6947 /* Create unicode object */
6948 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6949 PyErr_NoMemory();
6950 goto error;
6951 }
Victor Stinnerab595942011-12-17 04:59:06 +01006952 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006953 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006954 if (*v == NULL)
6955 goto error;
6956 startout = PyUnicode_AS_UNICODE(*v);
6957 }
6958 else {
6959 /* Extend unicode object */
6960 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6961 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6962 PyErr_NoMemory();
6963 goto error;
6964 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006965 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006966 goto error;
6967 startout = PyUnicode_AS_UNICODE(*v) + n;
6968 }
6969
6970 /* Decode the byte string character per character */
6971 out = startout;
6972 while (in < endin)
6973 {
6974 /* Decode a character */
6975 insize = 1;
6976 do
6977 {
6978 outsize = MultiByteToWideChar(code_page, flags,
6979 in, insize,
6980 buffer, Py_ARRAY_LENGTH(buffer));
6981 if (outsize > 0)
6982 break;
6983 err = GetLastError();
6984 if (err != ERROR_NO_UNICODE_TRANSLATION
6985 && err != ERROR_INSUFFICIENT_BUFFER)
6986 {
6987 PyErr_SetFromWindowsErr(0);
6988 goto error;
6989 }
6990 insize++;
6991 }
6992 /* 4=maximum length of a UTF-8 sequence */
6993 while (insize <= 4 && (in + insize) <= endin);
6994
6995 if (outsize <= 0) {
6996 Py_ssize_t startinpos, endinpos, outpos;
6997
Victor Stinner7d00cc12014-03-17 23:08:06 +01006998 /* last character in partial decode? */
6999 if (in + insize >= endin && !final)
7000 break;
7001
Victor Stinner3a50e702011-10-18 21:21:00 +02007002 startinpos = in - startin;
7003 endinpos = startinpos + 1;
7004 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007005 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007006 errors, &errorHandler,
7007 encoding, reason,
7008 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007009 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007010 {
7011 goto error;
7012 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007013 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007014 }
7015 else {
7016 in += insize;
7017 memcpy(out, buffer, outsize * sizeof(wchar_t));
7018 out += outsize;
7019 }
7020 }
7021
7022 /* write a NUL character at the end */
7023 *out = 0;
7024
7025 /* Extend unicode object */
7026 outsize = out - startout;
7027 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007028 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007029 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007030 /* (in - startin) <= size and size is an int */
7031 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007032
7033error:
7034 Py_XDECREF(encoding_obj);
7035 Py_XDECREF(errorHandler);
7036 Py_XDECREF(exc);
7037 return ret;
7038}
7039
Victor Stinner3a50e702011-10-18 21:21:00 +02007040static PyObject *
7041decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007042 const char *s, Py_ssize_t size,
7043 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007044{
Victor Stinner76a31a62011-11-04 00:05:13 +01007045 PyObject *v = NULL;
7046 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 if (code_page < 0) {
7049 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7050 return NULL;
7051 }
7052
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007054 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007055
Victor Stinner76a31a62011-11-04 00:05:13 +01007056 do
7057 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007058#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007059 if (size > INT_MAX) {
7060 chunk_size = INT_MAX;
7061 final = 0;
7062 done = 0;
7063 }
7064 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007066 {
7067 chunk_size = (int)size;
7068 final = (consumed == NULL);
7069 done = 1;
7070 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071
Victor Stinner76a31a62011-11-04 00:05:13 +01007072 if (chunk_size == 0 && done) {
7073 if (v != NULL)
7074 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007075 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007076 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077
Victor Stinner76a31a62011-11-04 00:05:13 +01007078 converted = decode_code_page_strict(code_page, &v,
7079 s, chunk_size);
7080 if (converted == -2)
7081 converted = decode_code_page_errors(code_page, &v,
7082 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007083 errors, final);
7084 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007085
7086 if (converted < 0) {
7087 Py_XDECREF(v);
7088 return NULL;
7089 }
7090
7091 if (consumed)
7092 *consumed += converted;
7093
7094 s += converted;
7095 size -= converted;
7096 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007097
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007098 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007099}
7100
Alexander Belopolsky40018472011-02-26 01:02:56 +00007101PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007102PyUnicode_DecodeCodePageStateful(int code_page,
7103 const char *s,
7104 Py_ssize_t size,
7105 const char *errors,
7106 Py_ssize_t *consumed)
7107{
7108 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7109}
7110
7111PyObject *
7112PyUnicode_DecodeMBCSStateful(const char *s,
7113 Py_ssize_t size,
7114 const char *errors,
7115 Py_ssize_t *consumed)
7116{
7117 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7118}
7119
7120PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007121PyUnicode_DecodeMBCS(const char *s,
7122 Py_ssize_t size,
7123 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007124{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007125 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7126}
7127
Victor Stinner3a50e702011-10-18 21:21:00 +02007128static DWORD
7129encode_code_page_flags(UINT code_page, const char *errors)
7130{
7131 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007132 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007133 }
7134 else if (code_page == CP_UTF7) {
7135 /* CP_UTF7 only supports flags=0 */
7136 return 0;
7137 }
7138 else {
7139 if (errors != NULL && strcmp(errors, "replace") == 0)
7140 return 0;
7141 else
7142 return WC_NO_BEST_FIT_CHARS;
7143 }
7144}
7145
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007146/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 * Encode a Unicode string to a Windows code page into a byte string in strict
7148 * mode.
7149 *
7150 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007151 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007152 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007153static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007154encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007155 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007157{
Victor Stinner554f3f02010-06-16 23:33:54 +00007158 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 BOOL *pusedDefaultChar = &usedDefaultChar;
7160 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007161 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007162 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007163 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007164 const DWORD flags = encode_code_page_flags(code_page, NULL);
7165 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007166 /* Create a substring so that we can get the UTF-16 representation
7167 of just the slice under consideration. */
7168 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007169
Martin v. Löwis3d325192011-11-04 18:23:06 +01007170 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007171
Victor Stinner3a50e702011-10-18 21:21:00 +02007172 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007173 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007175 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007176
Victor Stinner2fc507f2011-11-04 20:06:39 +01007177 substring = PyUnicode_Substring(unicode, offset, offset+len);
7178 if (substring == NULL)
7179 return -1;
7180 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7181 if (p == NULL) {
7182 Py_DECREF(substring);
7183 return -1;
7184 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007185 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007186
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007187 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007189 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 NULL, 0,
7191 NULL, pusedDefaultChar);
7192 if (outsize <= 0)
7193 goto error;
7194 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007195 if (pusedDefaultChar && *pusedDefaultChar) {
7196 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007198 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007199
Victor Stinner3a50e702011-10-18 21:21:00 +02007200 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007201 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007203 if (*outbytes == NULL) {
7204 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007205 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007206 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007208 }
7209 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007210 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007211 const Py_ssize_t n = PyBytes_Size(*outbytes);
7212 if (outsize > PY_SSIZE_T_MAX - n) {
7213 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007215 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7218 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007220 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007222 }
7223
7224 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007226 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 out, outsize,
7228 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007229 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 if (outsize <= 0)
7231 goto error;
7232 if (pusedDefaultChar && *pusedDefaultChar)
7233 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007234 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007235
Victor Stinner3a50e702011-10-18 21:21:00 +02007236error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7239 return -2;
7240 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007241 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007242}
7243
Victor Stinner3a50e702011-10-18 21:21:00 +02007244/*
7245 * Encode a Unicode string to a Windows code page into a byte string using a
7246 * error handler.
7247 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007248 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 * -1 on other error.
7250 */
7251static int
7252encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007253 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007254 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007255{
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007257 Py_ssize_t pos = unicode_offset;
7258 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 /* Ideally, we should get reason from FormatMessage. This is the Windows
7260 2000 English version of the message. */
7261 const char *reason = "invalid character";
7262 /* 4=maximum length of a UTF-8 sequence */
7263 char buffer[4];
7264 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7265 Py_ssize_t outsize;
7266 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 PyObject *errorHandler = NULL;
7268 PyObject *exc = NULL;
7269 PyObject *encoding_obj = NULL;
7270 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007271 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 PyObject *rep;
7273 int ret = -1;
7274
7275 assert(insize > 0);
7276
7277 encoding = code_page_name(code_page, &encoding_obj);
7278 if (encoding == NULL)
7279 return -1;
7280
7281 if (errors == NULL || strcmp(errors, "strict") == 0) {
7282 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7283 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007284 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007285 if (exc != NULL) {
7286 PyCodec_StrictErrors(exc);
7287 Py_DECREF(exc);
7288 }
7289 Py_XDECREF(encoding_obj);
7290 return -1;
7291 }
7292
7293 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7294 pusedDefaultChar = &usedDefaultChar;
7295 else
7296 pusedDefaultChar = NULL;
7297
7298 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7299 PyErr_NoMemory();
7300 goto error;
7301 }
7302 outsize = insize * Py_ARRAY_LENGTH(buffer);
7303
7304 if (*outbytes == NULL) {
7305 /* Create string object */
7306 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7307 if (*outbytes == NULL)
7308 goto error;
7309 out = PyBytes_AS_STRING(*outbytes);
7310 }
7311 else {
7312 /* Extend string object */
7313 Py_ssize_t n = PyBytes_Size(*outbytes);
7314 if (n > PY_SSIZE_T_MAX - outsize) {
7315 PyErr_NoMemory();
7316 goto error;
7317 }
7318 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7319 goto error;
7320 out = PyBytes_AS_STRING(*outbytes) + n;
7321 }
7322
7323 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007324 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007325 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007326 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7327 wchar_t chars[2];
7328 int charsize;
7329 if (ch < 0x10000) {
7330 chars[0] = (wchar_t)ch;
7331 charsize = 1;
7332 }
7333 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007334 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7335 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007336 charsize = 2;
7337 }
7338
Victor Stinner3a50e702011-10-18 21:21:00 +02007339 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 buffer, Py_ARRAY_LENGTH(buffer),
7342 NULL, pusedDefaultChar);
7343 if (outsize > 0) {
7344 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7345 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007346 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007347 memcpy(out, buffer, outsize);
7348 out += outsize;
7349 continue;
7350 }
7351 }
7352 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7353 PyErr_SetFromWindowsErr(0);
7354 goto error;
7355 }
7356
Victor Stinner3a50e702011-10-18 21:21:00 +02007357 rep = unicode_encode_call_errorhandler(
7358 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007359 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007360 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 if (rep == NULL)
7362 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007363 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007364
7365 if (PyBytes_Check(rep)) {
7366 outsize = PyBytes_GET_SIZE(rep);
7367 if (outsize != 1) {
7368 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7369 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7370 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7371 Py_DECREF(rep);
7372 goto error;
7373 }
7374 out = PyBytes_AS_STRING(*outbytes) + offset;
7375 }
7376 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7377 out += outsize;
7378 }
7379 else {
7380 Py_ssize_t i;
7381 enum PyUnicode_Kind kind;
7382 void *data;
7383
Benjamin Petersonbac79492012-01-14 13:34:47 -05007384 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 Py_DECREF(rep);
7386 goto error;
7387 }
7388
7389 outsize = PyUnicode_GET_LENGTH(rep);
7390 if (outsize != 1) {
7391 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7392 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7393 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7394 Py_DECREF(rep);
7395 goto error;
7396 }
7397 out = PyBytes_AS_STRING(*outbytes) + offset;
7398 }
7399 kind = PyUnicode_KIND(rep);
7400 data = PyUnicode_DATA(rep);
7401 for (i=0; i < outsize; i++) {
7402 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7403 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007404 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405 encoding, unicode,
7406 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 "unable to encode error handler result to ASCII");
7408 Py_DECREF(rep);
7409 goto error;
7410 }
7411 *out = (unsigned char)ch;
7412 out++;
7413 }
7414 }
7415 Py_DECREF(rep);
7416 }
7417 /* write a NUL byte */
7418 *out = 0;
7419 outsize = out - PyBytes_AS_STRING(*outbytes);
7420 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7421 if (_PyBytes_Resize(outbytes, outsize) < 0)
7422 goto error;
7423 ret = 0;
7424
7425error:
7426 Py_XDECREF(encoding_obj);
7427 Py_XDECREF(errorHandler);
7428 Py_XDECREF(exc);
7429 return ret;
7430}
7431
Victor Stinner3a50e702011-10-18 21:21:00 +02007432static PyObject *
7433encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007434 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 const char *errors)
7436{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007437 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007439 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007440 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007441
Victor Stinner29dacf22015-01-26 16:41:32 +01007442 if (!PyUnicode_Check(unicode)) {
7443 PyErr_BadArgument();
7444 return NULL;
7445 }
7446
Benjamin Petersonbac79492012-01-14 13:34:47 -05007447 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007448 return NULL;
7449 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007450
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 if (code_page < 0) {
7452 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7453 return NULL;
7454 }
7455
Martin v. Löwis3d325192011-11-04 18:23:06 +01007456 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007457 return PyBytes_FromStringAndSize(NULL, 0);
7458
Victor Stinner7581cef2011-11-03 22:32:33 +01007459 offset = 0;
7460 do
7461 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007462#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007464 chunks. */
7465 if (len > INT_MAX/2) {
7466 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007467 done = 0;
7468 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007469 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007470#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007471 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007473 done = 1;
7474 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475
Victor Stinner76a31a62011-11-04 00:05:13 +01007476 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007477 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007478 errors);
7479 if (ret == -2)
7480 ret = encode_code_page_errors(code_page, &outbytes,
7481 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007482 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007483 if (ret < 0) {
7484 Py_XDECREF(outbytes);
7485 return NULL;
7486 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007487
Victor Stinner7581cef2011-11-03 22:32:33 +01007488 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007490 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007491
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 return outbytes;
7493}
7494
7495PyObject *
7496PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7497 Py_ssize_t size,
7498 const char *errors)
7499{
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 PyObject *unicode, *res;
7501 unicode = PyUnicode_FromUnicode(p, size);
7502 if (unicode == NULL)
7503 return NULL;
7504 res = encode_code_page(CP_ACP, unicode, errors);
7505 Py_DECREF(unicode);
7506 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007507}
7508
7509PyObject *
7510PyUnicode_EncodeCodePage(int code_page,
7511 PyObject *unicode,
7512 const char *errors)
7513{
Victor Stinner7581cef2011-11-03 22:32:33 +01007514 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007515}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007516
Alexander Belopolsky40018472011-02-26 01:02:56 +00007517PyObject *
7518PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007519{
Victor Stinner7581cef2011-11-03 22:32:33 +01007520 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007521}
7522
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007523#undef NEED_RETRY
7524
Victor Stinner99b95382011-07-04 14:23:54 +02007525#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007526
Guido van Rossumd57fd912000-03-10 22:53:23 +00007527/* --- Character Mapping Codec -------------------------------------------- */
7528
Victor Stinnerfb161b12013-04-18 01:44:27 +02007529static int
7530charmap_decode_string(const char *s,
7531 Py_ssize_t size,
7532 PyObject *mapping,
7533 const char *errors,
7534 _PyUnicodeWriter *writer)
7535{
7536 const char *starts = s;
7537 const char *e;
7538 Py_ssize_t startinpos, endinpos;
7539 PyObject *errorHandler = NULL, *exc = NULL;
7540 Py_ssize_t maplen;
7541 enum PyUnicode_Kind mapkind;
7542 void *mapdata;
7543 Py_UCS4 x;
7544 unsigned char ch;
7545
7546 if (PyUnicode_READY(mapping) == -1)
7547 return -1;
7548
7549 maplen = PyUnicode_GET_LENGTH(mapping);
7550 mapdata = PyUnicode_DATA(mapping);
7551 mapkind = PyUnicode_KIND(mapping);
7552
7553 e = s + size;
7554
7555 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7556 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7557 * is disabled in encoding aliases, latin1 is preferred because
7558 * its implementation is faster. */
7559 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7560 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7561 Py_UCS4 maxchar = writer->maxchar;
7562
7563 assert (writer->kind == PyUnicode_1BYTE_KIND);
7564 while (s < e) {
7565 ch = *s;
7566 x = mapdata_ucs1[ch];
7567 if (x > maxchar) {
7568 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7569 goto onError;
7570 maxchar = writer->maxchar;
7571 outdata = (Py_UCS1 *)writer->data;
7572 }
7573 outdata[writer->pos] = x;
7574 writer->pos++;
7575 ++s;
7576 }
7577 return 0;
7578 }
7579
7580 while (s < e) {
7581 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7582 enum PyUnicode_Kind outkind = writer->kind;
7583 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7584 if (outkind == PyUnicode_1BYTE_KIND) {
7585 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7586 Py_UCS4 maxchar = writer->maxchar;
7587 while (s < e) {
7588 ch = *s;
7589 x = mapdata_ucs2[ch];
7590 if (x > maxchar)
7591 goto Error;
7592 outdata[writer->pos] = x;
7593 writer->pos++;
7594 ++s;
7595 }
7596 break;
7597 }
7598 else if (outkind == PyUnicode_2BYTE_KIND) {
7599 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7600 while (s < e) {
7601 ch = *s;
7602 x = mapdata_ucs2[ch];
7603 if (x == 0xFFFE)
7604 goto Error;
7605 outdata[writer->pos] = x;
7606 writer->pos++;
7607 ++s;
7608 }
7609 break;
7610 }
7611 }
7612 ch = *s;
7613
7614 if (ch < maplen)
7615 x = PyUnicode_READ(mapkind, mapdata, ch);
7616 else
7617 x = 0xfffe; /* invalid value */
7618Error:
7619 if (x == 0xfffe)
7620 {
7621 /* undefined mapping */
7622 startinpos = s-starts;
7623 endinpos = startinpos+1;
7624 if (unicode_decode_call_errorhandler_writer(
7625 errors, &errorHandler,
7626 "charmap", "character maps to <undefined>",
7627 &starts, &e, &startinpos, &endinpos, &exc, &s,
7628 writer)) {
7629 goto onError;
7630 }
7631 continue;
7632 }
7633
7634 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7635 goto onError;
7636 ++s;
7637 }
7638 Py_XDECREF(errorHandler);
7639 Py_XDECREF(exc);
7640 return 0;
7641
7642onError:
7643 Py_XDECREF(errorHandler);
7644 Py_XDECREF(exc);
7645 return -1;
7646}
7647
7648static int
7649charmap_decode_mapping(const char *s,
7650 Py_ssize_t size,
7651 PyObject *mapping,
7652 const char *errors,
7653 _PyUnicodeWriter *writer)
7654{
7655 const char *starts = s;
7656 const char *e;
7657 Py_ssize_t startinpos, endinpos;
7658 PyObject *errorHandler = NULL, *exc = NULL;
7659 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007660 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007661
7662 e = s + size;
7663
7664 while (s < e) {
7665 ch = *s;
7666
7667 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7668 key = PyLong_FromLong((long)ch);
7669 if (key == NULL)
7670 goto onError;
7671
7672 item = PyObject_GetItem(mapping, key);
7673 Py_DECREF(key);
7674 if (item == NULL) {
7675 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7676 /* No mapping found means: mapping is undefined. */
7677 PyErr_Clear();
7678 goto Undefined;
7679 } else
7680 goto onError;
7681 }
7682
7683 /* Apply mapping */
7684 if (item == Py_None)
7685 goto Undefined;
7686 if (PyLong_Check(item)) {
7687 long value = PyLong_AS_LONG(item);
7688 if (value == 0xFFFE)
7689 goto Undefined;
7690 if (value < 0 || value > MAX_UNICODE) {
7691 PyErr_Format(PyExc_TypeError,
7692 "character mapping must be in range(0x%lx)",
7693 (unsigned long)MAX_UNICODE + 1);
7694 goto onError;
7695 }
7696
7697 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7698 goto onError;
7699 }
7700 else if (PyUnicode_Check(item)) {
7701 if (PyUnicode_READY(item) == -1)
7702 goto onError;
7703 if (PyUnicode_GET_LENGTH(item) == 1) {
7704 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7705 if (value == 0xFFFE)
7706 goto Undefined;
7707 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7708 goto onError;
7709 }
7710 else {
7711 writer->overallocate = 1;
7712 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7713 goto onError;
7714 }
7715 }
7716 else {
7717 /* wrong return value */
7718 PyErr_SetString(PyExc_TypeError,
7719 "character mapping must return integer, None or str");
7720 goto onError;
7721 }
7722 Py_CLEAR(item);
7723 ++s;
7724 continue;
7725
7726Undefined:
7727 /* undefined mapping */
7728 Py_CLEAR(item);
7729 startinpos = s-starts;
7730 endinpos = startinpos+1;
7731 if (unicode_decode_call_errorhandler_writer(
7732 errors, &errorHandler,
7733 "charmap", "character maps to <undefined>",
7734 &starts, &e, &startinpos, &endinpos, &exc, &s,
7735 writer)) {
7736 goto onError;
7737 }
7738 }
7739 Py_XDECREF(errorHandler);
7740 Py_XDECREF(exc);
7741 return 0;
7742
7743onError:
7744 Py_XDECREF(item);
7745 Py_XDECREF(errorHandler);
7746 Py_XDECREF(exc);
7747 return -1;
7748}
7749
Alexander Belopolsky40018472011-02-26 01:02:56 +00007750PyObject *
7751PyUnicode_DecodeCharmap(const char *s,
7752 Py_ssize_t size,
7753 PyObject *mapping,
7754 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007756 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007757
Guido van Rossumd57fd912000-03-10 22:53:23 +00007758 /* Default to Latin-1 */
7759 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007763 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007764 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007765 writer.min_length = size;
7766 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007768
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007769 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007770 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7771 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007772 }
7773 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007774 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7775 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007777 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007778
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007780 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781 return NULL;
7782}
7783
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007784/* Charmap encoding: the lookup table */
7785
Alexander Belopolsky40018472011-02-26 01:02:56 +00007786struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007787 PyObject_HEAD
7788 unsigned char level1[32];
7789 int count2, count3;
7790 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007791};
7792
7793static PyObject*
7794encoding_map_size(PyObject *obj, PyObject* args)
7795{
7796 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007797 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007799}
7800
7801static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007802 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007803 PyDoc_STR("Return the size (in bytes) of this object") },
7804 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007805};
7806
7807static void
7808encoding_map_dealloc(PyObject* o)
7809{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007810 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007811}
7812
7813static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007814 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007815 "EncodingMap", /*tp_name*/
7816 sizeof(struct encoding_map), /*tp_basicsize*/
7817 0, /*tp_itemsize*/
7818 /* methods */
7819 encoding_map_dealloc, /*tp_dealloc*/
7820 0, /*tp_print*/
7821 0, /*tp_getattr*/
7822 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007823 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 0, /*tp_repr*/
7825 0, /*tp_as_number*/
7826 0, /*tp_as_sequence*/
7827 0, /*tp_as_mapping*/
7828 0, /*tp_hash*/
7829 0, /*tp_call*/
7830 0, /*tp_str*/
7831 0, /*tp_getattro*/
7832 0, /*tp_setattro*/
7833 0, /*tp_as_buffer*/
7834 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7835 0, /*tp_doc*/
7836 0, /*tp_traverse*/
7837 0, /*tp_clear*/
7838 0, /*tp_richcompare*/
7839 0, /*tp_weaklistoffset*/
7840 0, /*tp_iter*/
7841 0, /*tp_iternext*/
7842 encoding_map_methods, /*tp_methods*/
7843 0, /*tp_members*/
7844 0, /*tp_getset*/
7845 0, /*tp_base*/
7846 0, /*tp_dict*/
7847 0, /*tp_descr_get*/
7848 0, /*tp_descr_set*/
7849 0, /*tp_dictoffset*/
7850 0, /*tp_init*/
7851 0, /*tp_alloc*/
7852 0, /*tp_new*/
7853 0, /*tp_free*/
7854 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007855};
7856
7857PyObject*
7858PyUnicode_BuildEncodingMap(PyObject* string)
7859{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007860 PyObject *result;
7861 struct encoding_map *mresult;
7862 int i;
7863 int need_dict = 0;
7864 unsigned char level1[32];
7865 unsigned char level2[512];
7866 unsigned char *mlevel1, *mlevel2, *mlevel3;
7867 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007868 int kind;
7869 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007870 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007871 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007872
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007873 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874 PyErr_BadArgument();
7875 return NULL;
7876 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007877 kind = PyUnicode_KIND(string);
7878 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007879 length = PyUnicode_GET_LENGTH(string);
7880 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007881 memset(level1, 0xFF, sizeof level1);
7882 memset(level2, 0xFF, sizeof level2);
7883
7884 /* If there isn't a one-to-one mapping of NULL to \0,
7885 or if there are non-BMP characters, we need to use
7886 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007887 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007888 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007889 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007890 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007891 ch = PyUnicode_READ(kind, data, i);
7892 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007893 need_dict = 1;
7894 break;
7895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007896 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 /* unmapped character */
7898 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007899 l1 = ch >> 11;
7900 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007901 if (level1[l1] == 0xFF)
7902 level1[l1] = count2++;
7903 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007904 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 }
7906
7907 if (count2 >= 0xFF || count3 >= 0xFF)
7908 need_dict = 1;
7909
7910 if (need_dict) {
7911 PyObject *result = PyDict_New();
7912 PyObject *key, *value;
7913 if (!result)
7914 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007915 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007916 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007917 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918 if (!key || !value)
7919 goto failed1;
7920 if (PyDict_SetItem(result, key, value) == -1)
7921 goto failed1;
7922 Py_DECREF(key);
7923 Py_DECREF(value);
7924 }
7925 return result;
7926 failed1:
7927 Py_XDECREF(key);
7928 Py_XDECREF(value);
7929 Py_DECREF(result);
7930 return NULL;
7931 }
7932
7933 /* Create a three-level trie */
7934 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7935 16*count2 + 128*count3 - 1);
7936 if (!result)
7937 return PyErr_NoMemory();
7938 PyObject_Init(result, &EncodingMapType);
7939 mresult = (struct encoding_map*)result;
7940 mresult->count2 = count2;
7941 mresult->count3 = count3;
7942 mlevel1 = mresult->level1;
7943 mlevel2 = mresult->level23;
7944 mlevel3 = mresult->level23 + 16*count2;
7945 memcpy(mlevel1, level1, 32);
7946 memset(mlevel2, 0xFF, 16*count2);
7947 memset(mlevel3, 0, 128*count3);
7948 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007949 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007951 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7952 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007953 /* unmapped character */
7954 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007955 o1 = ch>>11;
7956 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007957 i2 = 16*mlevel1[o1] + o2;
7958 if (mlevel2[i2] == 0xFF)
7959 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007960 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007961 i3 = 128*mlevel2[i2] + o3;
7962 mlevel3[i3] = i;
7963 }
7964 return result;
7965}
7966
7967static int
Victor Stinner22168992011-11-20 17:09:18 +01007968encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969{
7970 struct encoding_map *map = (struct encoding_map*)mapping;
7971 int l1 = c>>11;
7972 int l2 = (c>>7) & 0xF;
7973 int l3 = c & 0x7F;
7974 int i;
7975
Victor Stinner22168992011-11-20 17:09:18 +01007976 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007978 if (c == 0)
7979 return 0;
7980 /* level 1*/
7981 i = map->level1[l1];
7982 if (i == 0xFF) {
7983 return -1;
7984 }
7985 /* level 2*/
7986 i = map->level23[16*i+l2];
7987 if (i == 0xFF) {
7988 return -1;
7989 }
7990 /* level 3 */
7991 i = map->level23[16*map->count2 + 128*i + l3];
7992 if (i == 0) {
7993 return -1;
7994 }
7995 return i;
7996}
7997
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007998/* Lookup the character ch in the mapping. If the character
7999 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008000 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008001static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008002charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008003{
Christian Heimes217cfd12007-12-02 14:31:20 +00008004 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008005 PyObject *x;
8006
8007 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008009 x = PyObject_GetItem(mapping, w);
8010 Py_DECREF(w);
8011 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008012 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8013 /* No mapping found means: mapping is undefined. */
8014 PyErr_Clear();
8015 x = Py_None;
8016 Py_INCREF(x);
8017 return x;
8018 } else
8019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008020 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008021 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008023 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 long value = PyLong_AS_LONG(x);
8025 if (value < 0 || value > 255) {
8026 PyErr_SetString(PyExc_TypeError,
8027 "character mapping must be in range(256)");
8028 Py_DECREF(x);
8029 return NULL;
8030 }
8031 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008032 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008033 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008034 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008035 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 /* wrong return value */
8037 PyErr_Format(PyExc_TypeError,
8038 "character mapping must return integer, bytes or None, not %.400s",
8039 x->ob_type->tp_name);
8040 Py_DECREF(x);
8041 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008042 }
8043}
8044
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008046charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008048 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8049 /* exponentially overallocate to minimize reallocations */
8050 if (requiredsize < 2*outsize)
8051 requiredsize = 2*outsize;
8052 if (_PyBytes_Resize(outobj, requiredsize))
8053 return -1;
8054 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055}
8056
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008059} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008060/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008061 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062 space is available. Return a new reference to the object that
8063 was put in the output buffer, or Py_None, if the mapping was undefined
8064 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008065 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008066static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008067charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008068 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008069{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070 PyObject *rep;
8071 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008072 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008073
Christian Heimes90aa7642007-12-19 02:45:37 +00008074 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008075 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008077 if (res == -1)
8078 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008079 if (outsize<requiredsize)
8080 if (charmapencode_resize(outobj, outpos, requiredsize))
8081 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008082 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 outstart[(*outpos)++] = (char)res;
8084 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085 }
8086
8087 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008088 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 Py_DECREF(rep);
8092 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 if (PyLong_Check(rep)) {
8095 Py_ssize_t requiredsize = *outpos+1;
8096 if (outsize<requiredsize)
8097 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8098 Py_DECREF(rep);
8099 return enc_EXCEPTION;
8100 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008101 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008103 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 else {
8105 const char *repchars = PyBytes_AS_STRING(rep);
8106 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8107 Py_ssize_t requiredsize = *outpos+repsize;
8108 if (outsize<requiredsize)
8109 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8110 Py_DECREF(rep);
8111 return enc_EXCEPTION;
8112 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008113 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008114 memcpy(outstart + *outpos, repchars, repsize);
8115 *outpos += repsize;
8116 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118 Py_DECREF(rep);
8119 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120}
8121
8122/* handle an error in PyUnicode_EncodeCharmap
8123 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008124static int
8125charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008126 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008127 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008128 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008129 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130{
8131 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008132 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008133 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008134 enum PyUnicode_Kind kind;
8135 void *data;
8136 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008137 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008138 Py_ssize_t collstartpos = *inpos;
8139 Py_ssize_t collendpos = *inpos+1;
8140 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141 char *encoding = "charmap";
8142 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008144 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008145 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146
Benjamin Petersonbac79492012-01-14 13:34:47 -05008147 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008148 return -1;
8149 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008150 /* find all unencodable characters */
8151 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008152 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008153 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008154 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008155 val = encoding_map_lookup(ch, mapping);
8156 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 break;
8158 ++collendpos;
8159 continue;
8160 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008161
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008162 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8163 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 if (rep==NULL)
8165 return -1;
8166 else if (rep!=Py_None) {
8167 Py_DECREF(rep);
8168 break;
8169 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008170 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172 }
8173 /* cache callback name lookup
8174 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008175 if (*error_handler == _Py_ERROR_UNKNOWN)
8176 *error_handler = get_error_handler(errors);
8177
8178 switch (*error_handler) {
8179 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008180 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008181 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008182
8183 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008184 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 x = charmapencode_output('?', mapping, res, respos);
8186 if (x==enc_EXCEPTION) {
8187 return -1;
8188 }
8189 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008190 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 return -1;
8192 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008193 }
8194 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008195 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008196 *inpos = collendpos;
8197 break;
Victor Stinner50149202015-09-22 00:26:54 +02008198
8199 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008200 /* generate replacement (temporarily (mis)uses p) */
8201 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 char buffer[2+29+1+1];
8203 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008204 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008205 for (cp = buffer; *cp; ++cp) {
8206 x = charmapencode_output(*cp, mapping, res, respos);
8207 if (x==enc_EXCEPTION)
8208 return -1;
8209 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008210 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 return -1;
8212 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008213 }
8214 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008215 *inpos = collendpos;
8216 break;
Victor Stinner50149202015-09-22 00:26:54 +02008217
Benjamin Peterson14339b62009-01-31 16:36:08 +00008218 default:
Victor Stinner50149202015-09-22 00:26:54 +02008219 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008220 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008221 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008222 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008224 if (PyBytes_Check(repunicode)) {
8225 /* Directly copy bytes result to output. */
8226 Py_ssize_t outsize = PyBytes_Size(*res);
8227 Py_ssize_t requiredsize;
8228 repsize = PyBytes_Size(repunicode);
8229 requiredsize = *respos + repsize;
8230 if (requiredsize > outsize)
8231 /* Make room for all additional bytes. */
8232 if (charmapencode_resize(res, respos, requiredsize)) {
8233 Py_DECREF(repunicode);
8234 return -1;
8235 }
8236 memcpy(PyBytes_AsString(*res) + *respos,
8237 PyBytes_AsString(repunicode), repsize);
8238 *respos += repsize;
8239 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008240 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008241 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008242 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008243 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008244 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008245 Py_DECREF(repunicode);
8246 return -1;
8247 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008248 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008249 data = PyUnicode_DATA(repunicode);
8250 kind = PyUnicode_KIND(repunicode);
8251 for (index = 0; index < repsize; index++) {
8252 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8253 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008255 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 return -1;
8257 }
8258 else if (x==enc_FAILED) {
8259 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008260 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 return -1;
8262 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008263 }
8264 *inpos = newpos;
8265 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 }
8267 return 0;
8268}
8269
Alexander Belopolsky40018472011-02-26 01:02:56 +00008270PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008271_PyUnicode_EncodeCharmap(PyObject *unicode,
8272 PyObject *mapping,
8273 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008274{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008275 /* output object */
8276 PyObject *res = NULL;
8277 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008278 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008281 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008282 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008284 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008285 void *data;
8286 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287
Benjamin Petersonbac79492012-01-14 13:34:47 -05008288 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008289 return NULL;
8290 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008291 data = PyUnicode_DATA(unicode);
8292 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008293
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294 /* Default to Latin-1 */
8295 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008296 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008297
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298 /* allocate enough for a simple encoding without
8299 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008300 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008301 if (res == NULL)
8302 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008303 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008305
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008307 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008309 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 if (x==enc_EXCEPTION) /* error */
8311 goto onError;
8312 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008313 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008315 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 &res, &respos)) {
8317 goto onError;
8318 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008319 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 else
8321 /* done with this character => adjust input position */
8322 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008323 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008326 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008327 if (_PyBytes_Resize(&res, respos) < 0)
8328 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008329
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008331 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 return res;
8333
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 Py_XDECREF(res);
8336 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008337 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338 return NULL;
8339}
8340
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008341/* Deprecated */
8342PyObject *
8343PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8344 Py_ssize_t size,
8345 PyObject *mapping,
8346 const char *errors)
8347{
8348 PyObject *result;
8349 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8350 if (unicode == NULL)
8351 return NULL;
8352 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8353 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008354 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008355}
8356
Alexander Belopolsky40018472011-02-26 01:02:56 +00008357PyObject *
8358PyUnicode_AsCharmapString(PyObject *unicode,
8359 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008360{
8361 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 PyErr_BadArgument();
8363 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008364 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008365 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008366}
8367
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008369static void
8370make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008371 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008372 Py_ssize_t startpos, Py_ssize_t endpos,
8373 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008374{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008376 *exceptionObject = _PyUnicodeTranslateError_Create(
8377 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378 }
8379 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8381 goto onError;
8382 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8383 goto onError;
8384 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8385 goto onError;
8386 return;
8387 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008388 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008389 }
8390}
8391
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392/* error handling callback helper:
8393 build arguments, call the callback and check the arguments,
8394 put the result into newpos and return the replacement string, which
8395 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008396static PyObject *
8397unicode_translate_call_errorhandler(const char *errors,
8398 PyObject **errorHandler,
8399 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008400 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008401 Py_ssize_t startpos, Py_ssize_t endpos,
8402 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008404 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008406 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 PyObject *restuple;
8408 PyObject *resunicode;
8409
8410 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 }
8415
8416 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420
8421 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008426 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 Py_DECREF(restuple);
8428 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 }
8430 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 &resunicode, &i_newpos)) {
8432 Py_DECREF(restuple);
8433 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008435 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008436 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008437 else
8438 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008440 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 Py_DECREF(restuple);
8442 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008443 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 Py_INCREF(resunicode);
8445 Py_DECREF(restuple);
8446 return resunicode;
8447}
8448
8449/* Lookup the character ch in the mapping and put the result in result,
8450 which must be decrefed by the caller.
8451 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008452static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008453charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454{
Christian Heimes217cfd12007-12-02 14:31:20 +00008455 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456 PyObject *x;
8457
8458 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 x = PyObject_GetItem(mapping, w);
8461 Py_DECREF(w);
8462 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8464 /* No mapping found means: use 1:1 mapping. */
8465 PyErr_Clear();
8466 *result = NULL;
8467 return 0;
8468 } else
8469 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 }
8471 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 *result = x;
8473 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008475 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008477 if (value < 0 || value > MAX_UNICODE) {
8478 PyErr_Format(PyExc_ValueError,
8479 "character mapping must be in range(0x%x)",
8480 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 Py_DECREF(x);
8482 return -1;
8483 }
8484 *result = x;
8485 return 0;
8486 }
8487 else if (PyUnicode_Check(x)) {
8488 *result = x;
8489 return 0;
8490 }
8491 else {
8492 /* wrong return value */
8493 PyErr_SetString(PyExc_TypeError,
8494 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 Py_DECREF(x);
8496 return -1;
8497 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498}
Victor Stinner1194ea02014-04-04 19:37:40 +02008499
8500/* lookup the character, write the result into the writer.
8501 Return 1 if the result was written into the writer, return 0 if the mapping
8502 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008503static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008504charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8505 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506{
Victor Stinner1194ea02014-04-04 19:37:40 +02008507 PyObject *item;
8508
8509 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008511
8512 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008514 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008517 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008519
8520 if (item == Py_None) {
8521 Py_DECREF(item);
8522 return 0;
8523 }
8524
8525 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008526 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8527 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8528 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008529 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8530 Py_DECREF(item);
8531 return -1;
8532 }
8533 Py_DECREF(item);
8534 return 1;
8535 }
8536
8537 if (!PyUnicode_Check(item)) {
8538 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008540 }
8541
8542 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8543 Py_DECREF(item);
8544 return -1;
8545 }
8546
8547 Py_DECREF(item);
8548 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008549}
8550
Victor Stinner89a76ab2014-04-05 11:44:04 +02008551static int
8552unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8553 Py_UCS1 *translate)
8554{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008555 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008556 int ret = 0;
8557
Victor Stinner89a76ab2014-04-05 11:44:04 +02008558 if (charmaptranslate_lookup(ch, mapping, &item)) {
8559 return -1;
8560 }
8561
8562 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008563 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008564 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008565 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008566 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008567 /* not found => default to 1:1 mapping */
8568 translate[ch] = ch;
8569 return 1;
8570 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008571 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008572 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008573 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8574 used it */
8575 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008576 /* invalid character or character outside ASCII:
8577 skip the fast translate */
8578 goto exit;
8579 }
8580 translate[ch] = (Py_UCS1)replace;
8581 }
8582 else if (PyUnicode_Check(item)) {
8583 Py_UCS4 replace;
8584
8585 if (PyUnicode_READY(item) == -1) {
8586 Py_DECREF(item);
8587 return -1;
8588 }
8589 if (PyUnicode_GET_LENGTH(item) != 1)
8590 goto exit;
8591
8592 replace = PyUnicode_READ_CHAR(item, 0);
8593 if (replace > 127)
8594 goto exit;
8595 translate[ch] = (Py_UCS1)replace;
8596 }
8597 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008598 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008599 goto exit;
8600 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008601 ret = 1;
8602
Benjamin Peterson1365de72014-04-07 20:15:41 -04008603 exit:
8604 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008605 return ret;
8606}
8607
8608/* Fast path for ascii => ascii translation. Return 1 if the whole string
8609 was translated into writer, return 0 if the input string was partially
8610 translated into writer, raise an exception and return -1 on error. */
8611static int
8612unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008613 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008614{
Victor Stinner872b2912014-04-05 14:27:07 +02008615 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008616 Py_ssize_t len;
8617 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008618 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008619
8620 if (PyUnicode_READY(input) == -1)
8621 return -1;
8622 if (!PyUnicode_IS_ASCII(input))
8623 return 0;
8624 len = PyUnicode_GET_LENGTH(input);
8625
Victor Stinner872b2912014-04-05 14:27:07 +02008626 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008627
8628 in = PyUnicode_1BYTE_DATA(input);
8629 end = in + len;
8630
8631 assert(PyUnicode_IS_ASCII(writer->buffer));
8632 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8633 out = PyUnicode_1BYTE_DATA(writer->buffer);
8634
Victor Stinner872b2912014-04-05 14:27:07 +02008635 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008636 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008637 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008638 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008639 int translate = unicode_fast_translate_lookup(mapping, ch,
8640 ascii_table);
8641 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008642 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008643 if (translate == 0)
8644 goto exit;
8645 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008646 }
Victor Stinner872b2912014-04-05 14:27:07 +02008647 if (ch2 == 0xfe) {
8648 if (ignore)
8649 continue;
8650 goto exit;
8651 }
8652 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008653 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008654 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008655 }
Victor Stinner872b2912014-04-05 14:27:07 +02008656 res = 1;
8657
8658exit:
8659 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8660 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008661}
8662
Alexander Belopolsky40018472011-02-26 01:02:56 +00008663PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664_PyUnicode_TranslateCharmap(PyObject *input,
8665 PyObject *mapping,
8666 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008667{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008669 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 Py_ssize_t size, i;
8671 int kind;
8672 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008673 _PyUnicodeWriter writer;
8674 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 char *reason = "character maps to <undefined>";
8676 PyObject *errorHandler = NULL;
8677 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008678 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008679 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680
Guido van Rossumd57fd912000-03-10 22:53:23 +00008681 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 PyErr_BadArgument();
8683 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008684 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008686 if (PyUnicode_READY(input) == -1)
8687 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008688 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 kind = PyUnicode_KIND(input);
8690 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691
8692 if (size == 0) {
8693 Py_INCREF(input);
8694 return input;
8695 }
8696
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008697 /* allocate enough for a simple 1:1 translation without
8698 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008699 _PyUnicodeWriter_Init(&writer);
8700 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008702
Victor Stinner872b2912014-04-05 14:27:07 +02008703 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8704
8705 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008706 if (res < 0) {
8707 _PyUnicodeWriter_Dealloc(&writer);
8708 return NULL;
8709 }
8710 if (res == 1)
8711 return _PyUnicodeWriter_Finish(&writer);
8712
Victor Stinner89a76ab2014-04-05 11:44:04 +02008713 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008716 int translate;
8717 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8718 Py_ssize_t newpos;
8719 /* startpos for collecting untranslatable chars */
8720 Py_ssize_t collstart;
8721 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008722 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008723
Victor Stinner1194ea02014-04-04 19:37:40 +02008724 ch = PyUnicode_READ(kind, data, i);
8725 translate = charmaptranslate_output(ch, mapping, &writer);
8726 if (translate < 0)
8727 goto onError;
8728
8729 if (translate != 0) {
8730 /* it worked => adjust input pointer */
8731 ++i;
8732 continue;
8733 }
8734
8735 /* untranslatable character */
8736 collstart = i;
8737 collend = i+1;
8738
8739 /* find all untranslatable characters */
8740 while (collend < size) {
8741 PyObject *x;
8742 ch = PyUnicode_READ(kind, data, collend);
8743 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008744 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008745 Py_XDECREF(x);
8746 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008748 ++collend;
8749 }
8750
8751 if (ignore) {
8752 i = collend;
8753 }
8754 else {
8755 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8756 reason, input, &exc,
8757 collstart, collend, &newpos);
8758 if (repunicode == NULL)
8759 goto onError;
8760 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008762 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008763 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008764 Py_DECREF(repunicode);
8765 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008766 }
8767 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008768 Py_XDECREF(exc);
8769 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008770 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008771
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008773 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008774 Py_XDECREF(exc);
8775 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008776 return NULL;
8777}
8778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779/* Deprecated. Use PyUnicode_Translate instead. */
8780PyObject *
8781PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8782 Py_ssize_t size,
8783 PyObject *mapping,
8784 const char *errors)
8785{
Christian Heimes5f520f42012-09-11 14:03:25 +02008786 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8788 if (!unicode)
8789 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008790 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8791 Py_DECREF(unicode);
8792 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008793}
8794
Alexander Belopolsky40018472011-02-26 01:02:56 +00008795PyObject *
8796PyUnicode_Translate(PyObject *str,
8797 PyObject *mapping,
8798 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008799{
8800 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008801
Guido van Rossumd57fd912000-03-10 22:53:23 +00008802 str = PyUnicode_FromObject(str);
8803 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008804 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008806 Py_DECREF(str);
8807 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008808}
Tim Petersced69f82003-09-16 20:30:58 +00008809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008810static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008811fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008812{
8813 /* No need to call PyUnicode_READY(self) because this function is only
8814 called as a callback from fixup() which does it already. */
8815 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8816 const int kind = PyUnicode_KIND(self);
8817 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008818 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008819 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008820 Py_ssize_t i;
8821
8822 for (i = 0; i < len; ++i) {
8823 ch = PyUnicode_READ(kind, data, i);
8824 fixed = 0;
8825 if (ch > 127) {
8826 if (Py_UNICODE_ISSPACE(ch))
8827 fixed = ' ';
8828 else {
8829 const int decimal = Py_UNICODE_TODECIMAL(ch);
8830 if (decimal >= 0)
8831 fixed = '0' + decimal;
8832 }
8833 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008834 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008835 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008836 PyUnicode_WRITE(kind, data, i, fixed);
8837 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008838 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008839 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 }
8842
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008843 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844}
8845
8846PyObject *
8847_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8848{
8849 if (!PyUnicode_Check(unicode)) {
8850 PyErr_BadInternalCall();
8851 return NULL;
8852 }
8853 if (PyUnicode_READY(unicode) == -1)
8854 return NULL;
8855 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8856 /* If the string is already ASCII, just return the same string */
8857 Py_INCREF(unicode);
8858 return unicode;
8859 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008860 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861}
8862
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008863PyObject *
8864PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8865 Py_ssize_t length)
8866{
Victor Stinnerf0124502011-11-21 23:12:56 +01008867 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008868 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008869 Py_UCS4 maxchar;
8870 enum PyUnicode_Kind kind;
8871 void *data;
8872
Victor Stinner99d7ad02012-02-22 13:37:39 +01008873 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008874 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008875 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008876 if (ch > 127) {
8877 int decimal = Py_UNICODE_TODECIMAL(ch);
8878 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008879 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008880 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008881 }
8882 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008883
8884 /* Copy to a new string */
8885 decimal = PyUnicode_New(length, maxchar);
8886 if (decimal == NULL)
8887 return decimal;
8888 kind = PyUnicode_KIND(decimal);
8889 data = PyUnicode_DATA(decimal);
8890 /* Iterate over code points */
8891 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008892 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008893 if (ch > 127) {
8894 int decimal = Py_UNICODE_TODECIMAL(ch);
8895 if (decimal >= 0)
8896 ch = '0' + decimal;
8897 }
8898 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008900 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008901}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008902/* --- Decimal Encoder ---------------------------------------------------- */
8903
Alexander Belopolsky40018472011-02-26 01:02:56 +00008904int
8905PyUnicode_EncodeDecimal(Py_UNICODE *s,
8906 Py_ssize_t length,
8907 char *output,
8908 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008909{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008910 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008911 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008912 enum PyUnicode_Kind kind;
8913 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008914
8915 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 PyErr_BadArgument();
8917 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008918 }
8919
Victor Stinner42bf7752011-11-21 22:52:58 +01008920 unicode = PyUnicode_FromUnicode(s, length);
8921 if (unicode == NULL)
8922 return -1;
8923
Benjamin Petersonbac79492012-01-14 13:34:47 -05008924 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008925 Py_DECREF(unicode);
8926 return -1;
8927 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008928 kind = PyUnicode_KIND(unicode);
8929 data = PyUnicode_DATA(unicode);
8930
Victor Stinnerb84d7232011-11-22 01:50:07 +01008931 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008932 PyObject *exc;
8933 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008934 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008935 Py_ssize_t startpos;
8936
8937 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008938
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008940 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008941 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008943 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 decimal = Py_UNICODE_TODECIMAL(ch);
8945 if (decimal >= 0) {
8946 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008947 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008948 continue;
8949 }
8950 if (0 < ch && ch < 256) {
8951 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008952 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008953 continue;
8954 }
Victor Stinner6345be92011-11-25 20:09:01 +01008955
Victor Stinner42bf7752011-11-21 22:52:58 +01008956 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008957 exc = NULL;
8958 raise_encode_exception(&exc, "decimal", unicode,
8959 startpos, startpos+1,
8960 "invalid decimal Unicode string");
8961 Py_XDECREF(exc);
8962 Py_DECREF(unicode);
8963 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008964 }
8965 /* 0-terminate the output string */
8966 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008967 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008968 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008969}
8970
Guido van Rossumd57fd912000-03-10 22:53:23 +00008971/* --- Helpers ------------------------------------------------------------ */
8972
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008973/* helper macro to fixup start/end slice values */
8974#define ADJUST_INDICES(start, end, len) \
8975 if (end > len) \
8976 end = len; \
8977 else if (end < 0) { \
8978 end += len; \
8979 if (end < 0) \
8980 end = 0; \
8981 } \
8982 if (start < 0) { \
8983 start += len; \
8984 if (start < 0) \
8985 start = 0; \
8986 }
8987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008988static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008989any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 Py_ssize_t start,
8991 Py_ssize_t end)
8992{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008993 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008994 void *buf1, *buf2;
8995 Py_ssize_t len1, len2, result;
8996
8997 kind1 = PyUnicode_KIND(s1);
8998 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008999 if (kind1 < kind2)
9000 return -1;
9001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002 len1 = PyUnicode_GET_LENGTH(s1);
9003 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009004 ADJUST_INDICES(start, end, len1);
9005 if (end - start < len2)
9006 return -1;
9007
9008 buf1 = PyUnicode_DATA(s1);
9009 buf2 = PyUnicode_DATA(s2);
9010 if (len2 == 1) {
9011 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9012 result = findchar((const char *)buf1 + kind1*start,
9013 kind1, end - start, ch, direction);
9014 if (result == -1)
9015 return -1;
9016 else
9017 return start + result;
9018 }
9019
9020 if (kind2 != kind1) {
9021 buf2 = _PyUnicode_AsKind(s2, kind1);
9022 if (!buf2)
9023 return -2;
9024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009025
Victor Stinner794d5672011-10-10 03:21:36 +02009026 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009027 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009028 case PyUnicode_1BYTE_KIND:
9029 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9030 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9031 else
9032 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9033 break;
9034 case PyUnicode_2BYTE_KIND:
9035 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9036 break;
9037 case PyUnicode_4BYTE_KIND:
9038 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9039 break;
9040 default:
9041 assert(0); result = -2;
9042 }
9043 }
9044 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009045 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009046 case PyUnicode_1BYTE_KIND:
9047 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9048 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9049 else
9050 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9051 break;
9052 case PyUnicode_2BYTE_KIND:
9053 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9054 break;
9055 case PyUnicode_4BYTE_KIND:
9056 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9057 break;
9058 default:
9059 assert(0); result = -2;
9060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061 }
9062
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009063 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064 PyMem_Free(buf2);
9065
9066 return result;
9067}
9068
9069Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009070_PyUnicode_InsertThousandsGrouping(
9071 PyObject *unicode, Py_ssize_t index,
9072 Py_ssize_t n_buffer,
9073 void *digits, Py_ssize_t n_digits,
9074 Py_ssize_t min_width,
9075 const char *grouping, PyObject *thousands_sep,
9076 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077{
Victor Stinner41a863c2012-02-24 00:37:51 +01009078 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009079 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009080 Py_ssize_t thousands_sep_len;
9081 Py_ssize_t len;
9082
9083 if (unicode != NULL) {
9084 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009085 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009086 }
9087 else {
9088 kind = PyUnicode_1BYTE_KIND;
9089 data = NULL;
9090 }
9091 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9092 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9093 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9094 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009095 if (thousands_sep_kind < kind) {
9096 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9097 if (!thousands_sep_data)
9098 return -1;
9099 }
9100 else {
9101 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9102 if (!data)
9103 return -1;
9104 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009105 }
9106
Benjamin Petersonead6b532011-12-20 17:23:42 -06009107 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009109 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009110 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009111 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009112 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009113 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009114 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009115 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009116 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009117 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009118 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009119 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009121 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009122 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009123 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009124 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009125 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009126 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009127 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009128 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009129 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009130 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009131 break;
9132 default:
9133 assert(0);
9134 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009136 if (unicode != NULL && thousands_sep_kind != kind) {
9137 if (thousands_sep_kind < kind)
9138 PyMem_Free(thousands_sep_data);
9139 else
9140 PyMem_Free(data);
9141 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009142 if (unicode == NULL) {
9143 *maxchar = 127;
9144 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009145 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009146 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009147 }
9148 }
9149 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009150}
9151
9152
Alexander Belopolsky40018472011-02-26 01:02:56 +00009153Py_ssize_t
9154PyUnicode_Count(PyObject *str,
9155 PyObject *substr,
9156 Py_ssize_t start,
9157 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009159 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009160 PyObject* str_obj;
9161 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009162 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 void *buf1 = NULL, *buf2 = NULL;
9164 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009165
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009166 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009167 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009169 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009170 if (!sub_obj) {
9171 Py_DECREF(str_obj);
9172 return -1;
9173 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009174 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009175 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 Py_DECREF(str_obj);
9177 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178 }
Tim Petersced69f82003-09-16 20:30:58 +00009179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 kind1 = PyUnicode_KIND(str_obj);
9181 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009182 if (kind1 < kind2) {
9183 Py_DECREF(sub_obj);
9184 Py_DECREF(str_obj);
9185 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009186 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009188 len1 = PyUnicode_GET_LENGTH(str_obj);
9189 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009191 if (end - start < len2) {
9192 Py_DECREF(sub_obj);
9193 Py_DECREF(str_obj);
9194 return 0;
9195 }
9196
9197 buf1 = PyUnicode_DATA(str_obj);
9198 buf2 = PyUnicode_DATA(sub_obj);
9199 if (kind2 != kind1) {
9200 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9201 if (!buf2)
9202 goto onError;
9203 }
9204
9205 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009207 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9208 result = asciilib_count(
9209 ((Py_UCS1*)buf1) + start, end - start,
9210 buf2, len2, PY_SSIZE_T_MAX
9211 );
9212 else
9213 result = ucs1lib_count(
9214 ((Py_UCS1*)buf1) + start, end - start,
9215 buf2, len2, PY_SSIZE_T_MAX
9216 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009217 break;
9218 case PyUnicode_2BYTE_KIND:
9219 result = ucs2lib_count(
9220 ((Py_UCS2*)buf1) + start, end - start,
9221 buf2, len2, PY_SSIZE_T_MAX
9222 );
9223 break;
9224 case PyUnicode_4BYTE_KIND:
9225 result = ucs4lib_count(
9226 ((Py_UCS4*)buf1) + start, end - start,
9227 buf2, len2, PY_SSIZE_T_MAX
9228 );
9229 break;
9230 default:
9231 assert(0); result = 0;
9232 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009233
9234 Py_DECREF(sub_obj);
9235 Py_DECREF(str_obj);
9236
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009237 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238 PyMem_Free(buf2);
9239
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009241 onError:
9242 Py_DECREF(sub_obj);
9243 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009244 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245 PyMem_Free(buf2);
9246 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247}
9248
Alexander Belopolsky40018472011-02-26 01:02:56 +00009249Py_ssize_t
9250PyUnicode_Find(PyObject *str,
9251 PyObject *sub,
9252 Py_ssize_t start,
9253 Py_ssize_t end,
9254 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009256 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009257
Guido van Rossumd57fd912000-03-10 22:53:23 +00009258 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009259 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009260 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009261 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009262 if (!sub) {
9263 Py_DECREF(str);
9264 return -2;
9265 }
9266 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9267 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009268 Py_DECREF(str);
9269 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009270 }
Tim Petersced69f82003-09-16 20:30:58 +00009271
Victor Stinner794d5672011-10-10 03:21:36 +02009272 result = any_find_slice(direction,
9273 str, sub, start, end
9274 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009275
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009277 Py_DECREF(sub);
9278
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279 return result;
9280}
9281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282Py_ssize_t
9283PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9284 Py_ssize_t start, Py_ssize_t end,
9285 int direction)
9286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009288 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289 if (PyUnicode_READY(str) == -1)
9290 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009291 if (start < 0 || end < 0) {
9292 PyErr_SetString(PyExc_IndexError, "string index out of range");
9293 return -2;
9294 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295 if (end > PyUnicode_GET_LENGTH(str))
9296 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009297 if (start >= end)
9298 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009300 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9301 kind, end-start, ch, direction);
9302 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009304 else
9305 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009306}
9307
Alexander Belopolsky40018472011-02-26 01:02:56 +00009308static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009309tailmatch(PyObject *self,
9310 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009311 Py_ssize_t start,
9312 Py_ssize_t end,
9313 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009314{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315 int kind_self;
9316 int kind_sub;
9317 void *data_self;
9318 void *data_sub;
9319 Py_ssize_t offset;
9320 Py_ssize_t i;
9321 Py_ssize_t end_sub;
9322
9323 if (PyUnicode_READY(self) == -1 ||
9324 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009325 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9328 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009330 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009332 if (PyUnicode_GET_LENGTH(substring) == 0)
9333 return 1;
9334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 kind_self = PyUnicode_KIND(self);
9336 data_self = PyUnicode_DATA(self);
9337 kind_sub = PyUnicode_KIND(substring);
9338 data_sub = PyUnicode_DATA(substring);
9339 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9340
9341 if (direction > 0)
9342 offset = end;
9343 else
9344 offset = start;
9345
9346 if (PyUnicode_READ(kind_self, data_self, offset) ==
9347 PyUnicode_READ(kind_sub, data_sub, 0) &&
9348 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9349 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9350 /* If both are of the same kind, memcmp is sufficient */
9351 if (kind_self == kind_sub) {
9352 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009353 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 data_sub,
9355 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009356 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009357 }
9358 /* otherwise we have to compare each character by first accesing it */
9359 else {
9360 /* We do not need to compare 0 and len(substring)-1 because
9361 the if statement above ensured already that they are equal
9362 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 for (i = 1; i < end_sub; ++i) {
9364 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9365 PyUnicode_READ(kind_sub, data_sub, i))
9366 return 0;
9367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370 }
9371
9372 return 0;
9373}
9374
Alexander Belopolsky40018472011-02-26 01:02:56 +00009375Py_ssize_t
9376PyUnicode_Tailmatch(PyObject *str,
9377 PyObject *substr,
9378 Py_ssize_t start,
9379 Py_ssize_t end,
9380 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009382 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009383
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 str = PyUnicode_FromObject(str);
9385 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009386 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387 substr = PyUnicode_FromObject(substr);
9388 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009389 Py_DECREF(str);
9390 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391 }
Tim Petersced69f82003-09-16 20:30:58 +00009392
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009393 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009394 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395 Py_DECREF(str);
9396 Py_DECREF(substr);
9397 return result;
9398}
9399
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400/* Apply fixfct filter to the Unicode object self and return a
9401 reference to the modified object */
9402
Alexander Belopolsky40018472011-02-26 01:02:56 +00009403static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009404fixup(PyObject *self,
9405 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 PyObject *u;
9408 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009409 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009411 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009412 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009413 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009414 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 /* fix functions return the new maximum character in a string,
9417 if the kind of the resulting unicode object does not change,
9418 everything is fine. Otherwise we need to change the string kind
9419 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009420 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009421
9422 if (maxchar_new == 0) {
9423 /* no changes */;
9424 if (PyUnicode_CheckExact(self)) {
9425 Py_DECREF(u);
9426 Py_INCREF(self);
9427 return self;
9428 }
9429 else
9430 return u;
9431 }
9432
Victor Stinnere6abb482012-05-02 01:15:40 +02009433 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434
Victor Stinnereaab6042011-12-11 22:22:39 +01009435 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009437
9438 /* In case the maximum character changed, we need to
9439 convert the string to the new category. */
9440 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9441 if (v == NULL) {
9442 Py_DECREF(u);
9443 return NULL;
9444 }
9445 if (maxchar_new > maxchar_old) {
9446 /* If the maxchar increased so that the kind changed, not all
9447 characters are representable anymore and we need to fix the
9448 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009449 _PyUnicode_FastCopyCharacters(v, 0,
9450 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009451 maxchar_old = fixfct(v);
9452 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 }
9454 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009455 _PyUnicode_FastCopyCharacters(v, 0,
9456 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009458 Py_DECREF(u);
9459 assert(_PyUnicode_CheckConsistency(v, 1));
9460 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461}
9462
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009463static PyObject *
9464ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009465{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009466 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9467 char *resdata, *data = PyUnicode_DATA(self);
9468 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009469
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009470 res = PyUnicode_New(len, 127);
9471 if (res == NULL)
9472 return NULL;
9473 resdata = PyUnicode_DATA(res);
9474 if (lower)
9475 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009477 _Py_bytes_upper(resdata, data, len);
9478 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009479}
9480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009482handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009484 Py_ssize_t j;
9485 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009486 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009487 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009488
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009489 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9490
9491 where ! is a negation and \p{xxx} is a character with property xxx.
9492 */
9493 for (j = i - 1; j >= 0; j--) {
9494 c = PyUnicode_READ(kind, data, j);
9495 if (!_PyUnicode_IsCaseIgnorable(c))
9496 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009498 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9499 if (final_sigma) {
9500 for (j = i + 1; j < length; j++) {
9501 c = PyUnicode_READ(kind, data, j);
9502 if (!_PyUnicode_IsCaseIgnorable(c))
9503 break;
9504 }
9505 final_sigma = j == length || !_PyUnicode_IsCased(c);
9506 }
9507 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508}
9509
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009510static int
9511lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9512 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009514 /* Obscure special case. */
9515 if (c == 0x3A3) {
9516 mapped[0] = handle_capital_sigma(kind, data, length, i);
9517 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009519 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520}
9521
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009522static Py_ssize_t
9523do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009525 Py_ssize_t i, k = 0;
9526 int n_res, j;
9527 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009528
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009529 c = PyUnicode_READ(kind, data, 0);
9530 n_res = _PyUnicode_ToUpperFull(c, mapped);
9531 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009532 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009533 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009535 for (i = 1; i < length; i++) {
9536 c = PyUnicode_READ(kind, data, i);
9537 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9538 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009539 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009540 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009541 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009542 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009543 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544}
9545
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009546static Py_ssize_t
9547do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9548 Py_ssize_t i, k = 0;
9549
9550 for (i = 0; i < length; i++) {
9551 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9552 int n_res, j;
9553 if (Py_UNICODE_ISUPPER(c)) {
9554 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9555 }
9556 else if (Py_UNICODE_ISLOWER(c)) {
9557 n_res = _PyUnicode_ToUpperFull(c, mapped);
9558 }
9559 else {
9560 n_res = 1;
9561 mapped[0] = c;
9562 }
9563 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009564 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 res[k++] = mapped[j];
9566 }
9567 }
9568 return k;
9569}
9570
9571static Py_ssize_t
9572do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9573 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009575 Py_ssize_t i, k = 0;
9576
9577 for (i = 0; i < length; i++) {
9578 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9579 int n_res, j;
9580 if (lower)
9581 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9582 else
9583 n_res = _PyUnicode_ToUpperFull(c, mapped);
9584 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009585 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009586 res[k++] = mapped[j];
9587 }
9588 }
9589 return k;
9590}
9591
9592static Py_ssize_t
9593do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9594{
9595 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9596}
9597
9598static Py_ssize_t
9599do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9600{
9601 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9602}
9603
Benjamin Petersone51757f2012-01-12 21:10:29 -05009604static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009605do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9606{
9607 Py_ssize_t i, k = 0;
9608
9609 for (i = 0; i < length; i++) {
9610 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9611 Py_UCS4 mapped[3];
9612 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9613 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009614 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009615 res[k++] = mapped[j];
9616 }
9617 }
9618 return k;
9619}
9620
9621static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009622do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9623{
9624 Py_ssize_t i, k = 0;
9625 int previous_is_cased;
9626
9627 previous_is_cased = 0;
9628 for (i = 0; i < length; i++) {
9629 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9630 Py_UCS4 mapped[3];
9631 int n_res, j;
9632
9633 if (previous_is_cased)
9634 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9635 else
9636 n_res = _PyUnicode_ToTitleFull(c, mapped);
9637
9638 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009639 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009640 res[k++] = mapped[j];
9641 }
9642
9643 previous_is_cased = _PyUnicode_IsCased(c);
9644 }
9645 return k;
9646}
9647
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648static PyObject *
9649case_operation(PyObject *self,
9650 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9651{
9652 PyObject *res = NULL;
9653 Py_ssize_t length, newlength = 0;
9654 int kind, outkind;
9655 void *data, *outdata;
9656 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9657
Benjamin Petersoneea48462012-01-16 14:28:50 -05009658 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659
9660 kind = PyUnicode_KIND(self);
9661 data = PyUnicode_DATA(self);
9662 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009663 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009664 PyErr_SetString(PyExc_OverflowError, "string is too long");
9665 return NULL;
9666 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009667 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009668 if (tmp == NULL)
9669 return PyErr_NoMemory();
9670 newlength = perform(kind, data, length, tmp, &maxchar);
9671 res = PyUnicode_New(newlength, maxchar);
9672 if (res == NULL)
9673 goto leave;
9674 tmpend = tmp + newlength;
9675 outdata = PyUnicode_DATA(res);
9676 outkind = PyUnicode_KIND(res);
9677 switch (outkind) {
9678 case PyUnicode_1BYTE_KIND:
9679 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9680 break;
9681 case PyUnicode_2BYTE_KIND:
9682 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9683 break;
9684 case PyUnicode_4BYTE_KIND:
9685 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9686 break;
9687 default:
9688 assert(0);
9689 break;
9690 }
9691 leave:
9692 PyMem_FREE(tmp);
9693 return res;
9694}
9695
Tim Peters8ce9f162004-08-27 01:49:32 +00009696PyObject *
9697PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009698{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009700 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009702 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009703 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9704 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009705 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009707 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009709 int use_memcpy;
9710 unsigned char *res_data = NULL, *sep_data = NULL;
9711 PyObject *last_obj;
9712 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009713
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009714 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009715 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009716 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009717 }
9718
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009719 /* NOTE: the following code can't call back into Python code,
9720 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009721 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009722
Tim Peters05eba1f2004-08-27 21:32:02 +00009723 seqlen = PySequence_Fast_GET_SIZE(fseq);
9724 /* If empty sequence, return u"". */
9725 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009726 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009727 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009728 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009729
Tim Peters05eba1f2004-08-27 21:32:02 +00009730 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009731 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009732 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009733 if (seqlen == 1) {
9734 if (PyUnicode_CheckExact(items[0])) {
9735 res = items[0];
9736 Py_INCREF(res);
9737 Py_DECREF(fseq);
9738 return res;
9739 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009741 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009742 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009743 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009744 /* Set up sep and seplen */
9745 if (separator == NULL) {
9746 /* fall back to a blank space separator */
9747 sep = PyUnicode_FromOrdinal(' ');
9748 if (!sep)
9749 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009750 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009751 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009752 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009753 else {
9754 if (!PyUnicode_Check(separator)) {
9755 PyErr_Format(PyExc_TypeError,
9756 "separator: expected str instance,"
9757 " %.80s found",
9758 Py_TYPE(separator)->tp_name);
9759 goto onError;
9760 }
9761 if (PyUnicode_READY(separator))
9762 goto onError;
9763 sep = separator;
9764 seplen = PyUnicode_GET_LENGTH(separator);
9765 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9766 /* inc refcount to keep this code path symmetric with the
9767 above case of a blank separator */
9768 Py_INCREF(sep);
9769 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009770 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009771 }
9772
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009773 /* There are at least two things to join, or else we have a subclass
9774 * of str in the sequence.
9775 * Do a pre-pass to figure out the total amount of space we'll
9776 * need (sz), and see whether all argument are strings.
9777 */
9778 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009779#ifdef Py_DEBUG
9780 use_memcpy = 0;
9781#else
9782 use_memcpy = 1;
9783#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009784 for (i = 0; i < seqlen; i++) {
9785 const Py_ssize_t old_sz = sz;
9786 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009787 if (!PyUnicode_Check(item)) {
9788 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009789 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009790 " %.80s found",
9791 i, Py_TYPE(item)->tp_name);
9792 goto onError;
9793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009794 if (PyUnicode_READY(item) == -1)
9795 goto onError;
9796 sz += PyUnicode_GET_LENGTH(item);
9797 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009798 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009799 if (i != 0)
9800 sz += seplen;
9801 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9802 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009803 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009804 goto onError;
9805 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009806 if (use_memcpy && last_obj != NULL) {
9807 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9808 use_memcpy = 0;
9809 }
9810 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009811 }
Tim Petersced69f82003-09-16 20:30:58 +00009812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009814 if (res == NULL)
9815 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009816
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009817 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009818#ifdef Py_DEBUG
9819 use_memcpy = 0;
9820#else
9821 if (use_memcpy) {
9822 res_data = PyUnicode_1BYTE_DATA(res);
9823 kind = PyUnicode_KIND(res);
9824 if (seplen != 0)
9825 sep_data = PyUnicode_1BYTE_DATA(sep);
9826 }
9827#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009828 if (use_memcpy) {
9829 for (i = 0; i < seqlen; ++i) {
9830 Py_ssize_t itemlen;
9831 item = items[i];
9832
9833 /* Copy item, and maybe the separator. */
9834 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009835 Py_MEMCPY(res_data,
9836 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009837 kind * seplen);
9838 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009839 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009840
9841 itemlen = PyUnicode_GET_LENGTH(item);
9842 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009843 Py_MEMCPY(res_data,
9844 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009845 kind * itemlen);
9846 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009847 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009848 }
9849 assert(res_data == PyUnicode_1BYTE_DATA(res)
9850 + kind * PyUnicode_GET_LENGTH(res));
9851 }
9852 else {
9853 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9854 Py_ssize_t itemlen;
9855 item = items[i];
9856
9857 /* Copy item, and maybe the separator. */
9858 if (i && seplen != 0) {
9859 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9860 res_offset += seplen;
9861 }
9862
9863 itemlen = PyUnicode_GET_LENGTH(item);
9864 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009865 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009866 res_offset += itemlen;
9867 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009868 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009869 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009870 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009871
Tim Peters05eba1f2004-08-27 21:32:02 +00009872 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009874 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876
Benjamin Peterson29060642009-01-31 22:14:21 +00009877 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009878 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009880 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009881 return NULL;
9882}
9883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884#define FILL(kind, data, value, start, length) \
9885 do { \
9886 Py_ssize_t i_ = 0; \
9887 assert(kind != PyUnicode_WCHAR_KIND); \
9888 switch ((kind)) { \
9889 case PyUnicode_1BYTE_KIND: { \
9890 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009891 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 break; \
9893 } \
9894 case PyUnicode_2BYTE_KIND: { \
9895 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9896 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9897 break; \
9898 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009899 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009900 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9901 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9902 break; \
9903 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009904 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 } \
9906 } while (0)
9907
Victor Stinnerd3f08822012-05-29 12:57:52 +02009908void
9909_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9910 Py_UCS4 fill_char)
9911{
9912 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9913 const void *data = PyUnicode_DATA(unicode);
9914 assert(PyUnicode_IS_READY(unicode));
9915 assert(unicode_modifiable(unicode));
9916 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9917 assert(start >= 0);
9918 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9919 FILL(kind, data, fill_char, start, length);
9920}
9921
Victor Stinner3fe55312012-01-04 00:33:50 +01009922Py_ssize_t
9923PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9924 Py_UCS4 fill_char)
9925{
9926 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009927
9928 if (!PyUnicode_Check(unicode)) {
9929 PyErr_BadInternalCall();
9930 return -1;
9931 }
9932 if (PyUnicode_READY(unicode) == -1)
9933 return -1;
9934 if (unicode_check_modifiable(unicode))
9935 return -1;
9936
Victor Stinnerd3f08822012-05-29 12:57:52 +02009937 if (start < 0) {
9938 PyErr_SetString(PyExc_IndexError, "string index out of range");
9939 return -1;
9940 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009941 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9942 PyErr_SetString(PyExc_ValueError,
9943 "fill character is bigger than "
9944 "the string maximum character");
9945 return -1;
9946 }
9947
9948 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9949 length = Py_MIN(maxlen, length);
9950 if (length <= 0)
9951 return 0;
9952
Victor Stinnerd3f08822012-05-29 12:57:52 +02009953 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009954 return length;
9955}
9956
Victor Stinner9310abb2011-10-05 00:59:23 +02009957static PyObject *
9958pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009959 Py_ssize_t left,
9960 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 PyObject *u;
9964 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009965 int kind;
9966 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009967
9968 if (left < 0)
9969 left = 0;
9970 if (right < 0)
9971 right = 0;
9972
Victor Stinnerc4b49542011-12-11 22:44:26 +01009973 if (left == 0 && right == 0)
9974 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9977 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009978 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9979 return NULL;
9980 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009982 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009984 if (!u)
9985 return NULL;
9986
9987 kind = PyUnicode_KIND(u);
9988 data = PyUnicode_DATA(u);
9989 if (left)
9990 FILL(kind, data, fill, 0, left);
9991 if (right)
9992 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009993 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009994 assert(_PyUnicode_CheckConsistency(u, 1));
9995 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009996}
9997
Alexander Belopolsky40018472011-02-26 01:02:56 +00009998PyObject *
9999PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010000{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010001 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010002
10003 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010004 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010005 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010006 if (PyUnicode_READY(string) == -1) {
10007 Py_DECREF(string);
10008 return NULL;
10009 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010010
Benjamin Petersonead6b532011-12-20 17:23:42 -060010011 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010013 if (PyUnicode_IS_ASCII(string))
10014 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010015 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010016 PyUnicode_GET_LENGTH(string), keepends);
10017 else
10018 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010019 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010020 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010021 break;
10022 case PyUnicode_2BYTE_KIND:
10023 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010024 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 PyUnicode_GET_LENGTH(string), keepends);
10026 break;
10027 case PyUnicode_4BYTE_KIND:
10028 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010029 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010030 PyUnicode_GET_LENGTH(string), keepends);
10031 break;
10032 default:
10033 assert(0);
10034 list = 0;
10035 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010036 Py_DECREF(string);
10037 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010038}
10039
Alexander Belopolsky40018472011-02-26 01:02:56 +000010040static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010041split(PyObject *self,
10042 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010043 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010044{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010045 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 void *buf1, *buf2;
10047 Py_ssize_t len1, len2;
10048 PyObject* out;
10049
Guido van Rossumd57fd912000-03-10 22:53:23 +000010050 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010051 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 if (PyUnicode_READY(self) == -1)
10054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010057 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010059 if (PyUnicode_IS_ASCII(self))
10060 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010061 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010062 PyUnicode_GET_LENGTH(self), maxcount
10063 );
10064 else
10065 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010066 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010067 PyUnicode_GET_LENGTH(self), maxcount
10068 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 case PyUnicode_2BYTE_KIND:
10070 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010071 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 PyUnicode_GET_LENGTH(self), maxcount
10073 );
10074 case PyUnicode_4BYTE_KIND:
10075 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010076 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 PyUnicode_GET_LENGTH(self), maxcount
10078 );
10079 default:
10080 assert(0);
10081 return NULL;
10082 }
10083
10084 if (PyUnicode_READY(substring) == -1)
10085 return NULL;
10086
10087 kind1 = PyUnicode_KIND(self);
10088 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 len1 = PyUnicode_GET_LENGTH(self);
10090 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010091 if (kind1 < kind2 || len1 < len2) {
10092 out = PyList_New(1);
10093 if (out == NULL)
10094 return NULL;
10095 Py_INCREF(self);
10096 PyList_SET_ITEM(out, 0, self);
10097 return out;
10098 }
10099 buf1 = PyUnicode_DATA(self);
10100 buf2 = PyUnicode_DATA(substring);
10101 if (kind2 != kind1) {
10102 buf2 = _PyUnicode_AsKind(substring, kind1);
10103 if (!buf2)
10104 return NULL;
10105 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010107 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010109 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10110 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010111 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010112 else
10113 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010114 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 break;
10116 case PyUnicode_2BYTE_KIND:
10117 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010118 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 break;
10120 case PyUnicode_4BYTE_KIND:
10121 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010122 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 break;
10124 default:
10125 out = NULL;
10126 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010127 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 PyMem_Free(buf2);
10129 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130}
10131
Alexander Belopolsky40018472011-02-26 01:02:56 +000010132static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010133rsplit(PyObject *self,
10134 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010135 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010136{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010137 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 void *buf1, *buf2;
10139 Py_ssize_t len1, len2;
10140 PyObject* out;
10141
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010142 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010143 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 if (PyUnicode_READY(self) == -1)
10146 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010149 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010151 if (PyUnicode_IS_ASCII(self))
10152 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010153 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010154 PyUnicode_GET_LENGTH(self), maxcount
10155 );
10156 else
10157 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010158 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010159 PyUnicode_GET_LENGTH(self), maxcount
10160 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 case PyUnicode_2BYTE_KIND:
10162 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010163 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 PyUnicode_GET_LENGTH(self), maxcount
10165 );
10166 case PyUnicode_4BYTE_KIND:
10167 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010168 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 PyUnicode_GET_LENGTH(self), maxcount
10170 );
10171 default:
10172 assert(0);
10173 return NULL;
10174 }
10175
10176 if (PyUnicode_READY(substring) == -1)
10177 return NULL;
10178
10179 kind1 = PyUnicode_KIND(self);
10180 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 len1 = PyUnicode_GET_LENGTH(self);
10182 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010183 if (kind1 < kind2 || len1 < len2) {
10184 out = PyList_New(1);
10185 if (out == NULL)
10186 return NULL;
10187 Py_INCREF(self);
10188 PyList_SET_ITEM(out, 0, self);
10189 return out;
10190 }
10191 buf1 = PyUnicode_DATA(self);
10192 buf2 = PyUnicode_DATA(substring);
10193 if (kind2 != kind1) {
10194 buf2 = _PyUnicode_AsKind(substring, kind1);
10195 if (!buf2)
10196 return NULL;
10197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010199 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010201 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10202 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010203 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010204 else
10205 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010206 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 break;
10208 case PyUnicode_2BYTE_KIND:
10209 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010210 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 break;
10212 case PyUnicode_4BYTE_KIND:
10213 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010214 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 break;
10216 default:
10217 out = NULL;
10218 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010219 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 PyMem_Free(buf2);
10221 return out;
10222}
10223
10224static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010225anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10226 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010228 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010230 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10231 return asciilib_find(buf1, len1, buf2, len2, offset);
10232 else
10233 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 case PyUnicode_2BYTE_KIND:
10235 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10236 case PyUnicode_4BYTE_KIND:
10237 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10238 }
10239 assert(0);
10240 return -1;
10241}
10242
10243static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010244anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10245 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010247 switch (kind) {
10248 case PyUnicode_1BYTE_KIND:
10249 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10250 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10251 else
10252 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10253 case PyUnicode_2BYTE_KIND:
10254 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10255 case PyUnicode_4BYTE_KIND:
10256 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10257 }
10258 assert(0);
10259 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010260}
10261
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010262static void
10263replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10264 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10265{
10266 int kind = PyUnicode_KIND(u);
10267 void *data = PyUnicode_DATA(u);
10268 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10269 if (kind == PyUnicode_1BYTE_KIND) {
10270 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10271 (Py_UCS1 *)data + len,
10272 u1, u2, maxcount);
10273 }
10274 else if (kind == PyUnicode_2BYTE_KIND) {
10275 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10276 (Py_UCS2 *)data + len,
10277 u1, u2, maxcount);
10278 }
10279 else {
10280 assert(kind == PyUnicode_4BYTE_KIND);
10281 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10282 (Py_UCS4 *)data + len,
10283 u1, u2, maxcount);
10284 }
10285}
10286
Alexander Belopolsky40018472011-02-26 01:02:56 +000010287static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288replace(PyObject *self, PyObject *str1,
10289 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 PyObject *u;
10292 char *sbuf = PyUnicode_DATA(self);
10293 char *buf1 = PyUnicode_DATA(str1);
10294 char *buf2 = PyUnicode_DATA(str2);
10295 int srelease = 0, release1 = 0, release2 = 0;
10296 int skind = PyUnicode_KIND(self);
10297 int kind1 = PyUnicode_KIND(str1);
10298 int kind2 = PyUnicode_KIND(str2);
10299 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10300 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10301 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010302 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010303 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304
10305 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010306 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010308 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309
Victor Stinner59de0ee2011-10-07 10:01:28 +020010310 if (str1 == str2)
10311 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312
Victor Stinner49a0a212011-10-12 23:46:10 +020010313 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010314 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10315 if (maxchar < maxchar_str1)
10316 /* substring too wide to be present */
10317 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010318 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10319 /* Replacing str1 with str2 may cause a maxchar reduction in the
10320 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010321 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010322 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010325 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010327 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010330 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010331 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010332
Victor Stinner69ed0f42013-04-09 21:48:24 +020010333 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010334 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010335 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010336 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010337 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010339 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010341
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010342 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10343 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010344 }
10345 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 int rkind = skind;
10347 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010348 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 if (kind1 < rkind) {
10351 /* widen substring */
10352 buf1 = _PyUnicode_AsKind(str1, rkind);
10353 if (!buf1) goto error;
10354 release1 = 1;
10355 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010356 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010357 if (i < 0)
10358 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 if (rkind > kind2) {
10360 /* widen replacement */
10361 buf2 = _PyUnicode_AsKind(str2, rkind);
10362 if (!buf2) goto error;
10363 release2 = 1;
10364 }
10365 else if (rkind < kind2) {
10366 /* widen self and buf1 */
10367 rkind = kind2;
10368 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010369 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 sbuf = _PyUnicode_AsKind(self, rkind);
10371 if (!sbuf) goto error;
10372 srelease = 1;
10373 buf1 = _PyUnicode_AsKind(str1, rkind);
10374 if (!buf1) goto error;
10375 release1 = 1;
10376 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010377 u = PyUnicode_New(slen, maxchar);
10378 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010380 assert(PyUnicode_KIND(u) == rkind);
10381 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010382
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010383 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010384 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010385 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010387 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010389
10390 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010391 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010392 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010393 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010394 if (i == -1)
10395 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010396 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010398 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010400 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010402 }
10403 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010405 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 int rkind = skind;
10407 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010410 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 buf1 = _PyUnicode_AsKind(str1, rkind);
10412 if (!buf1) goto error;
10413 release1 = 1;
10414 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416 if (n == 0)
10417 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010419 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 buf2 = _PyUnicode_AsKind(str2, rkind);
10421 if (!buf2) goto error;
10422 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010425 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 rkind = kind2;
10427 sbuf = _PyUnicode_AsKind(self, rkind);
10428 if (!sbuf) goto error;
10429 srelease = 1;
10430 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010431 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 buf1 = _PyUnicode_AsKind(str1, rkind);
10433 if (!buf1) goto error;
10434 release1 = 1;
10435 }
10436 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10437 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010438 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 PyErr_SetString(PyExc_OverflowError,
10440 "replace string is too long");
10441 goto error;
10442 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010443 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010444 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010445 _Py_INCREF_UNICODE_EMPTY();
10446 if (!unicode_empty)
10447 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010448 u = unicode_empty;
10449 goto done;
10450 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010451 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 PyErr_SetString(PyExc_OverflowError,
10453 "replace string is too long");
10454 goto error;
10455 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010456 u = PyUnicode_New(new_size, maxchar);
10457 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010459 assert(PyUnicode_KIND(u) == rkind);
10460 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 ires = i = 0;
10462 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 while (n-- > 0) {
10464 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010465 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010466 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010467 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010468 if (j == -1)
10469 break;
10470 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010471 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010472 memcpy(res + rkind * ires,
10473 sbuf + rkind * i,
10474 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 }
10477 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010479 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010481 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010483 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010485 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010488 memcpy(res + rkind * ires,
10489 sbuf + rkind * i,
10490 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010491 }
10492 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010493 /* interleave */
10494 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010495 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010497 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010499 if (--n <= 0)
10500 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010501 memcpy(res + rkind * ires,
10502 sbuf + rkind * i,
10503 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504 ires++;
10505 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010506 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010507 memcpy(res + rkind * ires,
10508 sbuf + rkind * i,
10509 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010510 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010511 }
10512
10513 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010514 unicode_adjust_maxchar(&u);
10515 if (u == NULL)
10516 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010518
10519 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (srelease)
10521 PyMem_FREE(sbuf);
10522 if (release1)
10523 PyMem_FREE(buf1);
10524 if (release2)
10525 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010526 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010527 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010528
Benjamin Peterson29060642009-01-31 22:14:21 +000010529 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010530 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 if (srelease)
10532 PyMem_FREE(sbuf);
10533 if (release1)
10534 PyMem_FREE(buf1);
10535 if (release2)
10536 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010537 return unicode_result_unchanged(self);
10538
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 error:
10540 if (srelease && sbuf)
10541 PyMem_FREE(sbuf);
10542 if (release1 && buf1)
10543 PyMem_FREE(buf1);
10544 if (release2 && buf2)
10545 PyMem_FREE(buf2);
10546 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547}
10548
10549/* --- Unicode Object Methods --------------------------------------------- */
10550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010551PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010552 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010553\n\
10554Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010555characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010556
10557static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010558unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010559{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010560 if (PyUnicode_READY(self) == -1)
10561 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010562 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563}
10564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010565PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010566 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010567\n\
10568Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010569have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570
10571static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010572unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010574 if (PyUnicode_READY(self) == -1)
10575 return NULL;
10576 if (PyUnicode_GET_LENGTH(self) == 0)
10577 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010578 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010579}
10580
Benjamin Petersond5890c82012-01-14 13:23:30 -050010581PyDoc_STRVAR(casefold__doc__,
10582 "S.casefold() -> str\n\
10583\n\
10584Return a version of S suitable for caseless comparisons.");
10585
10586static PyObject *
10587unicode_casefold(PyObject *self)
10588{
10589 if (PyUnicode_READY(self) == -1)
10590 return NULL;
10591 if (PyUnicode_IS_ASCII(self))
10592 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010593 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010594}
10595
10596
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010597/* Argument converter. Coerces to a single unicode character */
10598
10599static int
10600convert_uc(PyObject *obj, void *addr)
10601{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010603 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010604
Benjamin Peterson14339b62009-01-31 16:36:08 +000010605 uniobj = PyUnicode_FromObject(obj);
10606 if (uniobj == NULL) {
10607 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010608 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010609 return 0;
10610 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010612 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010613 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010614 Py_DECREF(uniobj);
10615 return 0;
10616 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010618 Py_DECREF(uniobj);
10619 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010620}
10621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010622PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010623 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010625Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010626done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627
10628static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010629unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010631 Py_ssize_t marg, left;
10632 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 Py_UCS4 fillchar = ' ';
10634
Victor Stinnere9a29352011-10-01 02:14:59 +020010635 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637
Benjamin Petersonbac79492012-01-14 13:34:47 -050010638 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639 return NULL;
10640
Victor Stinnerc4b49542011-12-11 22:44:26 +010010641 if (PyUnicode_GET_LENGTH(self) >= width)
10642 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643
Victor Stinnerc4b49542011-12-11 22:44:26 +010010644 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645 left = marg / 2 + (marg & width & 1);
10646
Victor Stinner9310abb2011-10-05 00:59:23 +020010647 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648}
10649
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650/* This function assumes that str1 and str2 are readied by the caller. */
10651
Marc-André Lemburge5034372000-08-08 08:04:29 +000010652static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010653unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010654{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010655#define COMPARE(TYPE1, TYPE2) \
10656 do { \
10657 TYPE1* p1 = (TYPE1 *)data1; \
10658 TYPE2* p2 = (TYPE2 *)data2; \
10659 TYPE1* end = p1 + len; \
10660 Py_UCS4 c1, c2; \
10661 for (; p1 != end; p1++, p2++) { \
10662 c1 = *p1; \
10663 c2 = *p2; \
10664 if (c1 != c2) \
10665 return (c1 < c2) ? -1 : 1; \
10666 } \
10667 } \
10668 while (0)
10669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 int kind1, kind2;
10671 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010672 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010674 kind1 = PyUnicode_KIND(str1);
10675 kind2 = PyUnicode_KIND(str2);
10676 data1 = PyUnicode_DATA(str1);
10677 data2 = PyUnicode_DATA(str2);
10678 len1 = PyUnicode_GET_LENGTH(str1);
10679 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010680 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010681
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010682 switch(kind1) {
10683 case PyUnicode_1BYTE_KIND:
10684 {
10685 switch(kind2) {
10686 case PyUnicode_1BYTE_KIND:
10687 {
10688 int cmp = memcmp(data1, data2, len);
10689 /* normalize result of memcmp() into the range [-1; 1] */
10690 if (cmp < 0)
10691 return -1;
10692 if (cmp > 0)
10693 return 1;
10694 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010695 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010696 case PyUnicode_2BYTE_KIND:
10697 COMPARE(Py_UCS1, Py_UCS2);
10698 break;
10699 case PyUnicode_4BYTE_KIND:
10700 COMPARE(Py_UCS1, Py_UCS4);
10701 break;
10702 default:
10703 assert(0);
10704 }
10705 break;
10706 }
10707 case PyUnicode_2BYTE_KIND:
10708 {
10709 switch(kind2) {
10710 case PyUnicode_1BYTE_KIND:
10711 COMPARE(Py_UCS2, Py_UCS1);
10712 break;
10713 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010714 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010715 COMPARE(Py_UCS2, Py_UCS2);
10716 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010717 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010718 case PyUnicode_4BYTE_KIND:
10719 COMPARE(Py_UCS2, Py_UCS4);
10720 break;
10721 default:
10722 assert(0);
10723 }
10724 break;
10725 }
10726 case PyUnicode_4BYTE_KIND:
10727 {
10728 switch(kind2) {
10729 case PyUnicode_1BYTE_KIND:
10730 COMPARE(Py_UCS4, Py_UCS1);
10731 break;
10732 case PyUnicode_2BYTE_KIND:
10733 COMPARE(Py_UCS4, Py_UCS2);
10734 break;
10735 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010736 {
10737#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10738 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10739 /* normalize result of wmemcmp() into the range [-1; 1] */
10740 if (cmp < 0)
10741 return -1;
10742 if (cmp > 0)
10743 return 1;
10744#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010745 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010746#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010747 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010748 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010749 default:
10750 assert(0);
10751 }
10752 break;
10753 }
10754 default:
10755 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010756 }
10757
Victor Stinner770e19e2012-10-04 22:59:45 +020010758 if (len1 == len2)
10759 return 0;
10760 if (len1 < len2)
10761 return -1;
10762 else
10763 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010764
10765#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010766}
10767
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010768Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010769unicode_compare_eq(PyObject *str1, PyObject *str2)
10770{
10771 int kind;
10772 void *data1, *data2;
10773 Py_ssize_t len;
10774 int cmp;
10775
Victor Stinnere5567ad2012-10-23 02:48:49 +020010776 len = PyUnicode_GET_LENGTH(str1);
10777 if (PyUnicode_GET_LENGTH(str2) != len)
10778 return 0;
10779 kind = PyUnicode_KIND(str1);
10780 if (PyUnicode_KIND(str2) != kind)
10781 return 0;
10782 data1 = PyUnicode_DATA(str1);
10783 data2 = PyUnicode_DATA(str2);
10784
10785 cmp = memcmp(data1, data2, len * kind);
10786 return (cmp == 0);
10787}
10788
10789
Alexander Belopolsky40018472011-02-26 01:02:56 +000010790int
10791PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10794 if (PyUnicode_READY(left) == -1 ||
10795 PyUnicode_READY(right) == -1)
10796 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010797
10798 /* a string is equal to itself */
10799 if (left == right)
10800 return 0;
10801
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010802 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010803 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010804 PyErr_Format(PyExc_TypeError,
10805 "Can't compare %.100s and %.100s",
10806 left->ob_type->tp_name,
10807 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808 return -1;
10809}
10810
Martin v. Löwis5b222132007-06-10 09:51:05 +000010811int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010812_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10813{
10814 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10815 if (right_str == NULL)
10816 return -1;
10817 return PyUnicode_Compare(left, right_str);
10818}
10819
10820int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010821PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10822{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 Py_ssize_t i;
10824 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010825 Py_UCS4 chr;
10826
Victor Stinner910337b2011-10-03 03:20:16 +020010827 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010828 if (PyUnicode_READY(uni) == -1)
10829 return -1;
10830 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010831 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010832 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010833 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010834 size_t len, len2 = strlen(str);
10835 int cmp;
10836
10837 len = Py_MIN(len1, len2);
10838 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010839 if (cmp != 0) {
10840 if (cmp < 0)
10841 return -1;
10842 else
10843 return 1;
10844 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010845 if (len1 > len2)
10846 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010847 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010848 return -1; /* str is longer */
10849 return 0;
10850 }
10851 else {
10852 void *data = PyUnicode_DATA(uni);
10853 /* Compare Unicode string and source character set string */
10854 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010855 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010856 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10857 /* This check keeps Python strings that end in '\0' from comparing equal
10858 to C strings identical up to that point. */
10859 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10860 return 1; /* uni is longer */
10861 if (str[i])
10862 return -1; /* str is longer */
10863 return 0;
10864 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010865}
10866
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010867
Benjamin Peterson29060642009-01-31 22:14:21 +000010868#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010869 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010870
Alexander Belopolsky40018472011-02-26 01:02:56 +000010871PyObject *
10872PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010873{
10874 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010875 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010876
Victor Stinnere5567ad2012-10-23 02:48:49 +020010877 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10878 Py_RETURN_NOTIMPLEMENTED;
10879
10880 if (PyUnicode_READY(left) == -1 ||
10881 PyUnicode_READY(right) == -1)
10882 return NULL;
10883
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010884 if (left == right) {
10885 switch (op) {
10886 case Py_EQ:
10887 case Py_LE:
10888 case Py_GE:
10889 /* a string is equal to itself */
10890 v = Py_True;
10891 break;
10892 case Py_NE:
10893 case Py_LT:
10894 case Py_GT:
10895 v = Py_False;
10896 break;
10897 default:
10898 PyErr_BadArgument();
10899 return NULL;
10900 }
10901 }
10902 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010903 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010904 result ^= (op == Py_NE);
10905 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010906 }
10907 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010908 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010909
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010910 /* Convert the return value to a Boolean */
10911 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010912 case Py_LE:
10913 v = TEST_COND(result <= 0);
10914 break;
10915 case Py_GE:
10916 v = TEST_COND(result >= 0);
10917 break;
10918 case Py_LT:
10919 v = TEST_COND(result == -1);
10920 break;
10921 case Py_GT:
10922 v = TEST_COND(result == 1);
10923 break;
10924 default:
10925 PyErr_BadArgument();
10926 return NULL;
10927 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010928 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010929 Py_INCREF(v);
10930 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010931}
10932
Alexander Belopolsky40018472011-02-26 01:02:56 +000010933int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070010934_PyUnicode_EQ(PyObject *aa, PyObject *bb)
10935{
10936 return unicode_eq(aa, bb);
10937}
10938
10939int
Alexander Belopolsky40018472011-02-26 01:02:56 +000010940PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010941{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010942 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010943 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 void *buf1, *buf2;
10945 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010946 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010947
10948 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010949 sub = PyUnicode_FromObject(element);
10950 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010951 PyErr_Format(PyExc_TypeError,
10952 "'in <string>' requires string as left operand, not %s",
10953 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010954 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010955 }
10956
Thomas Wouters477c8d52006-05-27 19:21:47 +000010957 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010958 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010959 Py_DECREF(sub);
10960 return -1;
10961 }
10962
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 kind1 = PyUnicode_KIND(str);
10964 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010965 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010966 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010967 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010968 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 }
10970 len1 = PyUnicode_GET_LENGTH(str);
10971 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010972 if (len1 < len2) {
10973 Py_DECREF(sub);
10974 Py_DECREF(str);
10975 return 0;
10976 }
10977 buf1 = PyUnicode_DATA(str);
10978 buf2 = PyUnicode_DATA(sub);
10979 if (len2 == 1) {
10980 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10981 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
10982 Py_DECREF(sub);
10983 Py_DECREF(str);
10984 return result;
10985 }
10986 if (kind2 != kind1) {
10987 buf2 = _PyUnicode_AsKind(sub, kind1);
10988 if (!buf2) {
10989 Py_DECREF(sub);
10990 Py_DECREF(str);
10991 return -1;
10992 }
10993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010994
Victor Stinner77282cb2013-04-14 19:22:47 +020010995 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 case PyUnicode_1BYTE_KIND:
10997 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10998 break;
10999 case PyUnicode_2BYTE_KIND:
11000 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11001 break;
11002 case PyUnicode_4BYTE_KIND:
11003 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11004 break;
11005 default:
11006 result = -1;
11007 assert(0);
11008 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011009
11010 Py_DECREF(str);
11011 Py_DECREF(sub);
11012
Victor Stinner77282cb2013-04-14 19:22:47 +020011013 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011014 PyMem_Free(buf2);
11015
Guido van Rossum403d68b2000-03-13 15:55:09 +000011016 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011017}
11018
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019/* Concat to string or Unicode object giving a new Unicode object. */
11020
Alexander Belopolsky40018472011-02-26 01:02:56 +000011021PyObject *
11022PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011024 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011025 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011026 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027
11028 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011029 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011031 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011032 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011034 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035
11036 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011037 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011038 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011041 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044 }
11045
Victor Stinner488fa492011-12-12 00:01:39 +010011046 u_len = PyUnicode_GET_LENGTH(u);
11047 v_len = PyUnicode_GET_LENGTH(v);
11048 if (u_len > PY_SSIZE_T_MAX - v_len) {
11049 PyErr_SetString(PyExc_OverflowError,
11050 "strings are too large to concat");
11051 goto onError;
11052 }
11053 new_len = u_len + v_len;
11054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011056 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011057 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011058
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011060 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011062 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011063 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11064 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065 Py_DECREF(u);
11066 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011067 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011069
Benjamin Peterson29060642009-01-31 22:14:21 +000011070 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071 Py_XDECREF(u);
11072 Py_XDECREF(v);
11073 return NULL;
11074}
11075
Walter Dörwald1ab83302007-05-18 17:15:44 +000011076void
Victor Stinner23e56682011-10-03 03:54:37 +020011077PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011078{
Victor Stinner23e56682011-10-03 03:54:37 +020011079 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011080 Py_UCS4 maxchar, maxchar2;
11081 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011082
11083 if (p_left == NULL) {
11084 if (!PyErr_Occurred())
11085 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011086 return;
11087 }
Victor Stinner23e56682011-10-03 03:54:37 +020011088 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011089 if (right == NULL || left == NULL
11090 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011091 if (!PyErr_Occurred())
11092 PyErr_BadInternalCall();
11093 goto error;
11094 }
11095
Benjamin Petersonbac79492012-01-14 13:34:47 -050011096 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011097 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011098 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011099 goto error;
11100
Victor Stinner488fa492011-12-12 00:01:39 +010011101 /* Shortcuts */
11102 if (left == unicode_empty) {
11103 Py_DECREF(left);
11104 Py_INCREF(right);
11105 *p_left = right;
11106 return;
11107 }
11108 if (right == unicode_empty)
11109 return;
11110
11111 left_len = PyUnicode_GET_LENGTH(left);
11112 right_len = PyUnicode_GET_LENGTH(right);
11113 if (left_len > PY_SSIZE_T_MAX - right_len) {
11114 PyErr_SetString(PyExc_OverflowError,
11115 "strings are too large to concat");
11116 goto error;
11117 }
11118 new_len = left_len + right_len;
11119
11120 if (unicode_modifiable(left)
11121 && PyUnicode_CheckExact(right)
11122 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011123 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11124 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011125 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011126 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011127 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11128 {
11129 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011130 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011131 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011132
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011133 /* copy 'right' into the newly allocated area of 'left' */
11134 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011135 }
Victor Stinner488fa492011-12-12 00:01:39 +010011136 else {
11137 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11138 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011139 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011140
Victor Stinner488fa492011-12-12 00:01:39 +010011141 /* Concat the two Unicode strings */
11142 res = PyUnicode_New(new_len, maxchar);
11143 if (res == NULL)
11144 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011145 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11146 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011147 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011148 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011149 }
11150 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011151 return;
11152
11153error:
Victor Stinner488fa492011-12-12 00:01:39 +010011154 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011155}
11156
11157void
11158PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11159{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011160 PyUnicode_Append(pleft, right);
11161 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011162}
11163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011164PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011165 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011167Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011168string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011169interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170
11171static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011172unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011174 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011175 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011176 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011178 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 void *buf1, *buf2;
11180 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181
Jesus Ceaac451502011-04-20 17:09:23 +020011182 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11183 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011184 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011185
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 kind1 = PyUnicode_KIND(self);
11187 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011188 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011189 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011190 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 len1 = PyUnicode_GET_LENGTH(self);
11193 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011194 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011195 if (end - start < len2) {
11196 Py_DECREF(substring);
11197 return PyLong_FromLong(0);
11198 }
11199 buf1 = PyUnicode_DATA(self);
11200 buf2 = PyUnicode_DATA(substring);
11201 if (kind2 != kind1) {
11202 buf2 = _PyUnicode_AsKind(substring, kind1);
11203 if (!buf2) {
11204 Py_DECREF(substring);
11205 return NULL;
11206 }
11207 }
11208 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 case PyUnicode_1BYTE_KIND:
11210 iresult = ucs1lib_count(
11211 ((Py_UCS1*)buf1) + start, end - start,
11212 buf2, len2, PY_SSIZE_T_MAX
11213 );
11214 break;
11215 case PyUnicode_2BYTE_KIND:
11216 iresult = ucs2lib_count(
11217 ((Py_UCS2*)buf1) + start, end - start,
11218 buf2, len2, PY_SSIZE_T_MAX
11219 );
11220 break;
11221 case PyUnicode_4BYTE_KIND:
11222 iresult = ucs4lib_count(
11223 ((Py_UCS4*)buf1) + start, end - start,
11224 buf2, len2, PY_SSIZE_T_MAX
11225 );
11226 break;
11227 default:
11228 assert(0); iresult = 0;
11229 }
11230
11231 result = PyLong_FromSsize_t(iresult);
11232
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011233 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235
11236 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011237
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238 return result;
11239}
11240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011241PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011242 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011244Encode S using the codec registered for encoding. Default encoding\n\
11245is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011246handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011247a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11248'xmlcharrefreplace' as well as any other name registered with\n\
11249codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250
11251static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011252unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011254 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 char *encoding = NULL;
11256 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011257
Benjamin Peterson308d6372009-09-18 21:42:35 +000011258 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11259 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011261 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011262}
11263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011264PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011265 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266\n\
11267Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011268If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
11270static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011271unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011273 Py_ssize_t i, j, line_pos, src_len, incr;
11274 Py_UCS4 ch;
11275 PyObject *u;
11276 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011277 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011279 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011280 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
Ezio Melotti745d54d2013-11-16 19:10:57 +020011282 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11283 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285
Antoine Pitrou22425222011-10-04 19:10:51 +020011286 if (PyUnicode_READY(self) == -1)
11287 return NULL;
11288
Thomas Wouters7e474022000-07-16 12:04:32 +000011289 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011290 src_len = PyUnicode_GET_LENGTH(self);
11291 i = j = line_pos = 0;
11292 kind = PyUnicode_KIND(self);
11293 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011294 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011295 for (; i < src_len; i++) {
11296 ch = PyUnicode_READ(kind, src_data, i);
11297 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011298 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011299 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011300 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011301 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011302 goto overflow;
11303 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011304 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011305 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011306 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011308 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011309 goto overflow;
11310 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011312 if (ch == '\n' || ch == '\r')
11313 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011315 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011316 if (!found)
11317 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011318
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011320 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321 if (!u)
11322 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011323 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
Antoine Pitroue71d5742011-10-04 15:55:09 +020011325 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326
Antoine Pitroue71d5742011-10-04 15:55:09 +020011327 for (; i < src_len; i++) {
11328 ch = PyUnicode_READ(kind, src_data, i);
11329 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011330 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011331 incr = tabsize - (line_pos % tabsize);
11332 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011333 FILL(kind, dest_data, ' ', j, incr);
11334 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011336 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011337 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011338 line_pos++;
11339 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011340 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011341 if (ch == '\n' || ch == '\r')
11342 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011344 }
11345 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011346 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011347
Antoine Pitroue71d5742011-10-04 15:55:09 +020011348 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011349 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11350 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351}
11352
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011353PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011354 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355\n\
11356Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011357such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358arguments start and end are interpreted as in slice notation.\n\
11359\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011360Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361
11362static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011365 /* initialize variables to prevent gcc warning */
11366 PyObject *substring = NULL;
11367 Py_ssize_t start = 0;
11368 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011369 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370
Jesus Ceaac451502011-04-20 17:09:23 +020011371 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11372 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374
Christian Heimesd47802e2013-06-29 21:33:36 +020011375 if (PyUnicode_READY(self) == -1) {
11376 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011378 }
11379 if (PyUnicode_READY(substring) == -1) {
11380 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011382 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383
Victor Stinner7931d9a2011-11-04 00:22:48 +010011384 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
11386 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011388 if (result == -2)
11389 return NULL;
11390
Christian Heimes217cfd12007-12-02 14:31:20 +000011391 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392}
11393
11394static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011395unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011397 void *data;
11398 enum PyUnicode_Kind kind;
11399 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011400
11401 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11402 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011404 }
11405 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11406 PyErr_SetString(PyExc_IndexError, "string index out of range");
11407 return NULL;
11408 }
11409 kind = PyUnicode_KIND(self);
11410 data = PyUnicode_DATA(self);
11411 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011412 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413}
11414
Guido van Rossumc2504932007-09-18 19:42:40 +000011415/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011416 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011417static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011418unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419{
Guido van Rossumc2504932007-09-18 19:42:40 +000011420 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011421 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011422
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011423#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011424 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011425#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011426 if (_PyUnicode_HASH(self) != -1)
11427 return _PyUnicode_HASH(self);
11428 if (PyUnicode_READY(self) == -1)
11429 return -1;
11430 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011431 /*
11432 We make the hash of the empty string be 0, rather than using
11433 (prefix ^ suffix), since this slightly obfuscates the hash secret
11434 */
11435 if (len == 0) {
11436 _PyUnicode_HASH(self) = 0;
11437 return 0;
11438 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011439 x = _Py_HashBytes(PyUnicode_DATA(self),
11440 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011442 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443}
11444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011445PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011448Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
11450static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011453 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011454 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011455 PyObject *substring = NULL;
11456 Py_ssize_t start = 0;
11457 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458
Jesus Ceaac451502011-04-20 17:09:23 +020011459 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11460 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Christian Heimesd47a0452013-06-29 21:21:37 +020011463 if (PyUnicode_READY(self) == -1) {
11464 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011466 }
11467 if (PyUnicode_READY(substring) == -1) {
11468 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011470 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471
Victor Stinner7931d9a2011-11-04 00:22:48 +010011472 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473
11474 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (result == -2)
11477 return NULL;
11478
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479 if (result < 0) {
11480 PyErr_SetString(PyExc_ValueError, "substring not found");
11481 return NULL;
11482 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011483
Christian Heimes217cfd12007-12-02 14:31:20 +000011484 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485}
11486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011487PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011490Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011491at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492
11493static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011494unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 Py_ssize_t i, length;
11497 int kind;
11498 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 int cased;
11500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501 if (PyUnicode_READY(self) == -1)
11502 return NULL;
11503 length = PyUnicode_GET_LENGTH(self);
11504 kind = PyUnicode_KIND(self);
11505 data = PyUnicode_DATA(self);
11506
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 if (length == 1)
11509 return PyBool_FromLong(
11510 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011512 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011515
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 for (i = 0; i < length; i++) {
11518 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011519
Benjamin Peterson29060642009-01-31 22:14:21 +000011520 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11521 return PyBool_FromLong(0);
11522 else if (!cased && Py_UNICODE_ISLOWER(ch))
11523 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011525 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526}
11527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011528PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011529 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011531Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011532at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533
11534static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011535unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 Py_ssize_t i, length;
11538 int kind;
11539 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540 int cased;
11541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (PyUnicode_READY(self) == -1)
11543 return NULL;
11544 length = PyUnicode_GET_LENGTH(self);
11545 kind = PyUnicode_KIND(self);
11546 data = PyUnicode_DATA(self);
11547
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 if (length == 1)
11550 return PyBool_FromLong(
11551 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011553 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011555 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011556
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 for (i = 0; i < length; i++) {
11559 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011560
Benjamin Peterson29060642009-01-31 22:14:21 +000011561 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11562 return PyBool_FromLong(0);
11563 else if (!cased && Py_UNICODE_ISUPPER(ch))
11564 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011566 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567}
11568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011569PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011572Return True if S is a titlecased string and there is at least one\n\
11573character in S, i.e. upper- and titlecase characters may only\n\
11574follow uncased characters and lowercase characters only cased ones.\n\
11575Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
11577static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011578unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 Py_ssize_t i, length;
11581 int kind;
11582 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 int cased, previous_is_cased;
11584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 if (PyUnicode_READY(self) == -1)
11586 return NULL;
11587 length = PyUnicode_GET_LENGTH(self);
11588 kind = PyUnicode_KIND(self);
11589 data = PyUnicode_DATA(self);
11590
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011592 if (length == 1) {
11593 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11594 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11595 (Py_UNICODE_ISUPPER(ch) != 0));
11596 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011598 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011599 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011600 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011601
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602 cased = 0;
11603 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 for (i = 0; i < length; i++) {
11605 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011606
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11608 if (previous_is_cased)
11609 return PyBool_FromLong(0);
11610 previous_is_cased = 1;
11611 cased = 1;
11612 }
11613 else if (Py_UNICODE_ISLOWER(ch)) {
11614 if (!previous_is_cased)
11615 return PyBool_FromLong(0);
11616 previous_is_cased = 1;
11617 cased = 1;
11618 }
11619 else
11620 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011622 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623}
11624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011625PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011626 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011628Return True if all characters in S are whitespace\n\
11629and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630
11631static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011632unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 Py_ssize_t i, length;
11635 int kind;
11636 void *data;
11637
11638 if (PyUnicode_READY(self) == -1)
11639 return NULL;
11640 length = PyUnicode_GET_LENGTH(self);
11641 kind = PyUnicode_KIND(self);
11642 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 if (length == 1)
11646 return PyBool_FromLong(
11647 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011648
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011649 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011650 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011651 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 for (i = 0; i < length; i++) {
11654 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011655 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011656 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011658 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659}
11660
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011661PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011662 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011663\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011664Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011665and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011666
11667static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011668unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011669{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 Py_ssize_t i, length;
11671 int kind;
11672 void *data;
11673
11674 if (PyUnicode_READY(self) == -1)
11675 return NULL;
11676 length = PyUnicode_GET_LENGTH(self);
11677 kind = PyUnicode_KIND(self);
11678 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011679
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011680 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (length == 1)
11682 return PyBool_FromLong(
11683 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011684
11685 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011687 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 for (i = 0; i < length; i++) {
11690 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011692 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011693 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011694}
11695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011696PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011698\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011699Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011700and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011701
11702static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011703unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011704{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 int kind;
11706 void *data;
11707 Py_ssize_t len, i;
11708
11709 if (PyUnicode_READY(self) == -1)
11710 return NULL;
11711
11712 kind = PyUnicode_KIND(self);
11713 data = PyUnicode_DATA(self);
11714 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011715
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011716 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (len == 1) {
11718 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11719 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11720 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011721
11722 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011724 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 for (i = 0; i < len; i++) {
11727 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011728 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011729 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011730 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011731 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011732}
11733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011734PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011735 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011737Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011738False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739
11740static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011741unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 Py_ssize_t i, length;
11744 int kind;
11745 void *data;
11746
11747 if (PyUnicode_READY(self) == -1)
11748 return NULL;
11749 length = PyUnicode_GET_LENGTH(self);
11750 kind = PyUnicode_KIND(self);
11751 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 if (length == 1)
11755 return PyBool_FromLong(
11756 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011758 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011760 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 for (i = 0; i < length; i++) {
11763 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011766 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767}
11768
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011769PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011770 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011772Return True if all characters in S are digits\n\
11773and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774
11775static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011776unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 Py_ssize_t i, length;
11779 int kind;
11780 void *data;
11781
11782 if (PyUnicode_READY(self) == -1)
11783 return NULL;
11784 length = PyUnicode_GET_LENGTH(self);
11785 kind = PyUnicode_KIND(self);
11786 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011789 if (length == 1) {
11790 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11791 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11792 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011794 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011796 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 for (i = 0; i < length; i++) {
11799 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011800 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011802 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803}
11804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011805PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011806 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011808Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011809False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810
11811static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011812unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 Py_ssize_t i, length;
11815 int kind;
11816 void *data;
11817
11818 if (PyUnicode_READY(self) == -1)
11819 return NULL;
11820 length = PyUnicode_GET_LENGTH(self);
11821 kind = PyUnicode_KIND(self);
11822 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 if (length == 1)
11826 return PyBool_FromLong(
11827 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011829 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011831 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011833 for (i = 0; i < length; i++) {
11834 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011835 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011837 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838}
11839
Martin v. Löwis47383402007-08-15 07:32:56 +000011840int
11841PyUnicode_IsIdentifier(PyObject *self)
11842{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 int kind;
11844 void *data;
11845 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011846 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011847
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 if (PyUnicode_READY(self) == -1) {
11849 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 }
11852
11853 /* Special case for empty strings */
11854 if (PyUnicode_GET_LENGTH(self) == 0)
11855 return 0;
11856 kind = PyUnicode_KIND(self);
11857 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011858
11859 /* PEP 3131 says that the first character must be in
11860 XID_Start and subsequent characters in XID_Continue,
11861 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011862 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011863 letters, digits, underscore). However, given the current
11864 definition of XID_Start and XID_Continue, it is sufficient
11865 to check just for these, except that _ must be allowed
11866 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011868 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011869 return 0;
11870
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011871 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011873 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011874 return 1;
11875}
11876
11877PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011879\n\
11880Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011881to the language definition.\n\
11882\n\
11883Use keyword.iskeyword() to test for reserved identifiers\n\
11884such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011885
11886static PyObject*
11887unicode_isidentifier(PyObject *self)
11888{
11889 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11890}
11891
Georg Brandl559e5d72008-06-11 18:37:52 +000011892PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011893 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011894\n\
11895Return True if all characters in S are considered\n\
11896printable in repr() or S is empty, False otherwise.");
11897
11898static PyObject*
11899unicode_isprintable(PyObject *self)
11900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 Py_ssize_t i, length;
11902 int kind;
11903 void *data;
11904
11905 if (PyUnicode_READY(self) == -1)
11906 return NULL;
11907 length = PyUnicode_GET_LENGTH(self);
11908 kind = PyUnicode_KIND(self);
11909 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011910
11911 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (length == 1)
11913 return PyBool_FromLong(
11914 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 for (i = 0; i < length; i++) {
11917 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011918 Py_RETURN_FALSE;
11919 }
11920 }
11921 Py_RETURN_TRUE;
11922}
11923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011924PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011925 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926\n\
11927Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011928iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929
11930static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011931unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011933 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934}
11935
Martin v. Löwis18e16552006-02-15 17:27:45 +000011936static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011937unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 if (PyUnicode_READY(self) == -1)
11940 return -1;
11941 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942}
11943
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011944PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011947Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011948done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949
11950static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011951unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011953 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 Py_UCS4 fillchar = ' ';
11955
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011956 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957 return NULL;
11958
Benjamin Petersonbac79492012-01-14 13:34:47 -050011959 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011960 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011961
Victor Stinnerc4b49542011-12-11 22:44:26 +010011962 if (PyUnicode_GET_LENGTH(self) >= width)
11963 return unicode_result_unchanged(self);
11964
11965 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966}
11967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011968PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011969 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011971Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972
11973static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011974unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011976 if (PyUnicode_READY(self) == -1)
11977 return NULL;
11978 if (PyUnicode_IS_ASCII(self))
11979 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011980 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981}
11982
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011983#define LEFTSTRIP 0
11984#define RIGHTSTRIP 1
11985#define BOTHSTRIP 2
11986
11987/* Arrays indexed by above */
11988static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11989
11990#define STRIPNAME(i) (stripformat[i]+3)
11991
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011992/* externally visible for str.strip(unicode) */
11993PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011994_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 void *data;
11997 int kind;
11998 Py_ssize_t i, j, len;
11999 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012000 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12003 return NULL;
12004
12005 kind = PyUnicode_KIND(self);
12006 data = PyUnicode_DATA(self);
12007 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012008 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12010 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012011 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012012
Benjamin Peterson14339b62009-01-31 16:36:08 +000012013 i = 0;
12014 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012015 while (i < len) {
12016 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12017 if (!BLOOM(sepmask, ch))
12018 break;
12019 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12020 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012021 i++;
12022 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012023 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012024
Benjamin Peterson14339b62009-01-31 16:36:08 +000012025 j = len;
12026 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012027 j--;
12028 while (j >= i) {
12029 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12030 if (!BLOOM(sepmask, ch))
12031 break;
12032 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12033 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012034 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012035 }
12036
Benjamin Peterson29060642009-01-31 22:14:21 +000012037 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012038 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012039
Victor Stinner7931d9a2011-11-04 00:22:48 +010012040 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041}
12042
12043PyObject*
12044PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12045{
12046 unsigned char *data;
12047 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012048 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049
Victor Stinnerde636f32011-10-01 03:55:54 +020012050 if (PyUnicode_READY(self) == -1)
12051 return NULL;
12052
Victor Stinner684d5fd2012-05-03 02:32:34 +020012053 length = PyUnicode_GET_LENGTH(self);
12054 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012055
Victor Stinner684d5fd2012-05-03 02:32:34 +020012056 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012057 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058
Victor Stinnerde636f32011-10-01 03:55:54 +020012059 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012060 PyErr_SetString(PyExc_IndexError, "string index out of range");
12061 return NULL;
12062 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012063 if (start >= length || end < start)
12064 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012065
Victor Stinner684d5fd2012-05-03 02:32:34 +020012066 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012067 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012068 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012069 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012070 }
12071 else {
12072 kind = PyUnicode_KIND(self);
12073 data = PyUnicode_1BYTE_DATA(self);
12074 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012075 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012076 length);
12077 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012078}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
12080static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012081do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012082{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 Py_ssize_t len, i, j;
12084
12085 if (PyUnicode_READY(self) == -1)
12086 return NULL;
12087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012089
Victor Stinnercc7af722013-04-09 22:39:24 +020012090 if (PyUnicode_IS_ASCII(self)) {
12091 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12092
12093 i = 0;
12094 if (striptype != RIGHTSTRIP) {
12095 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012096 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012097 if (!_Py_ascii_whitespace[ch])
12098 break;
12099 i++;
12100 }
12101 }
12102
12103 j = len;
12104 if (striptype != LEFTSTRIP) {
12105 j--;
12106 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012107 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012108 if (!_Py_ascii_whitespace[ch])
12109 break;
12110 j--;
12111 }
12112 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012113 }
12114 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012115 else {
12116 int kind = PyUnicode_KIND(self);
12117 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012118
Victor Stinnercc7af722013-04-09 22:39:24 +020012119 i = 0;
12120 if (striptype != RIGHTSTRIP) {
12121 while (i < len) {
12122 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12123 if (!Py_UNICODE_ISSPACE(ch))
12124 break;
12125 i++;
12126 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012127 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012128
12129 j = len;
12130 if (striptype != LEFTSTRIP) {
12131 j--;
12132 while (j >= i) {
12133 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12134 if (!Py_UNICODE_ISSPACE(ch))
12135 break;
12136 j--;
12137 }
12138 j++;
12139 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012140 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141
Victor Stinner7931d9a2011-11-04 00:22:48 +010012142 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143}
12144
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145
12146static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012147do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012148{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012149 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012150
Serhiy Storchakac6792272013-10-19 21:03:34 +030012151 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012152 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012153
Benjamin Peterson14339b62009-01-31 16:36:08 +000012154 if (sep != NULL && sep != Py_None) {
12155 if (PyUnicode_Check(sep))
12156 return _PyUnicode_XStrip(self, striptype, sep);
12157 else {
12158 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 "%s arg must be None or str",
12160 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012161 return NULL;
12162 }
12163 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012164
Benjamin Peterson14339b62009-01-31 16:36:08 +000012165 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166}
12167
12168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012169PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012170 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012171\n\
12172Return a copy of the string S with leading and trailing\n\
12173whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012174If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012175
12176static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012177unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012178{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012179 if (PyTuple_GET_SIZE(args) == 0)
12180 return do_strip(self, BOTHSTRIP); /* Common case */
12181 else
12182 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012183}
12184
12185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012186PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012187 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012188\n\
12189Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012190If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012191
12192static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012193unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012194{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012195 if (PyTuple_GET_SIZE(args) == 0)
12196 return do_strip(self, LEFTSTRIP); /* Common case */
12197 else
12198 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012199}
12200
12201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012202PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012203 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012204\n\
12205Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012206If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012207
12208static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012209unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012210{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012211 if (PyTuple_GET_SIZE(args) == 0)
12212 return do_strip(self, RIGHTSTRIP); /* Common case */
12213 else
12214 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012215}
12216
12217
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012219unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012221 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223
Serhiy Storchaka05997252013-01-26 12:14:02 +020012224 if (len < 1)
12225 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226
Victor Stinnerc4b49542011-12-11 22:44:26 +010012227 /* no repeat, return original string */
12228 if (len == 1)
12229 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012230
Benjamin Petersonbac79492012-01-14 13:34:47 -050012231 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232 return NULL;
12233
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012234 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012235 PyErr_SetString(PyExc_OverflowError,
12236 "repeated string is too long");
12237 return NULL;
12238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012240
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012241 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242 if (!u)
12243 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012244 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012246 if (PyUnicode_GET_LENGTH(str) == 1) {
12247 const int kind = PyUnicode_KIND(str);
12248 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012249 if (kind == PyUnicode_1BYTE_KIND) {
12250 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012251 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012252 }
12253 else if (kind == PyUnicode_2BYTE_KIND) {
12254 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012255 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012256 ucs2[n] = fill_char;
12257 } else {
12258 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12259 assert(kind == PyUnicode_4BYTE_KIND);
12260 for (n = 0; n < len; ++n)
12261 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 }
12264 else {
12265 /* number of characters copied this far */
12266 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012267 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268 char *to = (char *) PyUnicode_DATA(u);
12269 Py_MEMCPY(to, PyUnicode_DATA(str),
12270 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012271 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 n = (done <= nchars-done) ? done : nchars-done;
12273 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012274 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012275 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276 }
12277
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012278 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012279 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280}
12281
Alexander Belopolsky40018472011-02-26 01:02:56 +000012282PyObject *
12283PyUnicode_Replace(PyObject *obj,
12284 PyObject *subobj,
12285 PyObject *replobj,
12286 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287{
12288 PyObject *self;
12289 PyObject *str1;
12290 PyObject *str2;
12291 PyObject *result;
12292
12293 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012294 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012295 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012297 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012298 Py_DECREF(self);
12299 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300 }
12301 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012302 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012303 Py_DECREF(self);
12304 Py_DECREF(str1);
12305 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012307 if (PyUnicode_READY(self) == -1 ||
12308 PyUnicode_READY(str1) == -1 ||
12309 PyUnicode_READY(str2) == -1)
12310 result = NULL;
12311 else
12312 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313 Py_DECREF(self);
12314 Py_DECREF(str1);
12315 Py_DECREF(str2);
12316 return result;
12317}
12318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012319PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012320 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321\n\
12322Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012323old replaced by new. If the optional argument count is\n\
12324given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325
12326static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012329 PyObject *str1;
12330 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012331 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012332 PyObject *result;
12333
Martin v. Löwis18e16552006-02-15 17:27:45 +000012334 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012335 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012336 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012337 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012339 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 return NULL;
12341 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012342 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012343 Py_DECREF(str1);
12344 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012345 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012346 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12347 result = NULL;
12348 else
12349 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350
12351 Py_DECREF(str1);
12352 Py_DECREF(str2);
12353 return result;
12354}
12355
Alexander Belopolsky40018472011-02-26 01:02:56 +000012356static PyObject *
12357unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012358{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012359 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012360 Py_ssize_t isize;
12361 Py_ssize_t osize, squote, dquote, i, o;
12362 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012363 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012367 return NULL;
12368
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 isize = PyUnicode_GET_LENGTH(unicode);
12370 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012371
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012372 /* Compute length of output, quote characters, and
12373 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012374 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 max = 127;
12376 squote = dquote = 0;
12377 ikind = PyUnicode_KIND(unicode);
12378 for (i = 0; i < isize; i++) {
12379 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012380 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012382 case '\'': squote++; break;
12383 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012385 incr = 2;
12386 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387 default:
12388 /* Fast-path ASCII */
12389 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012390 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012392 ;
12393 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012396 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012398 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012400 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012402 if (osize > PY_SSIZE_T_MAX - incr) {
12403 PyErr_SetString(PyExc_OverflowError,
12404 "string is too long to generate repr");
12405 return NULL;
12406 }
12407 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012408 }
12409
12410 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012411 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012413 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 if (dquote)
12415 /* Both squote and dquote present. Use squote,
12416 and escape them */
12417 osize += squote;
12418 else
12419 quote = '"';
12420 }
Victor Stinner55c08782013-04-14 18:45:39 +020012421 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422
12423 repr = PyUnicode_New(osize, max);
12424 if (repr == NULL)
12425 return NULL;
12426 okind = PyUnicode_KIND(repr);
12427 odata = PyUnicode_DATA(repr);
12428
12429 PyUnicode_WRITE(okind, odata, 0, quote);
12430 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012431 if (unchanged) {
12432 _PyUnicode_FastCopyCharacters(repr, 1,
12433 unicode, 0,
12434 isize);
12435 }
12436 else {
12437 for (i = 0, o = 1; i < isize; i++) {
12438 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439
Victor Stinner55c08782013-04-14 18:45:39 +020012440 /* Escape quotes and backslashes */
12441 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012442 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012444 continue;
12445 }
12446
12447 /* Map special whitespace to '\t', \n', '\r' */
12448 if (ch == '\t') {
12449 PyUnicode_WRITE(okind, odata, o++, '\\');
12450 PyUnicode_WRITE(okind, odata, o++, 't');
12451 }
12452 else if (ch == '\n') {
12453 PyUnicode_WRITE(okind, odata, o++, '\\');
12454 PyUnicode_WRITE(okind, odata, o++, 'n');
12455 }
12456 else if (ch == '\r') {
12457 PyUnicode_WRITE(okind, odata, o++, '\\');
12458 PyUnicode_WRITE(okind, odata, o++, 'r');
12459 }
12460
12461 /* Map non-printable US ASCII to '\xhh' */
12462 else if (ch < ' ' || ch == 0x7F) {
12463 PyUnicode_WRITE(okind, odata, o++, '\\');
12464 PyUnicode_WRITE(okind, odata, o++, 'x');
12465 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12466 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12467 }
12468
12469 /* Copy ASCII characters as-is */
12470 else if (ch < 0x7F) {
12471 PyUnicode_WRITE(okind, odata, o++, ch);
12472 }
12473
12474 /* Non-ASCII characters */
12475 else {
12476 /* Map Unicode whitespace and control characters
12477 (categories Z* and C* except ASCII space)
12478 */
12479 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12480 PyUnicode_WRITE(okind, odata, o++, '\\');
12481 /* Map 8-bit characters to '\xhh' */
12482 if (ch <= 0xff) {
12483 PyUnicode_WRITE(okind, odata, o++, 'x');
12484 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12485 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12486 }
12487 /* Map 16-bit characters to '\uxxxx' */
12488 else if (ch <= 0xffff) {
12489 PyUnicode_WRITE(okind, odata, o++, 'u');
12490 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12491 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12492 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12493 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12494 }
12495 /* Map 21-bit characters to '\U00xxxxxx' */
12496 else {
12497 PyUnicode_WRITE(okind, odata, o++, 'U');
12498 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12499 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12500 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12501 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12502 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12503 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12504 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12505 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12506 }
12507 }
12508 /* Copy characters as-is */
12509 else {
12510 PyUnicode_WRITE(okind, odata, o++, ch);
12511 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012512 }
12513 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012516 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012517 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518}
12519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012520PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012521 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522\n\
12523Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012524such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525arguments start and end are interpreted as in slice notation.\n\
12526\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012527Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528
12529static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012530unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012532 /* initialize variables to prevent gcc warning */
12533 PyObject *substring = NULL;
12534 Py_ssize_t start = 0;
12535 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012536 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537
Jesus Ceaac451502011-04-20 17:09:23 +020012538 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12539 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012540 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541
Christian Heimesea71a522013-06-29 21:17:34 +020012542 if (PyUnicode_READY(self) == -1) {
12543 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012545 }
12546 if (PyUnicode_READY(substring) == -1) {
12547 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550
Victor Stinner7931d9a2011-11-04 00:22:48 +010012551 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552
12553 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 if (result == -2)
12556 return NULL;
12557
Christian Heimes217cfd12007-12-02 14:31:20 +000012558 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559}
12560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012561PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012562 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012563\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012564Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565
12566static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012569 /* initialize variables to prevent gcc warning */
12570 PyObject *substring = NULL;
12571 Py_ssize_t start = 0;
12572 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012573 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574
Jesus Ceaac451502011-04-20 17:09:23 +020012575 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12576 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012577 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578
Christian Heimesea71a522013-06-29 21:17:34 +020012579 if (PyUnicode_READY(self) == -1) {
12580 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012582 }
12583 if (PyUnicode_READY(substring) == -1) {
12584 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587
Victor Stinner7931d9a2011-11-04 00:22:48 +010012588 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589
12590 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 if (result == -2)
12593 return NULL;
12594
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595 if (result < 0) {
12596 PyErr_SetString(PyExc_ValueError, "substring not found");
12597 return NULL;
12598 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599
Christian Heimes217cfd12007-12-02 14:31:20 +000012600 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012601}
12602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012603PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012604 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012606Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012607done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608
12609static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012610unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012612 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 Py_UCS4 fillchar = ' ';
12614
Victor Stinnere9a29352011-10-01 02:14:59 +020012615 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012617
Benjamin Petersonbac79492012-01-14 13:34:47 -050012618 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619 return NULL;
12620
Victor Stinnerc4b49542011-12-11 22:44:26 +010012621 if (PyUnicode_GET_LENGTH(self) >= width)
12622 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623
Victor Stinnerc4b49542011-12-11 22:44:26 +010012624 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625}
12626
Alexander Belopolsky40018472011-02-26 01:02:56 +000012627PyObject *
12628PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629{
12630 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012631
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632 s = PyUnicode_FromObject(s);
12633 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012634 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012635 if (sep != NULL) {
12636 sep = PyUnicode_FromObject(sep);
12637 if (sep == NULL) {
12638 Py_DECREF(s);
12639 return NULL;
12640 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641 }
12642
Victor Stinner9310abb2011-10-05 00:59:23 +020012643 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644
12645 Py_DECREF(s);
12646 Py_XDECREF(sep);
12647 return result;
12648}
12649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012650PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012651 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652\n\
12653Return a list of the words in S, using sep as the\n\
12654delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012655splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012656whitespace string is a separator and empty strings are\n\
12657removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658
12659static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012660unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012662 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012664 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012666 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12667 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012668 return NULL;
12669
12670 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012671 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012672 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012673 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012675 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676}
12677
Thomas Wouters477c8d52006-05-27 19:21:47 +000012678PyObject *
12679PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12680{
12681 PyObject* str_obj;
12682 PyObject* sep_obj;
12683 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012684 int kind1, kind2;
12685 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012687
12688 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012689 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012690 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012691 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012692 if (!sep_obj) {
12693 Py_DECREF(str_obj);
12694 return NULL;
12695 }
12696 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12697 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012698 Py_DECREF(str_obj);
12699 return NULL;
12700 }
12701
Victor Stinner14f8f022011-10-05 20:58:25 +020012702 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704 len1 = PyUnicode_GET_LENGTH(str_obj);
12705 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012706 if (kind1 < kind2 || len1 < len2) {
12707 _Py_INCREF_UNICODE_EMPTY();
12708 if (!unicode_empty)
12709 out = NULL;
12710 else {
12711 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12712 Py_DECREF(unicode_empty);
12713 }
12714 Py_DECREF(sep_obj);
12715 Py_DECREF(str_obj);
12716 return out;
12717 }
12718 buf1 = PyUnicode_DATA(str_obj);
12719 buf2 = PyUnicode_DATA(sep_obj);
12720 if (kind2 != kind1) {
12721 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12722 if (!buf2)
12723 goto onError;
12724 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012726 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012728 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12729 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12730 else
12731 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012732 break;
12733 case PyUnicode_2BYTE_KIND:
12734 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12735 break;
12736 case PyUnicode_4BYTE_KIND:
12737 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12738 break;
12739 default:
12740 assert(0);
12741 out = 0;
12742 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012743
12744 Py_DECREF(sep_obj);
12745 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012746 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012748
12749 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 onError:
12751 Py_DECREF(sep_obj);
12752 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012753 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754 PyMem_Free(buf2);
12755 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012756}
12757
12758
12759PyObject *
12760PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12761{
12762 PyObject* str_obj;
12763 PyObject* sep_obj;
12764 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012765 int kind1, kind2;
12766 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012768
12769 str_obj = PyUnicode_FromObject(str_in);
12770 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012772 sep_obj = PyUnicode_FromObject(sep_in);
12773 if (!sep_obj) {
12774 Py_DECREF(str_obj);
12775 return NULL;
12776 }
12777
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012778 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012779 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012780 len1 = PyUnicode_GET_LENGTH(str_obj);
12781 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012782 if (kind1 < kind2 || len1 < len2) {
12783 _Py_INCREF_UNICODE_EMPTY();
12784 if (!unicode_empty)
12785 out = NULL;
12786 else {
12787 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12788 Py_DECREF(unicode_empty);
12789 }
12790 Py_DECREF(sep_obj);
12791 Py_DECREF(str_obj);
12792 return out;
12793 }
12794 buf1 = PyUnicode_DATA(str_obj);
12795 buf2 = PyUnicode_DATA(sep_obj);
12796 if (kind2 != kind1) {
12797 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12798 if (!buf2)
12799 goto onError;
12800 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012801
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012802 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012804 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12805 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12806 else
12807 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 break;
12809 case PyUnicode_2BYTE_KIND:
12810 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12811 break;
12812 case PyUnicode_4BYTE_KIND:
12813 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12814 break;
12815 default:
12816 assert(0);
12817 out = 0;
12818 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012819
12820 Py_DECREF(sep_obj);
12821 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012822 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012823 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012824
12825 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012826 onError:
12827 Py_DECREF(sep_obj);
12828 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012829 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830 PyMem_Free(buf2);
12831 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832}
12833
12834PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012837Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012838the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012839found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012840
12841static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012842unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012843{
Victor Stinner9310abb2011-10-05 00:59:23 +020012844 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012845}
12846
12847PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012848 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012850Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012851the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012852separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853
12854static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012855unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856{
Victor Stinner9310abb2011-10-05 00:59:23 +020012857 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012858}
12859
Alexander Belopolsky40018472011-02-26 01:02:56 +000012860PyObject *
12861PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012862{
12863 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012864
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012865 s = PyUnicode_FromObject(s);
12866 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012867 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012868 if (sep != NULL) {
12869 sep = PyUnicode_FromObject(sep);
12870 if (sep == NULL) {
12871 Py_DECREF(s);
12872 return NULL;
12873 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012874 }
12875
Victor Stinner9310abb2011-10-05 00:59:23 +020012876 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012877
12878 Py_DECREF(s);
12879 Py_XDECREF(sep);
12880 return result;
12881}
12882
12883PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012884 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012885\n\
12886Return a list of the words in S, using sep as the\n\
12887delimiter string, starting at the end of the string and\n\
12888working to the front. If maxsplit is given, at most maxsplit\n\
12889splits are done. If sep is not specified, any whitespace string\n\
12890is a separator.");
12891
12892static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012893unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012894{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012895 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012896 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012897 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012898
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012899 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12900 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012901 return NULL;
12902
12903 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012904 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012905 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012906 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012907 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012908 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012909}
12910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012911PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012912 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913\n\
12914Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012915Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012916is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012917
12918static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012919unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012921 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012922 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012924 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12925 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926 return NULL;
12927
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012928 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012929}
12930
12931static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012932PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012934 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935}
12936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012937PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012938 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012939\n\
12940Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012941and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942
12943static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012944unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012946 if (PyUnicode_READY(self) == -1)
12947 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012948 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012949}
12950
Larry Hastings61272b72014-01-07 12:41:53 -080012951/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012952
Larry Hastings31826802013-10-19 00:09:25 -070012953@staticmethod
12954str.maketrans as unicode_maketrans
12955
12956 x: object
12957
12958 y: unicode=NULL
12959
12960 z: unicode=NULL
12961
12962 /
12963
12964Return a translation table usable for str.translate().
12965
12966If there is only one argument, it must be a dictionary mapping Unicode
12967ordinals (integers) or characters to Unicode ordinals, strings or None.
12968Character keys will be then converted to ordinals.
12969If there are two arguments, they must be strings of equal length, and
12970in the resulting dictionary, each character in x will be mapped to the
12971character at the same position in y. If there is a third argument, it
12972must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012973[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012974
Larry Hastings31826802013-10-19 00:09:25 -070012975static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012976unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012977/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012978{
Georg Brandlceee0772007-11-27 23:48:05 +000012979 PyObject *new = NULL, *key, *value;
12980 Py_ssize_t i = 0;
12981 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012982
Georg Brandlceee0772007-11-27 23:48:05 +000012983 new = PyDict_New();
12984 if (!new)
12985 return NULL;
12986 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 int x_kind, y_kind, z_kind;
12988 void *x_data, *y_data, *z_data;
12989
Georg Brandlceee0772007-11-27 23:48:05 +000012990 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012991 if (!PyUnicode_Check(x)) {
12992 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12993 "be a string if there is a second argument");
12994 goto err;
12995 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012997 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12998 "arguments must have equal length");
12999 goto err;
13000 }
13001 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 x_kind = PyUnicode_KIND(x);
13003 y_kind = PyUnicode_KIND(y);
13004 x_data = PyUnicode_DATA(x);
13005 y_data = PyUnicode_DATA(y);
13006 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13007 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013008 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013009 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013010 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013011 if (!value) {
13012 Py_DECREF(key);
13013 goto err;
13014 }
Georg Brandlceee0772007-11-27 23:48:05 +000013015 res = PyDict_SetItem(new, key, value);
13016 Py_DECREF(key);
13017 Py_DECREF(value);
13018 if (res < 0)
13019 goto err;
13020 }
13021 /* create entries for deleting chars in z */
13022 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 z_kind = PyUnicode_KIND(z);
13024 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013025 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013027 if (!key)
13028 goto err;
13029 res = PyDict_SetItem(new, key, Py_None);
13030 Py_DECREF(key);
13031 if (res < 0)
13032 goto err;
13033 }
13034 }
13035 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 int kind;
13037 void *data;
13038
Georg Brandlceee0772007-11-27 23:48:05 +000013039 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013040 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013041 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13042 "to maketrans it must be a dict");
13043 goto err;
13044 }
13045 /* copy entries into the new dict, converting string keys to int keys */
13046 while (PyDict_Next(x, &i, &key, &value)) {
13047 if (PyUnicode_Check(key)) {
13048 /* convert string keys to integer keys */
13049 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013050 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013051 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13052 "table must be of length 1");
13053 goto err;
13054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013055 kind = PyUnicode_KIND(key);
13056 data = PyUnicode_DATA(key);
13057 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013058 if (!newkey)
13059 goto err;
13060 res = PyDict_SetItem(new, newkey, value);
13061 Py_DECREF(newkey);
13062 if (res < 0)
13063 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013064 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013065 /* just keep integer keys */
13066 if (PyDict_SetItem(new, key, value) < 0)
13067 goto err;
13068 } else {
13069 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13070 "be strings or integers");
13071 goto err;
13072 }
13073 }
13074 }
13075 return new;
13076 err:
13077 Py_DECREF(new);
13078 return NULL;
13079}
13080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013081PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013082 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013084Return a copy of the string S in which each character has been mapped\n\
13085through the given translation table. The table must implement\n\
13086lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13087mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13088this operation raises LookupError, the character is left untouched.\n\
13089Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090
13091static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013094 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095}
13096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013097PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013098 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013100Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101
13102static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013103unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013105 if (PyUnicode_READY(self) == -1)
13106 return NULL;
13107 if (PyUnicode_IS_ASCII(self))
13108 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013109 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110}
13111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013112PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013113 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013115Pad a numeric string S with zeros on the left, to fill a field\n\
13116of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117
13118static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013119unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013121 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013122 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013123 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 int kind;
13125 void *data;
13126 Py_UCS4 chr;
13127
Martin v. Löwis18e16552006-02-15 17:27:45 +000013128 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129 return NULL;
13130
Benjamin Petersonbac79492012-01-14 13:34:47 -050013131 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013132 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133
Victor Stinnerc4b49542011-12-11 22:44:26 +010013134 if (PyUnicode_GET_LENGTH(self) >= width)
13135 return unicode_result_unchanged(self);
13136
13137 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138
13139 u = pad(self, fill, 0, '0');
13140
Walter Dörwald068325e2002-04-15 13:36:47 +000013141 if (u == NULL)
13142 return NULL;
13143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 kind = PyUnicode_KIND(u);
13145 data = PyUnicode_DATA(u);
13146 chr = PyUnicode_READ(kind, data, fill);
13147
13148 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013150 PyUnicode_WRITE(kind, data, 0, chr);
13151 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152 }
13153
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013154 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013155 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157
13158#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013159static PyObject *
13160unicode__decimal2ascii(PyObject *self)
13161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013162 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013163}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164#endif
13165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013166PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013169Return True if S starts with the specified prefix, False otherwise.\n\
13170With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013171With optional end, stop comparing S at that position.\n\
13172prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173
13174static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013175unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013178 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013179 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013180 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013181 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013182 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
Jesus Ceaac451502011-04-20 17:09:23 +020013184 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013186 if (PyTuple_Check(subobj)) {
13187 Py_ssize_t i;
13188 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013189 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013190 if (substring == NULL)
13191 return NULL;
13192 result = tailmatch(self, substring, start, end, -1);
13193 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013194 if (result == -1)
13195 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013196 if (result) {
13197 Py_RETURN_TRUE;
13198 }
13199 }
13200 /* nothing matched */
13201 Py_RETURN_FALSE;
13202 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013203 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013204 if (substring == NULL) {
13205 if (PyErr_ExceptionMatches(PyExc_TypeError))
13206 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13207 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013209 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013210 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013212 if (result == -1)
13213 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013214 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215}
13216
13217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013218PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013221Return True if S ends with the specified suffix, False otherwise.\n\
13222With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223With optional end, stop comparing S at that position.\n\
13224suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225
13226static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013227unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013228 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013229{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013230 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013231 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013232 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013233 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013234 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235
Jesus Ceaac451502011-04-20 17:09:23 +020013236 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013238 if (PyTuple_Check(subobj)) {
13239 Py_ssize_t i;
13240 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013241 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013242 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013243 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013245 result = tailmatch(self, substring, start, end, +1);
13246 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013247 if (result == -1)
13248 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013249 if (result) {
13250 Py_RETURN_TRUE;
13251 }
13252 }
13253 Py_RETURN_FALSE;
13254 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013255 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013256 if (substring == NULL) {
13257 if (PyErr_ExceptionMatches(PyExc_TypeError))
13258 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13259 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013260 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013261 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013262 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013263 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013264 if (result == -1)
13265 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013266 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267}
13268
Victor Stinner202fdca2012-05-07 12:47:02 +020013269Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013270_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013271{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013272 if (!writer->readonly)
13273 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13274 else {
13275 /* Copy-on-write mode: set buffer size to 0 so
13276 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13277 * next write. */
13278 writer->size = 0;
13279 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013280 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13281 writer->data = PyUnicode_DATA(writer->buffer);
13282 writer->kind = PyUnicode_KIND(writer->buffer);
13283}
13284
Victor Stinnerd3f08822012-05-29 12:57:52 +020013285void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013286_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013287{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013288 memset(writer, 0, sizeof(*writer));
13289#ifdef Py_DEBUG
13290 writer->kind = 5; /* invalid kind */
13291#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013292 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013293}
13294
Victor Stinnerd3f08822012-05-29 12:57:52 +020013295int
13296_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13297 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013298{
Victor Stinner6989ba02013-11-18 21:08:39 +010013299#ifdef MS_WINDOWS
13300 /* On Windows, overallocate by 50% is the best factor */
13301# define OVERALLOCATE_FACTOR 2
13302#else
13303 /* On Linux, overallocate by 25% is the best factor */
13304# define OVERALLOCATE_FACTOR 4
13305#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013306 Py_ssize_t newlen;
13307 PyObject *newbuffer;
13308
Victor Stinnerca9381e2015-09-22 00:58:32 +020013309 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013310 assert((maxchar > writer->maxchar && length >= 0)
13311 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013312
Victor Stinner202fdca2012-05-07 12:47:02 +020013313 if (length > PY_SSIZE_T_MAX - writer->pos) {
13314 PyErr_NoMemory();
13315 return -1;
13316 }
13317 newlen = writer->pos + length;
13318
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013319 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013320
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013322 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013323 if (writer->overallocate
13324 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13325 /* overallocate to limit the number of realloc() */
13326 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013328 if (newlen < writer->min_length)
13329 newlen = writer->min_length;
13330
Victor Stinnerd3f08822012-05-29 12:57:52 +020013331 writer->buffer = PyUnicode_New(newlen, maxchar);
13332 if (writer->buffer == NULL)
13333 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013334 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013335 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013336 if (writer->overallocate
13337 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13338 /* overallocate to limit the number of realloc() */
13339 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013340 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013341 if (newlen < writer->min_length)
13342 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013343
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013344 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013345 /* resize + widen */
13346 newbuffer = PyUnicode_New(newlen, maxchar);
13347 if (newbuffer == NULL)
13348 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13350 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013351 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013352 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013353 }
13354 else {
13355 newbuffer = resize_compact(writer->buffer, newlen);
13356 if (newbuffer == NULL)
13357 return -1;
13358 }
13359 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013360 }
13361 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013362 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013363 newbuffer = PyUnicode_New(writer->size, maxchar);
13364 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013365 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013366 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13367 writer->buffer, 0, writer->pos);
13368 Py_DECREF(writer->buffer);
13369 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013370 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013371 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013372 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013373
13374#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013375}
13376
Victor Stinnerca9381e2015-09-22 00:58:32 +020013377int
13378_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13379 enum PyUnicode_Kind kind)
13380{
13381 Py_UCS4 maxchar;
13382
13383 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13384 assert(writer->kind < kind);
13385
13386 switch (kind)
13387 {
13388 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13389 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13390 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13391 default:
13392 assert(0 && "invalid kind");
13393 return -1;
13394 }
13395
13396 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13397}
13398
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013399Py_LOCAL_INLINE(int)
13400_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013401{
13402 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13403 return -1;
13404 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13405 writer->pos++;
13406 return 0;
13407}
13408
13409int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013410_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13411{
13412 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13413}
13414
13415int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013416_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13417{
13418 Py_UCS4 maxchar;
13419 Py_ssize_t len;
13420
13421 if (PyUnicode_READY(str) == -1)
13422 return -1;
13423 len = PyUnicode_GET_LENGTH(str);
13424 if (len == 0)
13425 return 0;
13426 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13427 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013428 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013429 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013430 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013431 Py_INCREF(str);
13432 writer->buffer = str;
13433 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013434 writer->pos += len;
13435 return 0;
13436 }
13437 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13438 return -1;
13439 }
13440 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13441 str, 0, len);
13442 writer->pos += len;
13443 return 0;
13444}
13445
Victor Stinnere215d962012-10-06 23:03:36 +020013446int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013447_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13448 Py_ssize_t start, Py_ssize_t end)
13449{
13450 Py_UCS4 maxchar;
13451 Py_ssize_t len;
13452
13453 if (PyUnicode_READY(str) == -1)
13454 return -1;
13455
13456 assert(0 <= start);
13457 assert(end <= PyUnicode_GET_LENGTH(str));
13458 assert(start <= end);
13459
13460 if (end == 0)
13461 return 0;
13462
13463 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13464 return _PyUnicodeWriter_WriteStr(writer, str);
13465
13466 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13467 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13468 else
13469 maxchar = writer->maxchar;
13470 len = end - start;
13471
13472 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13473 return -1;
13474
13475 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13476 str, start, len);
13477 writer->pos += len;
13478 return 0;
13479}
13480
13481int
Victor Stinner4a587072013-11-19 12:54:53 +010013482_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13483 const char *ascii, Py_ssize_t len)
13484{
13485 if (len == -1)
13486 len = strlen(ascii);
13487
13488 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13489
13490 if (writer->buffer == NULL && !writer->overallocate) {
13491 PyObject *str;
13492
13493 str = _PyUnicode_FromASCII(ascii, len);
13494 if (str == NULL)
13495 return -1;
13496
13497 writer->readonly = 1;
13498 writer->buffer = str;
13499 _PyUnicodeWriter_Update(writer);
13500 writer->pos += len;
13501 return 0;
13502 }
13503
13504 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13505 return -1;
13506
13507 switch (writer->kind)
13508 {
13509 case PyUnicode_1BYTE_KIND:
13510 {
13511 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13512 Py_UCS1 *data = writer->data;
13513
13514 Py_MEMCPY(data + writer->pos, str, len);
13515 break;
13516 }
13517 case PyUnicode_2BYTE_KIND:
13518 {
13519 _PyUnicode_CONVERT_BYTES(
13520 Py_UCS1, Py_UCS2,
13521 ascii, ascii + len,
13522 (Py_UCS2 *)writer->data + writer->pos);
13523 break;
13524 }
13525 case PyUnicode_4BYTE_KIND:
13526 {
13527 _PyUnicode_CONVERT_BYTES(
13528 Py_UCS1, Py_UCS4,
13529 ascii, ascii + len,
13530 (Py_UCS4 *)writer->data + writer->pos);
13531 break;
13532 }
13533 default:
13534 assert(0);
13535 }
13536
13537 writer->pos += len;
13538 return 0;
13539}
13540
13541int
13542_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13543 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013544{
13545 Py_UCS4 maxchar;
13546
13547 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13548 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13549 return -1;
13550 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13551 writer->pos += len;
13552 return 0;
13553}
13554
Victor Stinnerd3f08822012-05-29 12:57:52 +020013555PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013556_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013557{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013558 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013559 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013560 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013561 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013562 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013563 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013564 str = writer->buffer;
13565 writer->buffer = NULL;
13566 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13567 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013568 }
13569 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13570 PyObject *newbuffer;
13571 newbuffer = resize_compact(writer->buffer, writer->pos);
13572 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013573 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013574 return NULL;
13575 }
13576 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013577 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013578 str = writer->buffer;
13579 writer->buffer = NULL;
13580 assert(_PyUnicode_CheckConsistency(str, 1));
13581 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013582}
13583
Victor Stinnerd3f08822012-05-29 12:57:52 +020013584void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013585_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013586{
13587 Py_CLEAR(writer->buffer);
13588}
13589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013590#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013591
13592PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013594\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013595Return a formatted version of S, using substitutions from args and kwargs.\n\
13596The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013597
Eric Smith27bbca62010-11-04 17:06:58 +000013598PyDoc_STRVAR(format_map__doc__,
13599 "S.format_map(mapping) -> str\n\
13600\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013601Return a formatted version of S, using substitutions from mapping.\n\
13602The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013603
Eric Smith4a7d76d2008-05-30 18:10:19 +000013604static PyObject *
13605unicode__format__(PyObject* self, PyObject* args)
13606{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013607 PyObject *format_spec;
13608 _PyUnicodeWriter writer;
13609 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013610
13611 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13612 return NULL;
13613
Victor Stinnerd3f08822012-05-29 12:57:52 +020013614 if (PyUnicode_READY(self) == -1)
13615 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013616 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013617 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13618 self, format_spec, 0,
13619 PyUnicode_GET_LENGTH(format_spec));
13620 if (ret == -1) {
13621 _PyUnicodeWriter_Dealloc(&writer);
13622 return NULL;
13623 }
13624 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013625}
13626
Eric Smith8c663262007-08-25 02:26:07 +000013627PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013628 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013629\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013630Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013631
13632static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013633unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 Py_ssize_t size;
13636
13637 /* If it's a compact object, account for base structure +
13638 character data. */
13639 if (PyUnicode_IS_COMPACT_ASCII(v))
13640 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13641 else if (PyUnicode_IS_COMPACT(v))
13642 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013643 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013644 else {
13645 /* If it is a two-block object, account for base object, and
13646 for character block if present. */
13647 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013648 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013649 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013650 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013651 }
13652 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013653 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013654 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013655 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013656 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013657 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013658
13659 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013660}
13661
13662PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013664
13665static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013666unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013667{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013668 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013669 if (!copy)
13670 return NULL;
13671 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013672}
13673
Guido van Rossumd57fd912000-03-10 22:53:23 +000013674static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013675 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013676 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013677 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13678 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013679 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13680 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013681 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013682 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13683 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13684 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013685 {"expandtabs", (PyCFunction) unicode_expandtabs,
13686 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013687 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013688 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013689 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13690 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13691 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013692 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013693 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13694 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13695 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013696 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013697 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013698 {"splitlines", (PyCFunction) unicode_splitlines,
13699 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013700 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013701 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13702 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13703 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13704 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13705 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13706 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13707 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13708 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13709 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13710 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13711 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13712 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13713 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13714 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013715 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013716 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013717 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013718 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013719 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013720 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013721 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013722 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013723#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013724 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013725 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013726#endif
13727
Benjamin Peterson14339b62009-01-31 16:36:08 +000013728 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013729 {NULL, NULL}
13730};
13731
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013732static PyObject *
13733unicode_mod(PyObject *v, PyObject *w)
13734{
Brian Curtindfc80e32011-08-10 20:28:54 -050013735 if (!PyUnicode_Check(v))
13736 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013737 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013738}
13739
13740static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013741 0, /*nb_add*/
13742 0, /*nb_subtract*/
13743 0, /*nb_multiply*/
13744 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013745};
13746
Guido van Rossumd57fd912000-03-10 22:53:23 +000013747static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013748 (lenfunc) unicode_length, /* sq_length */
13749 PyUnicode_Concat, /* sq_concat */
13750 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13751 (ssizeargfunc) unicode_getitem, /* sq_item */
13752 0, /* sq_slice */
13753 0, /* sq_ass_item */
13754 0, /* sq_ass_slice */
13755 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013756};
13757
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013758static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013759unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013761 if (PyUnicode_READY(self) == -1)
13762 return NULL;
13763
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013764 if (PyIndex_Check(item)) {
13765 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013766 if (i == -1 && PyErr_Occurred())
13767 return NULL;
13768 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013769 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013770 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013771 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013772 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013773 PyObject *result;
13774 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013775 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013776 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013778 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013779 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013780 return NULL;
13781 }
13782
13783 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013784 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013785 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013786 slicelength == PyUnicode_GET_LENGTH(self)) {
13787 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013788 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013789 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013790 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013791 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013792 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013793 src_kind = PyUnicode_KIND(self);
13794 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013795 if (!PyUnicode_IS_ASCII(self)) {
13796 kind_limit = kind_maxchar_limit(src_kind);
13797 max_char = 0;
13798 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13799 ch = PyUnicode_READ(src_kind, src_data, cur);
13800 if (ch > max_char) {
13801 max_char = ch;
13802 if (max_char >= kind_limit)
13803 break;
13804 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013805 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013806 }
Victor Stinner55c99112011-10-13 01:17:06 +020013807 else
13808 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013809 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013810 if (result == NULL)
13811 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013812 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013813 dest_data = PyUnicode_DATA(result);
13814
13815 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013816 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13817 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013818 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013819 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013820 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013821 } else {
13822 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13823 return NULL;
13824 }
13825}
13826
13827static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013828 (lenfunc)unicode_length, /* mp_length */
13829 (binaryfunc)unicode_subscript, /* mp_subscript */
13830 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013831};
13832
Guido van Rossumd57fd912000-03-10 22:53:23 +000013833
Guido van Rossumd57fd912000-03-10 22:53:23 +000013834/* Helpers for PyUnicode_Format() */
13835
Victor Stinnera47082312012-10-04 02:19:54 +020013836struct unicode_formatter_t {
13837 PyObject *args;
13838 int args_owned;
13839 Py_ssize_t arglen, argidx;
13840 PyObject *dict;
13841
13842 enum PyUnicode_Kind fmtkind;
13843 Py_ssize_t fmtcnt, fmtpos;
13844 void *fmtdata;
13845 PyObject *fmtstr;
13846
13847 _PyUnicodeWriter writer;
13848};
13849
13850struct unicode_format_arg_t {
13851 Py_UCS4 ch;
13852 int flags;
13853 Py_ssize_t width;
13854 int prec;
13855 int sign;
13856};
13857
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013859unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013860{
Victor Stinnera47082312012-10-04 02:19:54 +020013861 Py_ssize_t argidx = ctx->argidx;
13862
13863 if (argidx < ctx->arglen) {
13864 ctx->argidx++;
13865 if (ctx->arglen < 0)
13866 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 else
Victor Stinnera47082312012-10-04 02:19:54 +020013868 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013869 }
13870 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013871 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013872 return NULL;
13873}
13874
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013875/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013876
Victor Stinnera47082312012-10-04 02:19:54 +020013877/* Format a float into the writer if the writer is not NULL, or into *p_output
13878 otherwise.
13879
13880 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013881static int
Victor Stinnera47082312012-10-04 02:19:54 +020013882formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13883 PyObject **p_output,
13884 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013885{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013886 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013887 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013888 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013889 int prec;
13890 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013891
Guido van Rossumd57fd912000-03-10 22:53:23 +000013892 x = PyFloat_AsDouble(v);
13893 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013894 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013895
Victor Stinnera47082312012-10-04 02:19:54 +020013896 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013897 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013899
Victor Stinnera47082312012-10-04 02:19:54 +020013900 if (arg->flags & F_ALT)
13901 dtoa_flags = Py_DTSF_ALT;
13902 else
13903 dtoa_flags = 0;
13904 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013905 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013906 return -1;
13907 len = strlen(p);
13908 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013909 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013910 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013911 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013912 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013913 }
13914 else
13915 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013916 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013917 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013918}
13919
Victor Stinnerd0880d52012-04-27 23:40:13 +020013920/* formatlong() emulates the format codes d, u, o, x and X, and
13921 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13922 * Python's regular ints.
13923 * Return value: a new PyUnicodeObject*, or NULL if error.
13924 * The output string is of the form
13925 * "-"? ("0x" | "0X")? digit+
13926 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13927 * set in flags. The case of hex digits will be correct,
13928 * There will be at least prec digits, zero-filled on the left if
13929 * necessary to get that many.
13930 * val object to be converted
13931 * flags bitmask of format flags; only F_ALT is looked at
13932 * prec minimum number of digits; 0-fill on left if needed
13933 * type a character in [duoxX]; u acts the same as d
13934 *
13935 * CAUTION: o, x and X conversions on regular ints can never
13936 * produce a '-' sign, but can for Python's unbounded ints.
13937 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013938PyObject *
13939_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013940{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013941 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013943 Py_ssize_t i;
13944 int sign; /* 1 if '-', else 0 */
13945 int len; /* number of characters */
13946 Py_ssize_t llen;
13947 int numdigits; /* len == numnondigits + numdigits */
13948 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013949
Victor Stinnerd0880d52012-04-27 23:40:13 +020013950 /* Avoid exceeding SSIZE_T_MAX */
13951 if (prec > INT_MAX-3) {
13952 PyErr_SetString(PyExc_OverflowError,
13953 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013954 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013955 }
13956
13957 assert(PyLong_Check(val));
13958
13959 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013960 default:
13961 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013962 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013963 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013964 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013965 /* int and int subclasses should print numerically when a numeric */
13966 /* format code is used (see issue18780) */
13967 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013968 break;
13969 case 'o':
13970 numnondigits = 2;
13971 result = PyNumber_ToBase(val, 8);
13972 break;
13973 case 'x':
13974 case 'X':
13975 numnondigits = 2;
13976 result = PyNumber_ToBase(val, 16);
13977 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013978 }
13979 if (!result)
13980 return NULL;
13981
13982 assert(unicode_modifiable(result));
13983 assert(PyUnicode_IS_READY(result));
13984 assert(PyUnicode_IS_ASCII(result));
13985
13986 /* To modify the string in-place, there can only be one reference. */
13987 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013988 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013989 PyErr_BadInternalCall();
13990 return NULL;
13991 }
13992 buf = PyUnicode_DATA(result);
13993 llen = PyUnicode_GET_LENGTH(result);
13994 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013995 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013996 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013997 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013998 return NULL;
13999 }
14000 len = (int)llen;
14001 sign = buf[0] == '-';
14002 numnondigits += sign;
14003 numdigits = len - numnondigits;
14004 assert(numdigits > 0);
14005
14006 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014007 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014008 (type == 'o' || type == 'x' || type == 'X'))) {
14009 assert(buf[sign] == '0');
14010 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14011 buf[sign+1] == 'o');
14012 numnondigits -= 2;
14013 buf += 2;
14014 len -= 2;
14015 if (sign)
14016 buf[0] = '-';
14017 assert(len == numnondigits + numdigits);
14018 assert(numdigits > 0);
14019 }
14020
14021 /* Fill with leading zeroes to meet minimum width. */
14022 if (prec > numdigits) {
14023 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14024 numnondigits + prec);
14025 char *b1;
14026 if (!r1) {
14027 Py_DECREF(result);
14028 return NULL;
14029 }
14030 b1 = PyBytes_AS_STRING(r1);
14031 for (i = 0; i < numnondigits; ++i)
14032 *b1++ = *buf++;
14033 for (i = 0; i < prec - numdigits; i++)
14034 *b1++ = '0';
14035 for (i = 0; i < numdigits; i++)
14036 *b1++ = *buf++;
14037 *b1 = '\0';
14038 Py_DECREF(result);
14039 result = r1;
14040 buf = PyBytes_AS_STRING(result);
14041 len = numnondigits + prec;
14042 }
14043
14044 /* Fix up case for hex conversions. */
14045 if (type == 'X') {
14046 /* Need to convert all lower case letters to upper case.
14047 and need to convert 0x to 0X (and -0x to -0X). */
14048 for (i = 0; i < len; i++)
14049 if (buf[i] >= 'a' && buf[i] <= 'x')
14050 buf[i] -= 'a'-'A';
14051 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014052 if (!PyUnicode_Check(result)
14053 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014054 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014055 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014056 Py_DECREF(result);
14057 result = unicode;
14058 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014059 else if (len != PyUnicode_GET_LENGTH(result)) {
14060 if (PyUnicode_Resize(&result, len) < 0)
14061 Py_CLEAR(result);
14062 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014064}
14065
Ethan Furmandf3ed242014-01-05 06:50:30 -080014066/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014067 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014068 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014069 * -1 and raise an exception on error */
14070static int
Victor Stinnera47082312012-10-04 02:19:54 +020014071mainformatlong(PyObject *v,
14072 struct unicode_format_arg_t *arg,
14073 PyObject **p_output,
14074 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014075{
14076 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014077 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014078
14079 if (!PyNumber_Check(v))
14080 goto wrongtype;
14081
Ethan Furman9ab74802014-03-21 06:38:46 -070014082 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014083 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014084 if (type == 'o' || type == 'x' || type == 'X') {
14085 iobj = PyNumber_Index(v);
14086 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014087 if (PyErr_ExceptionMatches(PyExc_TypeError))
14088 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014089 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014090 }
14091 }
14092 else {
14093 iobj = PyNumber_Long(v);
14094 if (iobj == NULL ) {
14095 if (PyErr_ExceptionMatches(PyExc_TypeError))
14096 goto wrongtype;
14097 return -1;
14098 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014099 }
14100 assert(PyLong_Check(iobj));
14101 }
14102 else {
14103 iobj = v;
14104 Py_INCREF(iobj);
14105 }
14106
14107 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014108 && arg->width == -1 && arg->prec == -1
14109 && !(arg->flags & (F_SIGN | F_BLANK))
14110 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014111 {
14112 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014113 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014114 int base;
14115
Victor Stinnera47082312012-10-04 02:19:54 +020014116 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014117 {
14118 default:
14119 assert(0 && "'type' not in [diuoxX]");
14120 case 'd':
14121 case 'i':
14122 case 'u':
14123 base = 10;
14124 break;
14125 case 'o':
14126 base = 8;
14127 break;
14128 case 'x':
14129 case 'X':
14130 base = 16;
14131 break;
14132 }
14133
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014134 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14135 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014136 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014137 }
14138 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014139 return 1;
14140 }
14141
Ethan Furmanb95b5612015-01-23 20:05:18 -080014142 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014143 Py_DECREF(iobj);
14144 if (res == NULL)
14145 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014146 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014147 return 0;
14148
14149wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014150 switch(type)
14151 {
14152 case 'o':
14153 case 'x':
14154 case 'X':
14155 PyErr_Format(PyExc_TypeError,
14156 "%%%c format: an integer is required, "
14157 "not %.200s",
14158 type, Py_TYPE(v)->tp_name);
14159 break;
14160 default:
14161 PyErr_Format(PyExc_TypeError,
14162 "%%%c format: a number is required, "
14163 "not %.200s",
14164 type, Py_TYPE(v)->tp_name);
14165 break;
14166 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014167 return -1;
14168}
14169
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014170static Py_UCS4
14171formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014172{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014173 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014174 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014175 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014176 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014177 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014178 goto onError;
14179 }
14180 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014181 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014182 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014183 /* make sure number is a type of integer */
14184 if (!PyLong_Check(v)) {
14185 iobj = PyNumber_Index(v);
14186 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014187 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014188 }
14189 v = iobj;
14190 Py_DECREF(iobj);
14191 }
14192 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014193 x = PyLong_AsLong(v);
14194 if (x == -1 && PyErr_Occurred())
14195 goto onError;
14196
Victor Stinner8faf8212011-12-08 22:14:11 +010014197 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014198 PyErr_SetString(PyExc_OverflowError,
14199 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014200 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014201 }
14202
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014203 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014204 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014205
Benjamin Peterson29060642009-01-31 22:14:21 +000014206 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014207 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014208 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014209 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014210}
14211
Victor Stinnera47082312012-10-04 02:19:54 +020014212/* Parse options of an argument: flags, width, precision.
14213 Handle also "%(name)" syntax.
14214
14215 Return 0 if the argument has been formatted into arg->str.
14216 Return 1 if the argument has been written into ctx->writer,
14217 Raise an exception and return -1 on error. */
14218static int
14219unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14220 struct unicode_format_arg_t *arg)
14221{
14222#define FORMAT_READ(ctx) \
14223 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14224
14225 PyObject *v;
14226
Victor Stinnera47082312012-10-04 02:19:54 +020014227 if (arg->ch == '(') {
14228 /* Get argument value from a dictionary. Example: "%(name)s". */
14229 Py_ssize_t keystart;
14230 Py_ssize_t keylen;
14231 PyObject *key;
14232 int pcount = 1;
14233
14234 if (ctx->dict == NULL) {
14235 PyErr_SetString(PyExc_TypeError,
14236 "format requires a mapping");
14237 return -1;
14238 }
14239 ++ctx->fmtpos;
14240 --ctx->fmtcnt;
14241 keystart = ctx->fmtpos;
14242 /* Skip over balanced parentheses */
14243 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14244 arg->ch = FORMAT_READ(ctx);
14245 if (arg->ch == ')')
14246 --pcount;
14247 else if (arg->ch == '(')
14248 ++pcount;
14249 ctx->fmtpos++;
14250 }
14251 keylen = ctx->fmtpos - keystart - 1;
14252 if (ctx->fmtcnt < 0 || pcount > 0) {
14253 PyErr_SetString(PyExc_ValueError,
14254 "incomplete format key");
14255 return -1;
14256 }
14257 key = PyUnicode_Substring(ctx->fmtstr,
14258 keystart, keystart + keylen);
14259 if (key == NULL)
14260 return -1;
14261 if (ctx->args_owned) {
14262 Py_DECREF(ctx->args);
14263 ctx->args_owned = 0;
14264 }
14265 ctx->args = PyObject_GetItem(ctx->dict, key);
14266 Py_DECREF(key);
14267 if (ctx->args == NULL)
14268 return -1;
14269 ctx->args_owned = 1;
14270 ctx->arglen = -1;
14271 ctx->argidx = -2;
14272 }
14273
14274 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014275 while (--ctx->fmtcnt >= 0) {
14276 arg->ch = FORMAT_READ(ctx);
14277 ctx->fmtpos++;
14278 switch (arg->ch) {
14279 case '-': arg->flags |= F_LJUST; continue;
14280 case '+': arg->flags |= F_SIGN; continue;
14281 case ' ': arg->flags |= F_BLANK; continue;
14282 case '#': arg->flags |= F_ALT; continue;
14283 case '0': arg->flags |= F_ZERO; continue;
14284 }
14285 break;
14286 }
14287
14288 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014289 if (arg->ch == '*') {
14290 v = unicode_format_getnextarg(ctx);
14291 if (v == NULL)
14292 return -1;
14293 if (!PyLong_Check(v)) {
14294 PyErr_SetString(PyExc_TypeError,
14295 "* wants int");
14296 return -1;
14297 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014298 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014299 if (arg->width == -1 && PyErr_Occurred())
14300 return -1;
14301 if (arg->width < 0) {
14302 arg->flags |= F_LJUST;
14303 arg->width = -arg->width;
14304 }
14305 if (--ctx->fmtcnt >= 0) {
14306 arg->ch = FORMAT_READ(ctx);
14307 ctx->fmtpos++;
14308 }
14309 }
14310 else if (arg->ch >= '0' && arg->ch <= '9') {
14311 arg->width = arg->ch - '0';
14312 while (--ctx->fmtcnt >= 0) {
14313 arg->ch = FORMAT_READ(ctx);
14314 ctx->fmtpos++;
14315 if (arg->ch < '0' || arg->ch > '9')
14316 break;
14317 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14318 mixing signed and unsigned comparison. Since arg->ch is between
14319 '0' and '9', casting to int is safe. */
14320 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14321 PyErr_SetString(PyExc_ValueError,
14322 "width too big");
14323 return -1;
14324 }
14325 arg->width = arg->width*10 + (arg->ch - '0');
14326 }
14327 }
14328
14329 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014330 if (arg->ch == '.') {
14331 arg->prec = 0;
14332 if (--ctx->fmtcnt >= 0) {
14333 arg->ch = FORMAT_READ(ctx);
14334 ctx->fmtpos++;
14335 }
14336 if (arg->ch == '*') {
14337 v = unicode_format_getnextarg(ctx);
14338 if (v == NULL)
14339 return -1;
14340 if (!PyLong_Check(v)) {
14341 PyErr_SetString(PyExc_TypeError,
14342 "* wants int");
14343 return -1;
14344 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014345 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014346 if (arg->prec == -1 && PyErr_Occurred())
14347 return -1;
14348 if (arg->prec < 0)
14349 arg->prec = 0;
14350 if (--ctx->fmtcnt >= 0) {
14351 arg->ch = FORMAT_READ(ctx);
14352 ctx->fmtpos++;
14353 }
14354 }
14355 else if (arg->ch >= '0' && arg->ch <= '9') {
14356 arg->prec = arg->ch - '0';
14357 while (--ctx->fmtcnt >= 0) {
14358 arg->ch = FORMAT_READ(ctx);
14359 ctx->fmtpos++;
14360 if (arg->ch < '0' || arg->ch > '9')
14361 break;
14362 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14363 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014364 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014365 return -1;
14366 }
14367 arg->prec = arg->prec*10 + (arg->ch - '0');
14368 }
14369 }
14370 }
14371
14372 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14373 if (ctx->fmtcnt >= 0) {
14374 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14375 if (--ctx->fmtcnt >= 0) {
14376 arg->ch = FORMAT_READ(ctx);
14377 ctx->fmtpos++;
14378 }
14379 }
14380 }
14381 if (ctx->fmtcnt < 0) {
14382 PyErr_SetString(PyExc_ValueError,
14383 "incomplete format");
14384 return -1;
14385 }
14386 return 0;
14387
14388#undef FORMAT_READ
14389}
14390
14391/* Format one argument. Supported conversion specifiers:
14392
14393 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014394 - "i", "d", "u": int or float
14395 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014396 - "e", "E", "f", "F", "g", "G": float
14397 - "c": int or str (1 character)
14398
Victor Stinner8dbd4212012-12-04 09:30:24 +010014399 When possible, the output is written directly into the Unicode writer
14400 (ctx->writer). A string is created when padding is required.
14401
Victor Stinnera47082312012-10-04 02:19:54 +020014402 Return 0 if the argument has been formatted into *p_str,
14403 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014404 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014405static int
14406unicode_format_arg_format(struct unicode_formatter_t *ctx,
14407 struct unicode_format_arg_t *arg,
14408 PyObject **p_str)
14409{
14410 PyObject *v;
14411 _PyUnicodeWriter *writer = &ctx->writer;
14412
14413 if (ctx->fmtcnt == 0)
14414 ctx->writer.overallocate = 0;
14415
14416 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014417 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014418 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014419 return 1;
14420 }
14421
14422 v = unicode_format_getnextarg(ctx);
14423 if (v == NULL)
14424 return -1;
14425
Victor Stinnera47082312012-10-04 02:19:54 +020014426
14427 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014428 case 's':
14429 case 'r':
14430 case 'a':
14431 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14432 /* Fast path */
14433 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14434 return -1;
14435 return 1;
14436 }
14437
14438 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14439 *p_str = v;
14440 Py_INCREF(*p_str);
14441 }
14442 else {
14443 if (arg->ch == 's')
14444 *p_str = PyObject_Str(v);
14445 else if (arg->ch == 'r')
14446 *p_str = PyObject_Repr(v);
14447 else
14448 *p_str = PyObject_ASCII(v);
14449 }
14450 break;
14451
14452 case 'i':
14453 case 'd':
14454 case 'u':
14455 case 'o':
14456 case 'x':
14457 case 'X':
14458 {
14459 int ret = mainformatlong(v, arg, p_str, writer);
14460 if (ret != 0)
14461 return ret;
14462 arg->sign = 1;
14463 break;
14464 }
14465
14466 case 'e':
14467 case 'E':
14468 case 'f':
14469 case 'F':
14470 case 'g':
14471 case 'G':
14472 if (arg->width == -1 && arg->prec == -1
14473 && !(arg->flags & (F_SIGN | F_BLANK)))
14474 {
14475 /* Fast path */
14476 if (formatfloat(v, arg, NULL, writer) == -1)
14477 return -1;
14478 return 1;
14479 }
14480
14481 arg->sign = 1;
14482 if (formatfloat(v, arg, p_str, NULL) == -1)
14483 return -1;
14484 break;
14485
14486 case 'c':
14487 {
14488 Py_UCS4 ch = formatchar(v);
14489 if (ch == (Py_UCS4) -1)
14490 return -1;
14491 if (arg->width == -1 && arg->prec == -1) {
14492 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014493 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014494 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014495 return 1;
14496 }
14497 *p_str = PyUnicode_FromOrdinal(ch);
14498 break;
14499 }
14500
14501 default:
14502 PyErr_Format(PyExc_ValueError,
14503 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014504 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014505 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14506 (int)arg->ch,
14507 ctx->fmtpos - 1);
14508 return -1;
14509 }
14510 if (*p_str == NULL)
14511 return -1;
14512 assert (PyUnicode_Check(*p_str));
14513 return 0;
14514}
14515
14516static int
14517unicode_format_arg_output(struct unicode_formatter_t *ctx,
14518 struct unicode_format_arg_t *arg,
14519 PyObject *str)
14520{
14521 Py_ssize_t len;
14522 enum PyUnicode_Kind kind;
14523 void *pbuf;
14524 Py_ssize_t pindex;
14525 Py_UCS4 signchar;
14526 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014527 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014528 Py_ssize_t sublen;
14529 _PyUnicodeWriter *writer = &ctx->writer;
14530 Py_UCS4 fill;
14531
14532 fill = ' ';
14533 if (arg->sign && arg->flags & F_ZERO)
14534 fill = '0';
14535
14536 if (PyUnicode_READY(str) == -1)
14537 return -1;
14538
14539 len = PyUnicode_GET_LENGTH(str);
14540 if ((arg->width == -1 || arg->width <= len)
14541 && (arg->prec == -1 || arg->prec >= len)
14542 && !(arg->flags & (F_SIGN | F_BLANK)))
14543 {
14544 /* Fast path */
14545 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14546 return -1;
14547 return 0;
14548 }
14549
14550 /* Truncate the string for "s", "r" and "a" formats
14551 if the precision is set */
14552 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14553 if (arg->prec >= 0 && len > arg->prec)
14554 len = arg->prec;
14555 }
14556
14557 /* Adjust sign and width */
14558 kind = PyUnicode_KIND(str);
14559 pbuf = PyUnicode_DATA(str);
14560 pindex = 0;
14561 signchar = '\0';
14562 if (arg->sign) {
14563 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14564 if (ch == '-' || ch == '+') {
14565 signchar = ch;
14566 len--;
14567 pindex++;
14568 }
14569 else if (arg->flags & F_SIGN)
14570 signchar = '+';
14571 else if (arg->flags & F_BLANK)
14572 signchar = ' ';
14573 else
14574 arg->sign = 0;
14575 }
14576 if (arg->width < len)
14577 arg->width = len;
14578
14579 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014580 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014581 if (!(arg->flags & F_LJUST)) {
14582 if (arg->sign) {
14583 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014584 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014585 }
14586 else {
14587 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014588 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014589 }
14590 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014591 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14592 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014593 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014594 }
14595
Victor Stinnera47082312012-10-04 02:19:54 +020014596 buflen = arg->width;
14597 if (arg->sign && len == arg->width)
14598 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014599 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014600 return -1;
14601
14602 /* Write the sign if needed */
14603 if (arg->sign) {
14604 if (fill != ' ') {
14605 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14606 writer->pos += 1;
14607 }
14608 if (arg->width > len)
14609 arg->width--;
14610 }
14611
14612 /* Write the numeric prefix for "x", "X" and "o" formats
14613 if the alternate form is used.
14614 For example, write "0x" for the "%#x" format. */
14615 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14616 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14617 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14618 if (fill != ' ') {
14619 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14620 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14621 writer->pos += 2;
14622 pindex += 2;
14623 }
14624 arg->width -= 2;
14625 if (arg->width < 0)
14626 arg->width = 0;
14627 len -= 2;
14628 }
14629
14630 /* Pad left with the fill character if needed */
14631 if (arg->width > len && !(arg->flags & F_LJUST)) {
14632 sublen = arg->width - len;
14633 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14634 writer->pos += sublen;
14635 arg->width = len;
14636 }
14637
14638 /* If padding with spaces: write sign if needed and/or numeric prefix if
14639 the alternate form is used */
14640 if (fill == ' ') {
14641 if (arg->sign) {
14642 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14643 writer->pos += 1;
14644 }
14645 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14646 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14647 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14648 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14649 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14650 writer->pos += 2;
14651 pindex += 2;
14652 }
14653 }
14654
14655 /* Write characters */
14656 if (len) {
14657 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14658 str, pindex, len);
14659 writer->pos += len;
14660 }
14661
14662 /* Pad right with the fill character if needed */
14663 if (arg->width > len) {
14664 sublen = arg->width - len;
14665 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14666 writer->pos += sublen;
14667 }
14668 return 0;
14669}
14670
14671/* Helper of PyUnicode_Format(): format one arg.
14672 Return 0 on success, raise an exception and return -1 on error. */
14673static int
14674unicode_format_arg(struct unicode_formatter_t *ctx)
14675{
14676 struct unicode_format_arg_t arg;
14677 PyObject *str;
14678 int ret;
14679
Victor Stinner8dbd4212012-12-04 09:30:24 +010014680 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14681 arg.flags = 0;
14682 arg.width = -1;
14683 arg.prec = -1;
14684 arg.sign = 0;
14685 str = NULL;
14686
Victor Stinnera47082312012-10-04 02:19:54 +020014687 ret = unicode_format_arg_parse(ctx, &arg);
14688 if (ret == -1)
14689 return -1;
14690
14691 ret = unicode_format_arg_format(ctx, &arg, &str);
14692 if (ret == -1)
14693 return -1;
14694
14695 if (ret != 1) {
14696 ret = unicode_format_arg_output(ctx, &arg, str);
14697 Py_DECREF(str);
14698 if (ret == -1)
14699 return -1;
14700 }
14701
14702 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14703 PyErr_SetString(PyExc_TypeError,
14704 "not all arguments converted during string formatting");
14705 return -1;
14706 }
14707 return 0;
14708}
14709
Alexander Belopolsky40018472011-02-26 01:02:56 +000014710PyObject *
14711PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014712{
Victor Stinnera47082312012-10-04 02:19:54 +020014713 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014714
Guido van Rossumd57fd912000-03-10 22:53:23 +000014715 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014716 PyErr_BadInternalCall();
14717 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014718 }
Victor Stinnera47082312012-10-04 02:19:54 +020014719
14720 ctx.fmtstr = PyUnicode_FromObject(format);
14721 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014722 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014723 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14724 Py_DECREF(ctx.fmtstr);
14725 return NULL;
14726 }
14727 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14728 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14729 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14730 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014731
Victor Stinner8f674cc2013-04-17 23:02:17 +020014732 _PyUnicodeWriter_Init(&ctx.writer);
14733 ctx.writer.min_length = ctx.fmtcnt + 100;
14734 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014735
Guido van Rossumd57fd912000-03-10 22:53:23 +000014736 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014737 ctx.arglen = PyTuple_Size(args);
14738 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014739 }
14740 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014741 ctx.arglen = -1;
14742 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014743 }
Victor Stinnera47082312012-10-04 02:19:54 +020014744 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014745 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014746 ctx.dict = args;
14747 else
14748 ctx.dict = NULL;
14749 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014750
Victor Stinnera47082312012-10-04 02:19:54 +020014751 while (--ctx.fmtcnt >= 0) {
14752 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014753 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014754
14755 nonfmtpos = ctx.fmtpos++;
14756 while (ctx.fmtcnt >= 0 &&
14757 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14758 ctx.fmtpos++;
14759 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014760 }
Victor Stinnera47082312012-10-04 02:19:54 +020014761 if (ctx.fmtcnt < 0) {
14762 ctx.fmtpos--;
14763 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014764 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014765
Victor Stinnercfc4c132013-04-03 01:48:39 +020014766 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14767 nonfmtpos, ctx.fmtpos) < 0)
14768 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014769 }
14770 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014771 ctx.fmtpos++;
14772 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014773 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014774 }
14775 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014776
Victor Stinnera47082312012-10-04 02:19:54 +020014777 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014778 PyErr_SetString(PyExc_TypeError,
14779 "not all arguments converted during string formatting");
14780 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014781 }
14782
Victor Stinnera47082312012-10-04 02:19:54 +020014783 if (ctx.args_owned) {
14784 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014785 }
Victor Stinnera47082312012-10-04 02:19:54 +020014786 Py_DECREF(ctx.fmtstr);
14787 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014788
Benjamin Peterson29060642009-01-31 22:14:21 +000014789 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014790 Py_DECREF(ctx.fmtstr);
14791 _PyUnicodeWriter_Dealloc(&ctx.writer);
14792 if (ctx.args_owned) {
14793 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014794 }
14795 return NULL;
14796}
14797
Jeremy Hylton938ace62002-07-17 16:30:39 +000014798static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014799unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14800
Tim Peters6d6c1a32001-08-02 04:15:00 +000014801static PyObject *
14802unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14803{
Benjamin Peterson29060642009-01-31 22:14:21 +000014804 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014805 static char *kwlist[] = {"object", "encoding", "errors", 0};
14806 char *encoding = NULL;
14807 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014808
Benjamin Peterson14339b62009-01-31 16:36:08 +000014809 if (type != &PyUnicode_Type)
14810 return unicode_subtype_new(type, args, kwds);
14811 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014812 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014813 return NULL;
14814 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014815 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014816 if (encoding == NULL && errors == NULL)
14817 return PyObject_Str(x);
14818 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014819 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014820}
14821
Guido van Rossume023fe02001-08-30 03:12:59 +000014822static PyObject *
14823unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14824{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014825 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014826 Py_ssize_t length, char_size;
14827 int share_wstr, share_utf8;
14828 unsigned int kind;
14829 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014830
Benjamin Peterson14339b62009-01-31 16:36:08 +000014831 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014832
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014833 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014834 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014835 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014836 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014837 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014838 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014839 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014840 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014841
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014842 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014843 if (self == NULL) {
14844 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014845 return NULL;
14846 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014847 kind = PyUnicode_KIND(unicode);
14848 length = PyUnicode_GET_LENGTH(unicode);
14849
14850 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014851#ifdef Py_DEBUG
14852 _PyUnicode_HASH(self) = -1;
14853#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014854 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014855#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014856 _PyUnicode_STATE(self).interned = 0;
14857 _PyUnicode_STATE(self).kind = kind;
14858 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014859 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014860 _PyUnicode_STATE(self).ready = 1;
14861 _PyUnicode_WSTR(self) = NULL;
14862 _PyUnicode_UTF8_LENGTH(self) = 0;
14863 _PyUnicode_UTF8(self) = NULL;
14864 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014865 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014866
14867 share_utf8 = 0;
14868 share_wstr = 0;
14869 if (kind == PyUnicode_1BYTE_KIND) {
14870 char_size = 1;
14871 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14872 share_utf8 = 1;
14873 }
14874 else if (kind == PyUnicode_2BYTE_KIND) {
14875 char_size = 2;
14876 if (sizeof(wchar_t) == 2)
14877 share_wstr = 1;
14878 }
14879 else {
14880 assert(kind == PyUnicode_4BYTE_KIND);
14881 char_size = 4;
14882 if (sizeof(wchar_t) == 4)
14883 share_wstr = 1;
14884 }
14885
14886 /* Ensure we won't overflow the length. */
14887 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14888 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014889 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014890 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014891 data = PyObject_MALLOC((length + 1) * char_size);
14892 if (data == NULL) {
14893 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014894 goto onError;
14895 }
14896
Victor Stinnerc3c74152011-10-02 20:39:55 +020014897 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014898 if (share_utf8) {
14899 _PyUnicode_UTF8_LENGTH(self) = length;
14900 _PyUnicode_UTF8(self) = data;
14901 }
14902 if (share_wstr) {
14903 _PyUnicode_WSTR_LENGTH(self) = length;
14904 _PyUnicode_WSTR(self) = (wchar_t *)data;
14905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014906
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014907 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014908 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014909 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014910#ifdef Py_DEBUG
14911 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14912#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014913 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014914 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014915
14916onError:
14917 Py_DECREF(unicode);
14918 Py_DECREF(self);
14919 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014920}
14921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014922PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014923"str(object='') -> str\n\
14924str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014925\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014926Create a new string object from the given object. If encoding or\n\
14927errors is specified, then the object must expose a data buffer\n\
14928that will be decoded using the given encoding and error handler.\n\
14929Otherwise, returns the result of object.__str__() (if defined)\n\
14930or repr(object).\n\
14931encoding defaults to sys.getdefaultencoding().\n\
14932errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014933
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014934static PyObject *unicode_iter(PyObject *seq);
14935
Guido van Rossumd57fd912000-03-10 22:53:23 +000014936PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014937 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014938 "str", /* tp_name */
14939 sizeof(PyUnicodeObject), /* tp_size */
14940 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014941 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014942 (destructor)unicode_dealloc, /* tp_dealloc */
14943 0, /* tp_print */
14944 0, /* tp_getattr */
14945 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014946 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014947 unicode_repr, /* tp_repr */
14948 &unicode_as_number, /* tp_as_number */
14949 &unicode_as_sequence, /* tp_as_sequence */
14950 &unicode_as_mapping, /* tp_as_mapping */
14951 (hashfunc) unicode_hash, /* tp_hash*/
14952 0, /* tp_call*/
14953 (reprfunc) unicode_str, /* tp_str */
14954 PyObject_GenericGetAttr, /* tp_getattro */
14955 0, /* tp_setattro */
14956 0, /* tp_as_buffer */
14957 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014958 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014959 unicode_doc, /* tp_doc */
14960 0, /* tp_traverse */
14961 0, /* tp_clear */
14962 PyUnicode_RichCompare, /* tp_richcompare */
14963 0, /* tp_weaklistoffset */
14964 unicode_iter, /* tp_iter */
14965 0, /* tp_iternext */
14966 unicode_methods, /* tp_methods */
14967 0, /* tp_members */
14968 0, /* tp_getset */
14969 &PyBaseObject_Type, /* tp_base */
14970 0, /* tp_dict */
14971 0, /* tp_descr_get */
14972 0, /* tp_descr_set */
14973 0, /* tp_dictoffset */
14974 0, /* tp_init */
14975 0, /* tp_alloc */
14976 unicode_new, /* tp_new */
14977 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014978};
14979
14980/* Initialize the Unicode implementation */
14981
Victor Stinner3a50e702011-10-18 21:21:00 +020014982int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014983{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014984 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014985 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014986 0x000A, /* LINE FEED */
14987 0x000D, /* CARRIAGE RETURN */
14988 0x001C, /* FILE SEPARATOR */
14989 0x001D, /* GROUP SEPARATOR */
14990 0x001E, /* RECORD SEPARATOR */
14991 0x0085, /* NEXT LINE */
14992 0x2028, /* LINE SEPARATOR */
14993 0x2029, /* PARAGRAPH SEPARATOR */
14994 };
14995
Fred Drakee4315f52000-05-09 19:53:39 +000014996 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014997 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014998 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014999 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015000 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015001
Guido van Rossumcacfc072002-05-24 19:01:59 +000015002 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015003 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015004
15005 /* initialize the linebreak bloom filter */
15006 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015007 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015008 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015009
Christian Heimes26532f72013-07-20 14:57:16 +020015010 if (PyType_Ready(&EncodingMapType) < 0)
15011 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015012
Benjamin Petersonc4311282012-10-30 23:21:10 -040015013 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15014 Py_FatalError("Can't initialize field name iterator type");
15015
15016 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15017 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015018
Victor Stinner3a50e702011-10-18 21:21:00 +020015019 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015020}
15021
15022/* Finalize the Unicode implementation */
15023
Christian Heimesa156e092008-02-16 07:38:31 +000015024int
15025PyUnicode_ClearFreeList(void)
15026{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015027 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015028}
15029
Guido van Rossumd57fd912000-03-10 22:53:23 +000015030void
Thomas Wouters78890102000-07-22 19:25:51 +000015031_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015032{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015033 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015034
Serhiy Storchaka05997252013-01-26 12:14:02 +020015035 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015036
Serhiy Storchaka05997252013-01-26 12:14:02 +020015037 for (i = 0; i < 256; i++)
15038 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015039 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015040 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015041}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015042
Walter Dörwald16807132007-05-25 13:52:07 +000015043void
15044PyUnicode_InternInPlace(PyObject **p)
15045{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015046 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015047 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015048#ifdef Py_DEBUG
15049 assert(s != NULL);
15050 assert(_PyUnicode_CHECK(s));
15051#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015052 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015053 return;
15054#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015055 /* If it's a subclass, we don't really know what putting
15056 it in the interned dict might do. */
15057 if (!PyUnicode_CheckExact(s))
15058 return;
15059 if (PyUnicode_CHECK_INTERNED(s))
15060 return;
15061 if (interned == NULL) {
15062 interned = PyDict_New();
15063 if (interned == NULL) {
15064 PyErr_Clear(); /* Don't leave an exception */
15065 return;
15066 }
15067 }
15068 /* It might be that the GetItem call fails even
15069 though the key is present in the dictionary,
15070 namely when this happens during a stack overflow. */
15071 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015072 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015073 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015074
Victor Stinnerf0335102013-04-14 19:13:03 +020015075 if (t) {
15076 Py_INCREF(t);
15077 Py_DECREF(*p);
15078 *p = t;
15079 return;
15080 }
Walter Dörwald16807132007-05-25 13:52:07 +000015081
Benjamin Peterson14339b62009-01-31 16:36:08 +000015082 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015083 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015084 PyErr_Clear();
15085 PyThreadState_GET()->recursion_critical = 0;
15086 return;
15087 }
15088 PyThreadState_GET()->recursion_critical = 0;
15089 /* The two references in interned are not counted by refcnt.
15090 The deallocator will take care of this */
15091 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015092 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015093}
15094
15095void
15096PyUnicode_InternImmortal(PyObject **p)
15097{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015098 PyUnicode_InternInPlace(p);
15099 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015100 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015101 Py_INCREF(*p);
15102 }
Walter Dörwald16807132007-05-25 13:52:07 +000015103}
15104
15105PyObject *
15106PyUnicode_InternFromString(const char *cp)
15107{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015108 PyObject *s = PyUnicode_FromString(cp);
15109 if (s == NULL)
15110 return NULL;
15111 PyUnicode_InternInPlace(&s);
15112 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015113}
15114
Alexander Belopolsky40018472011-02-26 01:02:56 +000015115void
15116_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015117{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015118 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015119 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015120 Py_ssize_t i, n;
15121 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015122
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 if (interned == NULL || !PyDict_Check(interned))
15124 return;
15125 keys = PyDict_Keys(interned);
15126 if (keys == NULL || !PyList_Check(keys)) {
15127 PyErr_Clear();
15128 return;
15129 }
Walter Dörwald16807132007-05-25 13:52:07 +000015130
Benjamin Peterson14339b62009-01-31 16:36:08 +000015131 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15132 detector, interned unicode strings are not forcibly deallocated;
15133 rather, we give them their stolen references back, and then clear
15134 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015135
Benjamin Peterson14339b62009-01-31 16:36:08 +000015136 n = PyList_GET_SIZE(keys);
15137 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015138 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015139 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015140 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015141 if (PyUnicode_READY(s) == -1) {
15142 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015143 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015145 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015146 case SSTATE_NOT_INTERNED:
15147 /* XXX Shouldn't happen */
15148 break;
15149 case SSTATE_INTERNED_IMMORTAL:
15150 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015151 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015152 break;
15153 case SSTATE_INTERNED_MORTAL:
15154 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015155 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015156 break;
15157 default:
15158 Py_FatalError("Inconsistent interned string state.");
15159 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015160 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 }
15162 fprintf(stderr, "total size of all interned strings: "
15163 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15164 "mortal/immortal\n", mortal_size, immortal_size);
15165 Py_DECREF(keys);
15166 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015167 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015168}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015169
15170
15171/********************* Unicode Iterator **************************/
15172
15173typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015174 PyObject_HEAD
15175 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015176 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015177} unicodeiterobject;
15178
15179static void
15180unicodeiter_dealloc(unicodeiterobject *it)
15181{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015182 _PyObject_GC_UNTRACK(it);
15183 Py_XDECREF(it->it_seq);
15184 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015185}
15186
15187static int
15188unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15189{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015190 Py_VISIT(it->it_seq);
15191 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015192}
15193
15194static PyObject *
15195unicodeiter_next(unicodeiterobject *it)
15196{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015197 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015198
Benjamin Peterson14339b62009-01-31 16:36:08 +000015199 assert(it != NULL);
15200 seq = it->it_seq;
15201 if (seq == NULL)
15202 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015203 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015205 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15206 int kind = PyUnicode_KIND(seq);
15207 void *data = PyUnicode_DATA(seq);
15208 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15209 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015210 if (item != NULL)
15211 ++it->it_index;
15212 return item;
15213 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015214
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 Py_DECREF(seq);
15216 it->it_seq = NULL;
15217 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015218}
15219
15220static PyObject *
15221unicodeiter_len(unicodeiterobject *it)
15222{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015223 Py_ssize_t len = 0;
15224 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015225 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015226 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015227}
15228
15229PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15230
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015231static PyObject *
15232unicodeiter_reduce(unicodeiterobject *it)
15233{
15234 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015235 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015236 it->it_seq, it->it_index);
15237 } else {
15238 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15239 if (u == NULL)
15240 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015241 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015242 }
15243}
15244
15245PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15246
15247static PyObject *
15248unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15249{
15250 Py_ssize_t index = PyLong_AsSsize_t(state);
15251 if (index == -1 && PyErr_Occurred())
15252 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015253 if (it->it_seq != NULL) {
15254 if (index < 0)
15255 index = 0;
15256 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15257 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15258 it->it_index = index;
15259 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015260 Py_RETURN_NONE;
15261}
15262
15263PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15264
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015265static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015266 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015267 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015268 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15269 reduce_doc},
15270 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15271 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015272 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015273};
15274
15275PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015276 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15277 "str_iterator", /* tp_name */
15278 sizeof(unicodeiterobject), /* tp_basicsize */
15279 0, /* tp_itemsize */
15280 /* methods */
15281 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15282 0, /* tp_print */
15283 0, /* tp_getattr */
15284 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015285 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 0, /* tp_repr */
15287 0, /* tp_as_number */
15288 0, /* tp_as_sequence */
15289 0, /* tp_as_mapping */
15290 0, /* tp_hash */
15291 0, /* tp_call */
15292 0, /* tp_str */
15293 PyObject_GenericGetAttr, /* tp_getattro */
15294 0, /* tp_setattro */
15295 0, /* tp_as_buffer */
15296 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15297 0, /* tp_doc */
15298 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15299 0, /* tp_clear */
15300 0, /* tp_richcompare */
15301 0, /* tp_weaklistoffset */
15302 PyObject_SelfIter, /* tp_iter */
15303 (iternextfunc)unicodeiter_next, /* tp_iternext */
15304 unicodeiter_methods, /* tp_methods */
15305 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015306};
15307
15308static PyObject *
15309unicode_iter(PyObject *seq)
15310{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015311 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015312
Benjamin Peterson14339b62009-01-31 16:36:08 +000015313 if (!PyUnicode_Check(seq)) {
15314 PyErr_BadInternalCall();
15315 return NULL;
15316 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015317 if (PyUnicode_READY(seq) == -1)
15318 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015319 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15320 if (it == NULL)
15321 return NULL;
15322 it->it_index = 0;
15323 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015324 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015325 _PyObject_GC_TRACK(it);
15326 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015327}
15328
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015329
15330size_t
15331Py_UNICODE_strlen(const Py_UNICODE *u)
15332{
15333 int res = 0;
15334 while(*u++)
15335 res++;
15336 return res;
15337}
15338
15339Py_UNICODE*
15340Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15341{
15342 Py_UNICODE *u = s1;
15343 while ((*u++ = *s2++));
15344 return s1;
15345}
15346
15347Py_UNICODE*
15348Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15349{
15350 Py_UNICODE *u = s1;
15351 while ((*u++ = *s2++))
15352 if (n-- == 0)
15353 break;
15354 return s1;
15355}
15356
15357Py_UNICODE*
15358Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15359{
15360 Py_UNICODE *u1 = s1;
15361 u1 += Py_UNICODE_strlen(u1);
15362 Py_UNICODE_strcpy(u1, s2);
15363 return s1;
15364}
15365
15366int
15367Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15368{
15369 while (*s1 && *s2 && *s1 == *s2)
15370 s1++, s2++;
15371 if (*s1 && *s2)
15372 return (*s1 < *s2) ? -1 : +1;
15373 if (*s1)
15374 return 1;
15375 if (*s2)
15376 return -1;
15377 return 0;
15378}
15379
15380int
15381Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15382{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015383 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015384 for (; n != 0; n--) {
15385 u1 = *s1;
15386 u2 = *s2;
15387 if (u1 != u2)
15388 return (u1 < u2) ? -1 : +1;
15389 if (u1 == '\0')
15390 return 0;
15391 s1++;
15392 s2++;
15393 }
15394 return 0;
15395}
15396
15397Py_UNICODE*
15398Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15399{
15400 const Py_UNICODE *p;
15401 for (p = s; *p; p++)
15402 if (*p == c)
15403 return (Py_UNICODE*)p;
15404 return NULL;
15405}
15406
15407Py_UNICODE*
15408Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15409{
15410 const Py_UNICODE *p;
15411 p = s + Py_UNICODE_strlen(s);
15412 while (p != s) {
15413 p--;
15414 if (*p == c)
15415 return (Py_UNICODE*)p;
15416 }
15417 return NULL;
15418}
Victor Stinner331ea922010-08-10 16:37:20 +000015419
Victor Stinner71133ff2010-09-01 23:43:53 +000015420Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015421PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015422{
Victor Stinner577db2c2011-10-11 22:12:48 +020015423 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015424 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015426 if (!PyUnicode_Check(unicode)) {
15427 PyErr_BadArgument();
15428 return NULL;
15429 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015430 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015431 if (u == NULL)
15432 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015433 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015434 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015435 PyErr_NoMemory();
15436 return NULL;
15437 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015438 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015439 size *= sizeof(Py_UNICODE);
15440 copy = PyMem_Malloc(size);
15441 if (copy == NULL) {
15442 PyErr_NoMemory();
15443 return NULL;
15444 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015445 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015446 return copy;
15447}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015448
Georg Brandl66c221e2010-10-14 07:04:07 +000015449/* A _string module, to export formatter_parser and formatter_field_name_split
15450 to the string.Formatter class implemented in Python. */
15451
15452static PyMethodDef _string_methods[] = {
15453 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15454 METH_O, PyDoc_STR("split the argument as a field name")},
15455 {"formatter_parser", (PyCFunction) formatter_parser,
15456 METH_O, PyDoc_STR("parse the argument as a format string")},
15457 {NULL, NULL}
15458};
15459
15460static struct PyModuleDef _string_module = {
15461 PyModuleDef_HEAD_INIT,
15462 "_string",
15463 PyDoc_STR("string helper module"),
15464 0,
15465 _string_methods,
15466 NULL,
15467 NULL,
15468 NULL,
15469 NULL
15470};
15471
15472PyMODINIT_FUNC
15473PyInit__string(void)
15474{
15475 return PyModule_Create(&_string_module);
15476}
15477
15478
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015479#ifdef __cplusplus
15480}
15481#endif