blob: 91be6031ca52537ceb64eb9c91bbf97260a04e2d [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
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200166#ifdef MS_WINDOWS
167 /* On Windows, overallocate by 50% is the best factor */
168# define OVERALLOCATE_FACTOR 2
169#else
170 /* On Linux, overallocate by 25% is the best factor */
171# define OVERALLOCATE_FACTOR 4
172#endif
173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 do { \
189 if (unicode_empty != NULL) \
190 Py_INCREF(unicode_empty); \
191 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192 unicode_empty = PyUnicode_New(0, 0); \
193 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200195 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
196 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200#define _Py_RETURN_UNICODE_EMPTY() \
201 do { \
202 _Py_INCREF_UNICODE_EMPTY(); \
203 return unicode_empty; \
204 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200206/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700207static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200208_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
209
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200210/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200212
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213/* Single character Unicode strings in the Latin-1 range are being
214 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Christian Heimes190d79e2008-01-30 11:58:22 +0000217/* Fast detection of the most frequent whitespace characters */
218const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000220/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000222/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x000C: * FORM FEED */
224/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 0, 1, 1, 1, 1, 1, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000227/* case 0x001C: * FILE SEPARATOR */
228/* case 0x001D: * GROUP SEPARATOR */
229/* case 0x001E: * RECORD SEPARATOR */
230/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000232/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000233 1, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000237
Benjamin Peterson14339b62009-01-31 16:36:08 +0000238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000246};
247
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200248/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200250static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100251static int unicode_modifiable(PyObject *unicode);
252
Victor Stinnerfe226c02011-10-03 03:52:20 +0200253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100255_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200256static PyObject *
257_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
258static PyObject *
259_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
260
261static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000263 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100264 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000265 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
266
Alexander Belopolsky40018472011-02-26 01:02:56 +0000267static void
268raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300269 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100270 PyObject *unicode,
271 Py_ssize_t startpos, Py_ssize_t endpos,
272 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200275static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278/* 0x000B, * LINE TABULATION */
279/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000281 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000283/* 0x001C, * FILE SEPARATOR */
284/* 0x001D, * GROUP SEPARATOR */
285/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 1, 1, 1, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000291
Benjamin Peterson14339b62009-01-31 16:36:08 +0000292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000300};
301
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300302#include "clinic/unicodeobject.c.h"
303
Victor Stinner50149202015-09-22 00:26:54 +0200304typedef enum {
305 _Py_ERROR_UNKNOWN=0,
306 _Py_ERROR_STRICT,
307 _Py_ERROR_SURROGATEESCAPE,
308 _Py_ERROR_REPLACE,
309 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200310 _Py_ERROR_BACKSLASHREPLACE,
311 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200312 _Py_ERROR_XMLCHARREFREPLACE,
313 _Py_ERROR_OTHER
314} _Py_error_handler;
315
316static _Py_error_handler
317get_error_handler(const char *errors)
318{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200321 }
322 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200323 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200324 }
325 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200326 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200327 }
328 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200329 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200330 }
331 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200332 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200333 }
334 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200335 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 }
337 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200338 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200339 }
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_OTHER;
341}
342
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300343/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
344 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000345Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000346PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000348#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000349 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000350#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000351 /* This is actually an illegal character, so it should
352 not be passed to unichr. */
353 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000354#endif
355}
356
Victor Stinner910337b2011-10-03 03:20:16 +0200357#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200358int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100359_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200360{
361 PyASCIIObject *ascii;
362 unsigned int kind;
363
364 assert(PyUnicode_Check(op));
365
366 ascii = (PyASCIIObject *)op;
367 kind = ascii->state.kind;
368
Victor Stinnera3b334d2011-10-03 13:53:37 +0200369 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200370 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 assert(ascii->state.ready == 1);
372 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200374 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200376
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 if (ascii->state.compact == 1) {
378 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200379 assert(kind == PyUnicode_1BYTE_KIND
380 || kind == PyUnicode_2BYTE_KIND
381 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200383 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200384 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100385 }
386 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200387 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
388
389 data = unicode->data.any;
390 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100391 assert(ascii->length == 0);
392 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 assert(ascii->state.compact == 0);
394 assert(ascii->state.ascii == 0);
395 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100396 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200397 assert(ascii->wstr != NULL);
398 assert(data == NULL);
399 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200400 }
401 else {
402 assert(kind == PyUnicode_1BYTE_KIND
403 || kind == PyUnicode_2BYTE_KIND
404 || kind == PyUnicode_4BYTE_KIND);
405 assert(ascii->state.compact == 0);
406 assert(ascii->state.ready == 1);
407 assert(data != NULL);
408 if (ascii->state.ascii) {
409 assert (compact->utf8 == data);
410 assert (compact->utf8_length == ascii->length);
411 }
412 else
413 assert (compact->utf8 != data);
414 }
415 }
416 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200417 if (
418#if SIZEOF_WCHAR_T == 2
419 kind == PyUnicode_2BYTE_KIND
420#else
421 kind == PyUnicode_4BYTE_KIND
422#endif
423 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200424 {
425 assert(ascii->wstr == data);
426 assert(compact->wstr_length == ascii->length);
427 } else
428 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200429 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200430
431 if (compact->utf8 == NULL)
432 assert(compact->utf8_length == 0);
433 if (ascii->wstr == NULL)
434 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200435 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200436 /* check that the best kind is used */
437 if (check_content && kind != PyUnicode_WCHAR_KIND)
438 {
439 Py_ssize_t i;
440 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200441 void *data;
442 Py_UCS4 ch;
443
444 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200445 for (i=0; i < ascii->length; i++)
446 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200447 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200448 if (ch > maxchar)
449 maxchar = ch;
450 }
451 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100452 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 255);
455 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200456 else
457 assert(maxchar < 128);
458 }
Victor Stinner77faf692011-11-20 18:56:05 +0100459 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200460 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100461 assert(maxchar <= 0xFFFF);
462 }
463 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200464 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100465 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100466 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200467 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200468 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400469 return 1;
470}
Victor Stinner910337b2011-10-03 03:20:16 +0200471#endif
472
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100473static PyObject*
474unicode_result_wchar(PyObject *unicode)
475{
476#ifndef Py_DEBUG
477 Py_ssize_t len;
478
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100479 len = _PyUnicode_WSTR_LENGTH(unicode);
480 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200482 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100483 }
484
485 if (len == 1) {
486 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100487 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100488 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
489 Py_DECREF(unicode);
490 return latin1_char;
491 }
492 }
493
494 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200495 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 return NULL;
497 }
498#else
Victor Stinneraa771272012-10-04 02:32:58 +0200499 assert(Py_REFCNT(unicode) == 1);
500
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100501 /* don't make the result ready in debug mode to ensure that the caller
502 makes the string ready before using it */
503 assert(_PyUnicode_CheckConsistency(unicode, 1));
504#endif
505 return unicode;
506}
507
508static PyObject*
509unicode_result_ready(PyObject *unicode)
510{
511 Py_ssize_t length;
512
513 length = PyUnicode_GET_LENGTH(unicode);
514 if (length == 0) {
515 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100516 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200517 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 }
519 return unicode_empty;
520 }
521
522 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200523 void *data = PyUnicode_DATA(unicode);
524 int kind = PyUnicode_KIND(unicode);
525 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100526 if (ch < 256) {
527 PyObject *latin1_char = unicode_latin1[ch];
528 if (latin1_char != NULL) {
529 if (unicode != latin1_char) {
530 Py_INCREF(latin1_char);
531 Py_DECREF(unicode);
532 }
533 return latin1_char;
534 }
535 else {
536 assert(_PyUnicode_CheckConsistency(unicode, 1));
537 Py_INCREF(unicode);
538 unicode_latin1[ch] = unicode;
539 return unicode;
540 }
541 }
542 }
543
544 assert(_PyUnicode_CheckConsistency(unicode, 1));
545 return unicode;
546}
547
548static PyObject*
549unicode_result(PyObject *unicode)
550{
551 assert(_PyUnicode_CHECK(unicode));
552 if (PyUnicode_IS_READY(unicode))
553 return unicode_result_ready(unicode);
554 else
555 return unicode_result_wchar(unicode);
556}
557
Victor Stinnerc4b49542011-12-11 22:44:26 +0100558static PyObject*
559unicode_result_unchanged(PyObject *unicode)
560{
561 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500562 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563 return NULL;
564 Py_INCREF(unicode);
565 return unicode;
566 }
567 else
568 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100569 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100570}
571
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
573 ASCII, Latin1, UTF-8, etc. */
574static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200575backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200576 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
577{
Victor Stinnerad771582015-10-09 12:38:53 +0200578 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200579 Py_UCS4 ch;
580 enum PyUnicode_Kind kind;
581 void *data;
582
583 assert(PyUnicode_IS_READY(unicode));
584 kind = PyUnicode_KIND(unicode);
585 data = PyUnicode_DATA(unicode);
586
587 size = 0;
588 /* determine replacement size */
589 for (i = collstart; i < collend; ++i) {
590 Py_ssize_t incr;
591
592 ch = PyUnicode_READ(kind, data, i);
593 if (ch < 0x100)
594 incr = 2+2;
595 else if (ch < 0x10000)
596 incr = 2+4;
597 else {
598 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200599 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200600 }
601 if (size > PY_SSIZE_T_MAX - incr) {
602 PyErr_SetString(PyExc_OverflowError,
603 "encoded result is too long for a Python string");
604 return NULL;
605 }
606 size += incr;
607 }
608
Victor Stinnerad771582015-10-09 12:38:53 +0200609 str = _PyBytesWriter_Prepare(writer, str, size);
610 if (str == NULL)
611 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200612
613 /* generate replacement */
614 for (i = collstart; i < collend; ++i) {
615 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200616 *str++ = '\\';
617 if (ch >= 0x00010000) {
618 *str++ = 'U';
619 *str++ = Py_hexdigits[(ch>>28)&0xf];
620 *str++ = Py_hexdigits[(ch>>24)&0xf];
621 *str++ = Py_hexdigits[(ch>>20)&0xf];
622 *str++ = Py_hexdigits[(ch>>16)&0xf];
623 *str++ = Py_hexdigits[(ch>>12)&0xf];
624 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200625 }
Victor Stinner797485e2015-10-09 03:17:30 +0200626 else if (ch >= 0x100) {
627 *str++ = 'u';
628 *str++ = Py_hexdigits[(ch>>12)&0xf];
629 *str++ = Py_hexdigits[(ch>>8)&0xf];
630 }
631 else
632 *str++ = 'x';
633 *str++ = Py_hexdigits[(ch>>4)&0xf];
634 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200635 }
636 return str;
637}
638
639/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
640 ASCII, Latin1, UTF-8, etc. */
641static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200642xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200643 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
644{
Victor Stinnerad771582015-10-09 12:38:53 +0200645 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200646 Py_UCS4 ch;
647 enum PyUnicode_Kind kind;
648 void *data;
649
650 assert(PyUnicode_IS_READY(unicode));
651 kind = PyUnicode_KIND(unicode);
652 data = PyUnicode_DATA(unicode);
653
654 size = 0;
655 /* determine replacement size */
656 for (i = collstart; i < collend; ++i) {
657 Py_ssize_t incr;
658
659 ch = PyUnicode_READ(kind, data, i);
660 if (ch < 10)
661 incr = 2+1+1;
662 else if (ch < 100)
663 incr = 2+2+1;
664 else if (ch < 1000)
665 incr = 2+3+1;
666 else if (ch < 10000)
667 incr = 2+4+1;
668 else if (ch < 100000)
669 incr = 2+5+1;
670 else if (ch < 1000000)
671 incr = 2+6+1;
672 else {
673 assert(ch <= MAX_UNICODE);
674 incr = 2+7+1;
675 }
676 if (size > PY_SSIZE_T_MAX - incr) {
677 PyErr_SetString(PyExc_OverflowError,
678 "encoded result is too long for a Python string");
679 return NULL;
680 }
681 size += incr;
682 }
683
Victor Stinnerad771582015-10-09 12:38:53 +0200684 str = _PyBytesWriter_Prepare(writer, str, size);
685 if (str == NULL)
686 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200687
688 /* generate replacement */
689 for (i = collstart; i < collend; ++i) {
690 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
691 }
692 return str;
693}
694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695/* --- Bloom Filters ----------------------------------------------------- */
696
697/* stuff to implement simple "bloom filters" for Unicode characters.
698 to keep things simple, we use a single bitmask, using the least 5
699 bits from each unicode characters as the bit index. */
700
701/* the linebreak mask is set up by Unicode_Init below */
702
Antoine Pitrouf068f942010-01-13 14:19:12 +0000703#if LONG_BIT >= 128
704#define BLOOM_WIDTH 128
705#elif LONG_BIT >= 64
706#define BLOOM_WIDTH 64
707#elif LONG_BIT >= 32
708#define BLOOM_WIDTH 32
709#else
710#error "LONG_BIT is smaller than 32"
711#endif
712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713#define BLOOM_MASK unsigned long
714
Serhiy Storchaka05997252013-01-26 12:14:02 +0200715static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716
Antoine Pitrouf068f942010-01-13 14:19:12 +0000717#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718
Benjamin Peterson29060642009-01-31 22:14:21 +0000719#define BLOOM_LINEBREAK(ch) \
720 ((ch) < 128U ? ascii_linebreak[(ch)] : \
721 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700723static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200724make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725{
Victor Stinnera85af502013-04-09 21:53:54 +0200726#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
727 do { \
728 TYPE *data = (TYPE *)PTR; \
729 TYPE *end = data + LEN; \
730 Py_UCS4 ch; \
731 for (; data != end; data++) { \
732 ch = *data; \
733 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
734 } \
735 break; \
736 } while (0)
737
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 /* calculate simple bloom-style bitmask for a given unicode string */
739
Antoine Pitrouf068f942010-01-13 14:19:12 +0000740 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741
742 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200743 switch (kind) {
744 case PyUnicode_1BYTE_KIND:
745 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
746 break;
747 case PyUnicode_2BYTE_KIND:
748 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
749 break;
750 case PyUnicode_4BYTE_KIND:
751 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
752 break;
753 default:
754 assert(0);
755 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200757
758#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759}
760
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300761static int
762ensure_unicode(PyObject *obj)
763{
764 if (!PyUnicode_Check(obj)) {
765 PyErr_Format(PyExc_TypeError,
766 "must be str, not %.100s",
767 Py_TYPE(obj)->tp_name);
768 return -1;
769 }
770 return PyUnicode_READY(obj);
771}
772
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773/* Compilation of templated routines */
774
775#include "stringlib/asciilib.h"
776#include "stringlib/fastsearch.h"
777#include "stringlib/partition.h"
778#include "stringlib/split.h"
779#include "stringlib/count.h"
780#include "stringlib/find.h"
781#include "stringlib/find_max_char.h"
782#include "stringlib/localeutil.h"
783#include "stringlib/undef.h"
784
785#include "stringlib/ucs1lib.h"
786#include "stringlib/fastsearch.h"
787#include "stringlib/partition.h"
788#include "stringlib/split.h"
789#include "stringlib/count.h"
790#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300791#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200792#include "stringlib/find_max_char.h"
793#include "stringlib/localeutil.h"
794#include "stringlib/undef.h"
795
796#include "stringlib/ucs2lib.h"
797#include "stringlib/fastsearch.h"
798#include "stringlib/partition.h"
799#include "stringlib/split.h"
800#include "stringlib/count.h"
801#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300802#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200803#include "stringlib/find_max_char.h"
804#include "stringlib/localeutil.h"
805#include "stringlib/undef.h"
806
807#include "stringlib/ucs4lib.h"
808#include "stringlib/fastsearch.h"
809#include "stringlib/partition.h"
810#include "stringlib/split.h"
811#include "stringlib/count.h"
812#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300813#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200814#include "stringlib/find_max_char.h"
815#include "stringlib/localeutil.h"
816#include "stringlib/undef.h"
817
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200818#include "stringlib/unicodedefs.h"
819#include "stringlib/fastsearch.h"
820#include "stringlib/count.h"
821#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100822#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823
Guido van Rossumd57fd912000-03-10 22:53:23 +0000824/* --- Unicode Object ----------------------------------------------------- */
825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200827fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700829static inline Py_ssize_t
830findchar(const void *s, int kind,
831 Py_ssize_t size, Py_UCS4 ch,
832 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200833{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 switch (kind) {
835 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200836 if ((Py_UCS1) ch != ch)
837 return -1;
838 if (direction > 0)
839 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
840 else
841 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200842 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200843 if ((Py_UCS2) ch != ch)
844 return -1;
845 if (direction > 0)
846 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
847 else
848 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200849 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if (direction > 0)
851 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
852 else
853 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200854 default:
855 assert(0);
856 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200858}
859
Victor Stinnerafffce42012-10-03 23:03:17 +0200860#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000861/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200862 earlier.
863
864 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
865 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
866 invalid character in Unicode 6.0. */
867static void
868unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
869{
870 int kind = PyUnicode_KIND(unicode);
871 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
872 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
873 if (length <= old_length)
874 return;
875 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
876}
877#endif
878
Victor Stinnerfe226c02011-10-03 03:52:20 +0200879static PyObject*
880resize_compact(PyObject *unicode, Py_ssize_t length)
881{
882 Py_ssize_t char_size;
883 Py_ssize_t struct_size;
884 Py_ssize_t new_size;
885 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100886 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200887#ifdef Py_DEBUG
888 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
889#endif
890
Victor Stinner79891572012-05-03 13:43:07 +0200891 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100893 assert(PyUnicode_IS_COMPACT(unicode));
894
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200895 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100896 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200897 struct_size = sizeof(PyASCIIObject);
898 else
899 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200900 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200901
Victor Stinnerfe226c02011-10-03 03:52:20 +0200902 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
903 PyErr_NoMemory();
904 return NULL;
905 }
906 new_size = (struct_size + (length + 1) * char_size);
907
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200908 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
909 PyObject_DEL(_PyUnicode_UTF8(unicode));
910 _PyUnicode_UTF8(unicode) = NULL;
911 _PyUnicode_UTF8_LENGTH(unicode) = 0;
912 }
Victor Stinner84def372011-12-11 20:04:56 +0100913 _Py_DEC_REFTOTAL;
914 _Py_ForgetReference(unicode);
915
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300916 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100917 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100918 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200919 PyErr_NoMemory();
920 return NULL;
921 }
Victor Stinner84def372011-12-11 20:04:56 +0100922 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200923 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100924
Victor Stinnerfe226c02011-10-03 03:52:20 +0200925 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200926 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200927 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100928 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200929 _PyUnicode_WSTR_LENGTH(unicode) = length;
930 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100931 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
932 PyObject_DEL(_PyUnicode_WSTR(unicode));
933 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100934 if (!PyUnicode_IS_ASCII(unicode))
935 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100936 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200937#ifdef Py_DEBUG
938 unicode_fill_invalid(unicode, old_length);
939#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
941 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200942 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200943 return unicode;
944}
945
Alexander Belopolsky40018472011-02-26 01:02:56 +0000946static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200947resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000948{
Victor Stinner95663112011-10-04 01:03:50 +0200949 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100950 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200951 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200952 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000953
Victor Stinnerfe226c02011-10-03 03:52:20 +0200954 if (PyUnicode_IS_READY(unicode)) {
955 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200956 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200957 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200958#ifdef Py_DEBUG
959 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
960#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200961
962 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200963 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
965 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200966
967 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
968 PyErr_NoMemory();
969 return -1;
970 }
971 new_size = (length + 1) * char_size;
972
Victor Stinner7a9105a2011-12-12 00:13:42 +0100973 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
974 {
975 PyObject_DEL(_PyUnicode_UTF8(unicode));
976 _PyUnicode_UTF8(unicode) = NULL;
977 _PyUnicode_UTF8_LENGTH(unicode) = 0;
978 }
979
Victor Stinnerfe226c02011-10-03 03:52:20 +0200980 data = (PyObject *)PyObject_REALLOC(data, new_size);
981 if (data == NULL) {
982 PyErr_NoMemory();
983 return -1;
984 }
985 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200986 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200987 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200988 _PyUnicode_WSTR_LENGTH(unicode) = length;
989 }
990 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200991 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200992 _PyUnicode_UTF8_LENGTH(unicode) = length;
993 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200994 _PyUnicode_LENGTH(unicode) = length;
995 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200996#ifdef Py_DEBUG
997 unicode_fill_invalid(unicode, old_length);
998#endif
Victor Stinner95663112011-10-04 01:03:50 +0200999 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001000 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003 }
Victor Stinner95663112011-10-04 01:03:50 +02001004 assert(_PyUnicode_WSTR(unicode) != NULL);
1005
1006 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001007 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001008 PyErr_NoMemory();
1009 return -1;
1010 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001012 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001013 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001014 if (!wstr) {
1015 PyErr_NoMemory();
1016 return -1;
1017 }
1018 _PyUnicode_WSTR(unicode) = wstr;
1019 _PyUnicode_WSTR(unicode)[length] = 0;
1020 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001021 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001022 return 0;
1023}
1024
Victor Stinnerfe226c02011-10-03 03:52:20 +02001025static PyObject*
1026resize_copy(PyObject *unicode, Py_ssize_t length)
1027{
1028 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001029 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001030 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001031
Benjamin Petersonbac79492012-01-14 13:34:47 -05001032 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001033 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001034
1035 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1036 if (copy == NULL)
1037 return NULL;
1038
1039 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001040 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001041 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001042 }
1043 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001044 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001045
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001046 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001047 if (w == NULL)
1048 return NULL;
1049 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1050 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001051 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001052 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001053 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001054 }
1055}
1056
Guido van Rossumd57fd912000-03-10 22:53:23 +00001057/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001058 Ux0000 terminated; some code (e.g. new_identifier)
1059 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001060
1061 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001062 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001063
1064*/
1065
Alexander Belopolsky40018472011-02-26 01:02:56 +00001066static PyUnicodeObject *
1067_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001068{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001069 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001071
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001073 if (length == 0 && unicode_empty != NULL) {
1074 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001075 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001076 }
1077
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001078 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001079 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001080 return (PyUnicodeObject *)PyErr_NoMemory();
1081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 if (length < 0) {
1083 PyErr_SetString(PyExc_SystemError,
1084 "Negative size passed to _PyUnicode_New");
1085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001086 }
1087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001088 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1089 if (unicode == NULL)
1090 return NULL;
1091 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001092
1093 _PyUnicode_WSTR_LENGTH(unicode) = length;
1094 _PyUnicode_HASH(unicode) = -1;
1095 _PyUnicode_STATE(unicode).interned = 0;
1096 _PyUnicode_STATE(unicode).kind = 0;
1097 _PyUnicode_STATE(unicode).compact = 0;
1098 _PyUnicode_STATE(unicode).ready = 0;
1099 _PyUnicode_STATE(unicode).ascii = 0;
1100 _PyUnicode_DATA_ANY(unicode) = NULL;
1101 _PyUnicode_LENGTH(unicode) = 0;
1102 _PyUnicode_UTF8(unicode) = NULL;
1103 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1106 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001107 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001108 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001109 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111
Jeremy Hyltond8082792003-09-16 19:41:39 +00001112 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001113 * the caller fails before initializing str -- unicode_resize()
1114 * reads str[0], and the Keep-Alive optimization can keep memory
1115 * allocated for str alive across a call to unicode_dealloc(unicode).
1116 * We don't want unicode_resize to read uninitialized memory in
1117 * that case.
1118 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 _PyUnicode_WSTR(unicode)[0] = 0;
1120 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001121
Victor Stinner7931d9a2011-11-04 00:22:48 +01001122 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001123 return unicode;
1124}
1125
Victor Stinnerf42dc442011-10-02 23:33:16 +02001126static const char*
1127unicode_kind_name(PyObject *unicode)
1128{
Victor Stinner42dfd712011-10-03 14:41:45 +02001129 /* don't check consistency: unicode_kind_name() is called from
1130 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001131 if (!PyUnicode_IS_COMPACT(unicode))
1132 {
1133 if (!PyUnicode_IS_READY(unicode))
1134 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001135 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001136 {
1137 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 return "legacy ascii";
1140 else
1141 return "legacy latin1";
1142 case PyUnicode_2BYTE_KIND:
1143 return "legacy UCS2";
1144 case PyUnicode_4BYTE_KIND:
1145 return "legacy UCS4";
1146 default:
1147 return "<legacy invalid kind>";
1148 }
1149 }
1150 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001151 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001153 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001154 return "ascii";
1155 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001156 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001157 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001158 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001159 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001160 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001161 default:
1162 return "<invalid compact kind>";
1163 }
1164}
1165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167/* Functions wrapping macros for use in debugger */
1168char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001169 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170}
1171
1172void *_PyUnicode_compact_data(void *unicode) {
1173 return _PyUnicode_COMPACT_DATA(unicode);
1174}
1175void *_PyUnicode_data(void *unicode){
1176 printf("obj %p\n", unicode);
1177 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1178 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1179 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1180 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1181 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1182 return PyUnicode_DATA(unicode);
1183}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001184
1185void
1186_PyUnicode_Dump(PyObject *op)
1187{
1188 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001189 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1190 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1191 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001192
Victor Stinnera849a4b2011-10-03 12:12:11 +02001193 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001194 {
1195 if (ascii->state.ascii)
1196 data = (ascii + 1);
1197 else
1198 data = (compact + 1);
1199 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001200 else
1201 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001202 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1203 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->wstr == data)
1206 printf("shared ");
1207 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001208
Victor Stinnera3b334d2011-10-03 13:53:37 +02001209 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001210 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001211 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1212 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001213 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1214 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001215 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001216 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001217}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218#endif
1219
1220PyObject *
1221PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1222{
1223 PyObject *obj;
1224 PyCompactUnicodeObject *unicode;
1225 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001226 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001227 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 Py_ssize_t char_size;
1229 Py_ssize_t struct_size;
1230
1231 /* Optimization for empty strings */
1232 if (size == 0 && unicode_empty != NULL) {
1233 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001234 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235 }
1236
Victor Stinner9e9d6892011-10-04 01:02:02 +02001237 is_ascii = 0;
1238 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001239 struct_size = sizeof(PyCompactUnicodeObject);
1240 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001241 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001242 char_size = 1;
1243 is_ascii = 1;
1244 struct_size = sizeof(PyASCIIObject);
1245 }
1246 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001247 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248 char_size = 1;
1249 }
1250 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001251 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 char_size = 2;
1253 if (sizeof(wchar_t) == 2)
1254 is_sharing = 1;
1255 }
1256 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001257 if (maxchar > MAX_UNICODE) {
1258 PyErr_SetString(PyExc_SystemError,
1259 "invalid maximum character passed to PyUnicode_New");
1260 return NULL;
1261 }
Victor Stinner8f825062012-04-27 13:55:39 +02001262 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 char_size = 4;
1264 if (sizeof(wchar_t) == 4)
1265 is_sharing = 1;
1266 }
1267
1268 /* Ensure we won't overflow the size. */
1269 if (size < 0) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "Negative size passed to PyUnicode_New");
1272 return NULL;
1273 }
1274 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1275 return PyErr_NoMemory();
1276
1277 /* Duplicated allocation code from _PyObject_New() instead of a call to
1278 * PyObject_New() so we are able to allocate space for the object and
1279 * it's data buffer.
1280 */
1281 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1282 if (obj == NULL)
1283 return PyErr_NoMemory();
1284 obj = PyObject_INIT(obj, &PyUnicode_Type);
1285 if (obj == NULL)
1286 return NULL;
1287
1288 unicode = (PyCompactUnicodeObject *)obj;
1289 if (is_ascii)
1290 data = ((PyASCIIObject*)obj) + 1;
1291 else
1292 data = unicode + 1;
1293 _PyUnicode_LENGTH(unicode) = size;
1294 _PyUnicode_HASH(unicode) = -1;
1295 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001296 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 _PyUnicode_STATE(unicode).compact = 1;
1298 _PyUnicode_STATE(unicode).ready = 1;
1299 _PyUnicode_STATE(unicode).ascii = is_ascii;
1300 if (is_ascii) {
1301 ((char*)data)[size] = 0;
1302 _PyUnicode_WSTR(unicode) = NULL;
1303 }
Victor Stinner8f825062012-04-27 13:55:39 +02001304 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 ((char*)data)[size] = 0;
1306 _PyUnicode_WSTR(unicode) = NULL;
1307 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001309 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 else {
1312 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001313 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001314 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((Py_UCS4*)data)[size] = 0;
1318 if (is_sharing) {
1319 _PyUnicode_WSTR_LENGTH(unicode) = size;
1320 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1321 }
1322 else {
1323 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1324 _PyUnicode_WSTR(unicode) = NULL;
1325 }
1326 }
Victor Stinner8f825062012-04-27 13:55:39 +02001327#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001328 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001329#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001330 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001331 return obj;
1332}
1333
1334#if SIZEOF_WCHAR_T == 2
1335/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1336 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001337 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338
1339 This function assumes that unicode can hold one more code point than wstr
1340 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001341static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001343 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344{
1345 const wchar_t *iter;
1346 Py_UCS4 *ucs4_out;
1347
Victor Stinner910337b2011-10-03 03:20:16 +02001348 assert(unicode != NULL);
1349 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1351 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1352
1353 for (iter = begin; iter < end; ) {
1354 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1355 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001356 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1357 && (iter+1) < end
1358 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001359 {
Victor Stinner551ac952011-11-29 22:58:13 +01001360 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 iter += 2;
1362 }
1363 else {
1364 *ucs4_out++ = *iter;
1365 iter++;
1366 }
1367 }
1368 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1369 _PyUnicode_GET_LENGTH(unicode)));
1370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371}
1372#endif
1373
Victor Stinnercd9950f2011-10-02 00:34:53 +02001374static int
Victor Stinner488fa492011-12-12 00:01:39 +01001375unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001376{
Victor Stinner488fa492011-12-12 00:01:39 +01001377 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001378 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001379 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001380 return -1;
1381 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001382 return 0;
1383}
1384
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385static int
1386_copy_characters(PyObject *to, Py_ssize_t to_start,
1387 PyObject *from, Py_ssize_t from_start,
1388 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001390 unsigned int from_kind, to_kind;
1391 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
Victor Stinneree4544c2012-05-09 22:24:08 +02001393 assert(0 <= how_many);
1394 assert(0 <= from_start);
1395 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001398 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399
Victor Stinnerd3f08822012-05-29 12:57:52 +02001400 assert(PyUnicode_Check(to));
1401 assert(PyUnicode_IS_READY(to));
1402 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1403
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001404 if (how_many == 0)
1405 return 0;
1406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001408 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001410 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerf1852262012-06-16 16:38:26 +02001412#ifdef Py_DEBUG
1413 if (!check_maxchar
1414 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1415 {
1416 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1417 Py_UCS4 ch;
1418 Py_ssize_t i;
1419 for (i=0; i < how_many; i++) {
1420 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1421 assert(ch <= to_maxchar);
1422 }
1423 }
1424#endif
1425
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001426 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001427 if (check_maxchar
1428 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1429 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001430 /* Writing Latin-1 characters into an ASCII string requires to
1431 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001432 Py_UCS4 max_char;
1433 max_char = ucs1lib_find_max_char(from_data,
1434 (Py_UCS1*)from_data + how_many);
1435 if (max_char >= 128)
1436 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001437 }
Christian Heimesf051e432016-09-13 20:22:02 +02001438 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001439 (char*)from_data + from_kind * from_start,
1440 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001441 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001442 else if (from_kind == PyUnicode_1BYTE_KIND
1443 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001444 {
1445 _PyUnicode_CONVERT_BYTES(
1446 Py_UCS1, Py_UCS2,
1447 PyUnicode_1BYTE_DATA(from) + from_start,
1448 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1449 PyUnicode_2BYTE_DATA(to) + to_start
1450 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001451 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001452 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001453 && to_kind == PyUnicode_4BYTE_KIND)
1454 {
1455 _PyUnicode_CONVERT_BYTES(
1456 Py_UCS1, Py_UCS4,
1457 PyUnicode_1BYTE_DATA(from) + from_start,
1458 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1459 PyUnicode_4BYTE_DATA(to) + to_start
1460 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001461 }
1462 else if (from_kind == PyUnicode_2BYTE_KIND
1463 && to_kind == PyUnicode_4BYTE_KIND)
1464 {
1465 _PyUnicode_CONVERT_BYTES(
1466 Py_UCS2, Py_UCS4,
1467 PyUnicode_2BYTE_DATA(from) + from_start,
1468 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1469 PyUnicode_4BYTE_DATA(to) + to_start
1470 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001471 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001472 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001473 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1474
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001475 if (!check_maxchar) {
1476 if (from_kind == PyUnicode_2BYTE_KIND
1477 && to_kind == PyUnicode_1BYTE_KIND)
1478 {
1479 _PyUnicode_CONVERT_BYTES(
1480 Py_UCS2, Py_UCS1,
1481 PyUnicode_2BYTE_DATA(from) + from_start,
1482 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1483 PyUnicode_1BYTE_DATA(to) + to_start
1484 );
1485 }
1486 else if (from_kind == PyUnicode_4BYTE_KIND
1487 && to_kind == PyUnicode_1BYTE_KIND)
1488 {
1489 _PyUnicode_CONVERT_BYTES(
1490 Py_UCS4, Py_UCS1,
1491 PyUnicode_4BYTE_DATA(from) + from_start,
1492 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1493 PyUnicode_1BYTE_DATA(to) + to_start
1494 );
1495 }
1496 else if (from_kind == PyUnicode_4BYTE_KIND
1497 && to_kind == PyUnicode_2BYTE_KIND)
1498 {
1499 _PyUnicode_CONVERT_BYTES(
1500 Py_UCS4, Py_UCS2,
1501 PyUnicode_4BYTE_DATA(from) + from_start,
1502 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1503 PyUnicode_2BYTE_DATA(to) + to_start
1504 );
1505 }
1506 else {
1507 assert(0);
1508 return -1;
1509 }
1510 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001511 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001512 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001513 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001514 Py_ssize_t i;
1515
Victor Stinnera0702ab2011-09-29 14:14:38 +02001516 for (i=0; i < how_many; i++) {
1517 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001518 if (ch > to_maxchar)
1519 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001520 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1521 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001522 }
1523 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 return 0;
1525}
1526
Victor Stinnerd3f08822012-05-29 12:57:52 +02001527void
1528_PyUnicode_FastCopyCharacters(
1529 PyObject *to, Py_ssize_t to_start,
1530 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001531{
1532 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1533}
1534
1535Py_ssize_t
1536PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1537 PyObject *from, Py_ssize_t from_start,
1538 Py_ssize_t how_many)
1539{
1540 int err;
1541
1542 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1543 PyErr_BadInternalCall();
1544 return -1;
1545 }
1546
Benjamin Petersonbac79492012-01-14 13:34:47 -05001547 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001548 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001549 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001550 return -1;
1551
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001552 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001553 PyErr_SetString(PyExc_IndexError, "string index out of range");
1554 return -1;
1555 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001556 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001557 PyErr_SetString(PyExc_IndexError, "string index out of range");
1558 return -1;
1559 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001560 if (how_many < 0) {
1561 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1562 return -1;
1563 }
1564 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001565 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1566 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001567 "Cannot write %zi characters at %zi "
1568 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001569 how_many, to_start, PyUnicode_GET_LENGTH(to));
1570 return -1;
1571 }
1572
1573 if (how_many == 0)
1574 return 0;
1575
Victor Stinner488fa492011-12-12 00:01:39 +01001576 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001577 return -1;
1578
1579 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1580 if (err) {
1581 PyErr_Format(PyExc_SystemError,
1582 "Cannot copy %s characters "
1583 "into a string of %s characters",
1584 unicode_kind_name(from),
1585 unicode_kind_name(to));
1586 return -1;
1587 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001588 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001589}
1590
Victor Stinner17222162011-09-28 22:15:37 +02001591/* Find the maximum code point and count the number of surrogate pairs so a
1592 correct string length can be computed before converting a string to UCS4.
1593 This function counts single surrogates as a character and not as a pair.
1594
1595 Return 0 on success, or -1 on error. */
1596static int
1597find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1598 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599{
1600 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001601 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602
Victor Stinnerc53be962011-10-02 21:33:54 +02001603 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604 *num_surrogates = 0;
1605 *maxchar = 0;
1606
1607 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001609 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1610 && (iter+1) < end
1611 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1612 {
1613 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1614 ++(*num_surrogates);
1615 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001616 }
1617 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001618#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001619 {
1620 ch = *iter;
1621 iter++;
1622 }
1623 if (ch > *maxchar) {
1624 *maxchar = ch;
1625 if (*maxchar > MAX_UNICODE) {
1626 PyErr_Format(PyExc_ValueError,
1627 "character U+%x is not in range [U+0000; U+10ffff]",
1628 ch);
1629 return -1;
1630 }
1631 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 }
1633 return 0;
1634}
1635
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001636int
1637_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638{
1639 wchar_t *end;
1640 Py_UCS4 maxchar = 0;
1641 Py_ssize_t num_surrogates;
1642#if SIZEOF_WCHAR_T == 2
1643 Py_ssize_t length_wo_surrogates;
1644#endif
1645
Georg Brandl7597add2011-10-05 16:36:47 +02001646 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001647 strings were created using _PyObject_New() and where no canonical
1648 representation (the str field) has been set yet aka strings
1649 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001650 assert(_PyUnicode_CHECK(unicode));
1651 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001653 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001654 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001655 /* Actually, it should neither be interned nor be anything else: */
1656 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001659 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001660 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001662
1663 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1665 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 PyErr_NoMemory();
1667 return -1;
1668 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001669 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001670 _PyUnicode_WSTR(unicode), end,
1671 PyUnicode_1BYTE_DATA(unicode));
1672 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1673 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1674 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1675 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001676 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001677 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001678 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001679 }
1680 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001681 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001682 _PyUnicode_UTF8(unicode) = NULL;
1683 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001684 }
1685 PyObject_FREE(_PyUnicode_WSTR(unicode));
1686 _PyUnicode_WSTR(unicode) = NULL;
1687 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1688 }
1689 /* In this case we might have to convert down from 4-byte native
1690 wchar_t to 2-byte unicode. */
1691 else if (maxchar < 65536) {
1692 assert(num_surrogates == 0 &&
1693 "FindMaxCharAndNumSurrogatePairs() messed up");
1694
Victor Stinner506f5922011-09-28 22:34:18 +02001695#if SIZEOF_WCHAR_T == 2
1696 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001697 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001698 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1699 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1700 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001701 _PyUnicode_UTF8(unicode) = NULL;
1702 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001703#else
1704 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001705 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001706 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001707 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001708 PyErr_NoMemory();
1709 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 }
Victor Stinner506f5922011-09-28 22:34:18 +02001711 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1712 _PyUnicode_WSTR(unicode), end,
1713 PyUnicode_2BYTE_DATA(unicode));
1714 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1715 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1716 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001717 _PyUnicode_UTF8(unicode) = NULL;
1718 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyObject_FREE(_PyUnicode_WSTR(unicode));
1720 _PyUnicode_WSTR(unicode) = NULL;
1721 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1722#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723 }
1724 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1725 else {
1726#if SIZEOF_WCHAR_T == 2
1727 /* in case the native representation is 2-bytes, we need to allocate a
1728 new normalized 4-byte version. */
1729 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001730 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1731 PyErr_NoMemory();
1732 return -1;
1733 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001734 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1735 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 PyErr_NoMemory();
1737 return -1;
1738 }
1739 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1740 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001741 _PyUnicode_UTF8(unicode) = NULL;
1742 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001743 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1744 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001745 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 PyObject_FREE(_PyUnicode_WSTR(unicode));
1747 _PyUnicode_WSTR(unicode) = NULL;
1748 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1749#else
1750 assert(num_surrogates == 0);
1751
Victor Stinnerc3c74152011-10-02 20:39:55 +02001752 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001754 _PyUnicode_UTF8(unicode) = NULL;
1755 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1757#endif
1758 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1759 }
1760 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001761 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 return 0;
1763}
1764
Alexander Belopolsky40018472011-02-26 01:02:56 +00001765static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001766unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001767{
Walter Dörwald16807132007-05-25 13:52:07 +00001768 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001769 case SSTATE_NOT_INTERNED:
1770 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001771
Benjamin Peterson29060642009-01-31 22:14:21 +00001772 case SSTATE_INTERNED_MORTAL:
1773 /* revive dead object temporarily for DelItem */
1774 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001775 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001776 Py_FatalError(
1777 "deletion of interned string failed");
1778 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001779
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_INTERNED_IMMORTAL:
1781 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 default:
1784 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001785 }
1786
Victor Stinner03490912011-10-03 23:45:12 +02001787 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001789 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001790 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001791 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1792 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001794 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001795}
1796
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001797#ifdef Py_DEBUG
1798static int
1799unicode_is_singleton(PyObject *unicode)
1800{
1801 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1802 if (unicode == unicode_empty)
1803 return 1;
1804 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1805 {
1806 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1807 if (ch < 256 && unicode_latin1[ch] == unicode)
1808 return 1;
1809 }
1810 return 0;
1811}
1812#endif
1813
Alexander Belopolsky40018472011-02-26 01:02:56 +00001814static int
Victor Stinner488fa492011-12-12 00:01:39 +01001815unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001816{
Victor Stinner488fa492011-12-12 00:01:39 +01001817 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001818 if (Py_REFCNT(unicode) != 1)
1819 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001820 if (_PyUnicode_HASH(unicode) != -1)
1821 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001822 if (PyUnicode_CHECK_INTERNED(unicode))
1823 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001824 if (!PyUnicode_CheckExact(unicode))
1825 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001826#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001827 /* singleton refcount is greater than 1 */
1828 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001829#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 return 1;
1831}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001832
Victor Stinnerfe226c02011-10-03 03:52:20 +02001833static int
1834unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1835{
1836 PyObject *unicode;
1837 Py_ssize_t old_length;
1838
1839 assert(p_unicode != NULL);
1840 unicode = *p_unicode;
1841
1842 assert(unicode != NULL);
1843 assert(PyUnicode_Check(unicode));
1844 assert(0 <= length);
1845
Victor Stinner910337b2011-10-03 03:20:16 +02001846 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001847 old_length = PyUnicode_WSTR_LENGTH(unicode);
1848 else
1849 old_length = PyUnicode_GET_LENGTH(unicode);
1850 if (old_length == length)
1851 return 0;
1852
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001853 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001854 _Py_INCREF_UNICODE_EMPTY();
1855 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001856 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001857 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001858 return 0;
1859 }
1860
Victor Stinner488fa492011-12-12 00:01:39 +01001861 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001862 PyObject *copy = resize_copy(unicode, length);
1863 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001864 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001865 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001866 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001867 }
1868
Victor Stinnerfe226c02011-10-03 03:52:20 +02001869 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001870 PyObject *new_unicode = resize_compact(unicode, length);
1871 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001872 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001873 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001875 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001876 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001877}
1878
Alexander Belopolsky40018472011-02-26 01:02:56 +00001879int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001880PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001881{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001882 PyObject *unicode;
1883 if (p_unicode == NULL) {
1884 PyErr_BadInternalCall();
1885 return -1;
1886 }
1887 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001888 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001889 {
1890 PyErr_BadInternalCall();
1891 return -1;
1892 }
1893 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001894}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001895
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001896/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001897
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001898 WARNING: The function doesn't copy the terminating null character and
1899 doesn't check the maximum character (may write a latin1 character in an
1900 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001901static void
1902unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1903 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001904{
1905 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1906 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001907 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001908
1909 switch (kind) {
1910 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001911 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001912#ifdef Py_DEBUG
1913 if (PyUnicode_IS_ASCII(unicode)) {
1914 Py_UCS4 maxchar = ucs1lib_find_max_char(
1915 (const Py_UCS1*)str,
1916 (const Py_UCS1*)str + len);
1917 assert(maxchar < 128);
1918 }
1919#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001920 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001921 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001922 }
1923 case PyUnicode_2BYTE_KIND: {
1924 Py_UCS2 *start = (Py_UCS2 *)data + index;
1925 Py_UCS2 *ucs2 = start;
1926 assert(index <= PyUnicode_GET_LENGTH(unicode));
1927
Victor Stinner184252a2012-06-16 02:57:41 +02001928 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001929 *ucs2 = (Py_UCS2)*str;
1930
1931 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001932 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001933 }
1934 default: {
1935 Py_UCS4 *start = (Py_UCS4 *)data + index;
1936 Py_UCS4 *ucs4 = start;
1937 assert(kind == PyUnicode_4BYTE_KIND);
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs4 = (Py_UCS4)*str;
1942
1943 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001944 }
1945 }
1946}
1947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948static PyObject*
1949get_latin1_char(unsigned char ch)
1950{
Victor Stinnera464fc12011-10-02 20:39:30 +02001951 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001953 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 if (!unicode)
1955 return NULL;
1956 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001957 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958 unicode_latin1[ch] = unicode;
1959 }
1960 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001961 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962}
1963
Victor Stinner985a82a2014-01-03 12:53:47 +01001964static PyObject*
1965unicode_char(Py_UCS4 ch)
1966{
1967 PyObject *unicode;
1968
1969 assert(ch <= MAX_UNICODE);
1970
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001971 if (ch < 256)
1972 return get_latin1_char(ch);
1973
Victor Stinner985a82a2014-01-03 12:53:47 +01001974 unicode = PyUnicode_New(1, ch);
1975 if (unicode == NULL)
1976 return NULL;
1977 switch (PyUnicode_KIND(unicode)) {
1978 case PyUnicode_1BYTE_KIND:
1979 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1980 break;
1981 case PyUnicode_2BYTE_KIND:
1982 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1983 break;
1984 default:
1985 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1986 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1987 }
1988 assert(_PyUnicode_CheckConsistency(unicode, 1));
1989 return unicode;
1990}
1991
Alexander Belopolsky40018472011-02-26 01:02:56 +00001992PyObject *
1993PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001994{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001995 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001996 Py_UCS4 maxchar = 0;
1997 Py_ssize_t num_surrogates;
1998
1999 if (u == NULL)
2000 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002001
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002002 /* If the Unicode data is known at construction time, we can apply
2003 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002006 if (size == 0)
2007 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 /* Single character Unicode objects in the Latin-1 range are
2010 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002011 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 return get_latin1_char((unsigned char)*u);
2013
2014 /* If not empty and not single character, copy the Unicode data
2015 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002016 if (find_maxchar_surrogates(u, u + size,
2017 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 return NULL;
2019
Victor Stinner8faf8212011-12-08 22:14:11 +01002020 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002021 if (!unicode)
2022 return NULL;
2023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002024 switch (PyUnicode_KIND(unicode)) {
2025 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002026 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002027 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2028 break;
2029 case PyUnicode_2BYTE_KIND:
2030#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002031 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002033 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2035#endif
2036 break;
2037 case PyUnicode_4BYTE_KIND:
2038#if SIZEOF_WCHAR_T == 2
2039 /* This is the only case which has to process surrogates, thus
2040 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002041 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002042#else
2043 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002044 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002045#endif
2046 break;
2047 default:
2048 assert(0 && "Impossible state");
2049 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002051 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002052}
2053
Alexander Belopolsky40018472011-02-26 01:02:56 +00002054PyObject *
2055PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002056{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002057 if (size < 0) {
2058 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002059 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002060 return NULL;
2061 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002062 if (u != NULL)
2063 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2064 else
2065 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002066}
2067
Alexander Belopolsky40018472011-02-26 01:02:56 +00002068PyObject *
2069PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002070{
2071 size_t size = strlen(u);
2072 if (size > PY_SSIZE_T_MAX) {
2073 PyErr_SetString(PyExc_OverflowError, "input too long");
2074 return NULL;
2075 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002076 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002077}
2078
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002079PyObject *
2080_PyUnicode_FromId(_Py_Identifier *id)
2081{
2082 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002083 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2084 strlen(id->string),
2085 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002086 if (!id->object)
2087 return NULL;
2088 PyUnicode_InternInPlace(&id->object);
2089 assert(!id->next);
2090 id->next = static_strings;
2091 static_strings = id;
2092 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002093 return id->object;
2094}
2095
2096void
2097_PyUnicode_ClearStaticStrings()
2098{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002099 _Py_Identifier *tmp, *s = static_strings;
2100 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002101 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002102 tmp = s->next;
2103 s->next = NULL;
2104 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002105 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002106 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002107}
2108
Benjamin Peterson0df54292012-03-26 14:50:32 -04002109/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002110
Victor Stinnerd3f08822012-05-29 12:57:52 +02002111PyObject*
2112_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002113{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002114 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002115 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002116 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002117#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002118 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002119#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002120 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002121 }
Victor Stinner785938e2011-12-11 20:09:03 +01002122 unicode = PyUnicode_New(size, 127);
2123 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002124 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002125 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2126 assert(_PyUnicode_CheckConsistency(unicode, 1));
2127 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002128}
2129
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002130static Py_UCS4
2131kind_maxchar_limit(unsigned int kind)
2132{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002133 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002134 case PyUnicode_1BYTE_KIND:
2135 return 0x80;
2136 case PyUnicode_2BYTE_KIND:
2137 return 0x100;
2138 case PyUnicode_4BYTE_KIND:
2139 return 0x10000;
2140 default:
2141 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002142 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002143 }
2144}
2145
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -07002146static inline Py_UCS4
Victor Stinnere6abb482012-05-02 01:15:40 +02002147align_maxchar(Py_UCS4 maxchar)
2148{
2149 if (maxchar <= 127)
2150 return 127;
2151 else if (maxchar <= 255)
2152 return 255;
2153 else if (maxchar <= 65535)
2154 return 65535;
2155 else
2156 return MAX_UNICODE;
2157}
2158
Victor Stinner702c7342011-10-05 13:50:52 +02002159static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002160_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002163 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002164
Serhiy Storchaka678db842013-01-26 12:16:36 +02002165 if (size == 0)
2166 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002167 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002168 if (size == 1)
2169 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002170
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002171 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002172 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 if (!res)
2174 return NULL;
2175 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002176 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002178}
2179
Victor Stinnere57b1c02011-09-28 22:20:48 +02002180static PyObject*
2181_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002182{
2183 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002184 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002185
Serhiy Storchaka678db842013-01-26 12:16:36 +02002186 if (size == 0)
2187 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002188 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002189 if (size == 1)
2190 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002191
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002192 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002193 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002194 if (!res)
2195 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002196 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002198 else {
2199 _PyUnicode_CONVERT_BYTES(
2200 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2201 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002202 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203 return res;
2204}
2205
Victor Stinnere57b1c02011-09-28 22:20:48 +02002206static PyObject*
2207_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208{
2209 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211
Serhiy Storchaka678db842013-01-26 12:16:36 +02002212 if (size == 0)
2213 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002214 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002215 if (size == 1)
2216 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002217
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002218 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002219 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 if (!res)
2221 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002222 if (max_char < 256)
2223 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2224 PyUnicode_1BYTE_DATA(res));
2225 else if (max_char < 0x10000)
2226 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2227 PyUnicode_2BYTE_DATA(res));
2228 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002230 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002231 return res;
2232}
2233
2234PyObject*
2235PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2236{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002237 if (size < 0) {
2238 PyErr_SetString(PyExc_ValueError, "size must be positive");
2239 return NULL;
2240 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002241 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002243 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002245 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002247 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002248 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002249 PyErr_SetString(PyExc_SystemError, "invalid kind");
2250 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252}
2253
Victor Stinnerece58de2012-04-23 23:36:38 +02002254Py_UCS4
2255_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2256{
2257 enum PyUnicode_Kind kind;
2258 void *startptr, *endptr;
2259
2260 assert(PyUnicode_IS_READY(unicode));
2261 assert(0 <= start);
2262 assert(end <= PyUnicode_GET_LENGTH(unicode));
2263 assert(start <= end);
2264
2265 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2266 return PyUnicode_MAX_CHAR_VALUE(unicode);
2267
2268 if (start == end)
2269 return 127;
2270
Victor Stinner94d558b2012-04-27 22:26:58 +02002271 if (PyUnicode_IS_ASCII(unicode))
2272 return 127;
2273
Victor Stinnerece58de2012-04-23 23:36:38 +02002274 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002275 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002276 endptr = (char *)startptr + end * kind;
2277 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002278 switch(kind) {
2279 case PyUnicode_1BYTE_KIND:
2280 return ucs1lib_find_max_char(startptr, endptr);
2281 case PyUnicode_2BYTE_KIND:
2282 return ucs2lib_find_max_char(startptr, endptr);
2283 case PyUnicode_4BYTE_KIND:
2284 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002285 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002286 assert(0);
2287 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002288 }
2289}
2290
Victor Stinner25a4b292011-10-06 12:31:55 +02002291/* Ensure that a string uses the most efficient storage, if it is not the
2292 case: create a new string with of the right kind. Write NULL into *p_unicode
2293 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002294static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002295unicode_adjust_maxchar(PyObject **p_unicode)
2296{
2297 PyObject *unicode, *copy;
2298 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002299 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002300 unsigned int kind;
2301
2302 assert(p_unicode != NULL);
2303 unicode = *p_unicode;
2304 assert(PyUnicode_IS_READY(unicode));
2305 if (PyUnicode_IS_ASCII(unicode))
2306 return;
2307
2308 len = PyUnicode_GET_LENGTH(unicode);
2309 kind = PyUnicode_KIND(unicode);
2310 if (kind == PyUnicode_1BYTE_KIND) {
2311 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002312 max_char = ucs1lib_find_max_char(u, u + len);
2313 if (max_char >= 128)
2314 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002315 }
2316 else if (kind == PyUnicode_2BYTE_KIND) {
2317 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002318 max_char = ucs2lib_find_max_char(u, u + len);
2319 if (max_char >= 256)
2320 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002321 }
2322 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002323 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002325 max_char = ucs4lib_find_max_char(u, u + len);
2326 if (max_char >= 0x10000)
2327 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002328 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002330 if (copy != NULL)
2331 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002332 Py_DECREF(unicode);
2333 *p_unicode = copy;
2334}
2335
Victor Stinner034f6cf2011-09-30 02:26:44 +02002336PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002337_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002338{
Victor Stinner87af4f22011-11-21 23:03:47 +01002339 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002340 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002341
Victor Stinner034f6cf2011-09-30 02:26:44 +02002342 if (!PyUnicode_Check(unicode)) {
2343 PyErr_BadInternalCall();
2344 return NULL;
2345 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002346 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002347 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002348
Victor Stinner87af4f22011-11-21 23:03:47 +01002349 length = PyUnicode_GET_LENGTH(unicode);
2350 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002351 if (!copy)
2352 return NULL;
2353 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2354
Christian Heimesf051e432016-09-13 20:22:02 +02002355 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002356 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002357 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002358 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002359}
2360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002361
Victor Stinnerbc603d12011-10-02 01:00:40 +02002362/* Widen Unicode objects to larger buffers. Don't write terminating null
2363 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002364
2365void*
2366_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2367{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002368 Py_ssize_t len;
2369 void *result;
2370 unsigned int skind;
2371
Benjamin Petersonbac79492012-01-14 13:34:47 -05002372 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002373 return NULL;
2374
2375 len = PyUnicode_GET_LENGTH(s);
2376 skind = PyUnicode_KIND(s);
2377 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002378 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 return NULL;
2380 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002381 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002383 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002384 if (!result)
2385 return PyErr_NoMemory();
2386 assert(skind == PyUnicode_1BYTE_KIND);
2387 _PyUnicode_CONVERT_BYTES(
2388 Py_UCS1, Py_UCS2,
2389 PyUnicode_1BYTE_DATA(s),
2390 PyUnicode_1BYTE_DATA(s) + len,
2391 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002392 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002393 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002394 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002395 if (!result)
2396 return PyErr_NoMemory();
2397 if (skind == PyUnicode_2BYTE_KIND) {
2398 _PyUnicode_CONVERT_BYTES(
2399 Py_UCS2, Py_UCS4,
2400 PyUnicode_2BYTE_DATA(s),
2401 PyUnicode_2BYTE_DATA(s) + len,
2402 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002404 else {
2405 assert(skind == PyUnicode_1BYTE_KIND);
2406 _PyUnicode_CONVERT_BYTES(
2407 Py_UCS1, Py_UCS4,
2408 PyUnicode_1BYTE_DATA(s),
2409 PyUnicode_1BYTE_DATA(s) + len,
2410 result);
2411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002413 default:
2414 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002415 }
Victor Stinner01698042011-10-04 00:04:26 +02002416 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 return NULL;
2418}
2419
2420static Py_UCS4*
2421as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2422 int copy_null)
2423{
2424 int kind;
2425 void *data;
2426 Py_ssize_t len, targetlen;
2427 if (PyUnicode_READY(string) == -1)
2428 return NULL;
2429 kind = PyUnicode_KIND(string);
2430 data = PyUnicode_DATA(string);
2431 len = PyUnicode_GET_LENGTH(string);
2432 targetlen = len;
2433 if (copy_null)
2434 targetlen++;
2435 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002436 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002437 if (!target) {
2438 PyErr_NoMemory();
2439 return NULL;
2440 }
2441 }
2442 else {
2443 if (targetsize < targetlen) {
2444 PyErr_Format(PyExc_SystemError,
2445 "string is longer than the buffer");
2446 if (copy_null && 0 < targetsize)
2447 target[0] = 0;
2448 return NULL;
2449 }
2450 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002451 if (kind == PyUnicode_1BYTE_KIND) {
2452 Py_UCS1 *start = (Py_UCS1 *) data;
2453 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002455 else if (kind == PyUnicode_2BYTE_KIND) {
2456 Py_UCS2 *start = (Py_UCS2 *) data;
2457 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2458 }
2459 else {
2460 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002461 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002463 if (copy_null)
2464 target[len] = 0;
2465 return target;
2466}
2467
2468Py_UCS4*
2469PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2470 int copy_null)
2471{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002472 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002473 PyErr_BadInternalCall();
2474 return NULL;
2475 }
2476 return as_ucs4(string, target, targetsize, copy_null);
2477}
2478
2479Py_UCS4*
2480PyUnicode_AsUCS4Copy(PyObject *string)
2481{
2482 return as_ucs4(string, NULL, 0, 1);
2483}
2484
2485#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002486
Alexander Belopolsky40018472011-02-26 01:02:56 +00002487PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002488PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002489{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002490 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002491 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002492 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002493 PyErr_BadInternalCall();
2494 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002495 }
2496
Martin v. Löwis790465f2008-04-05 20:41:37 +00002497 if (size == -1) {
2498 size = wcslen(w);
2499 }
2500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002501 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002502}
2503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002505
Victor Stinner15a11362012-10-06 23:48:20 +02002506/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002507 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2508 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2509#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002510
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002511static int
2512unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2513 Py_ssize_t width, Py_ssize_t precision)
2514{
2515 Py_ssize_t length, fill, arglen;
2516 Py_UCS4 maxchar;
2517
2518 if (PyUnicode_READY(str) == -1)
2519 return -1;
2520
2521 length = PyUnicode_GET_LENGTH(str);
2522 if ((precision == -1 || precision >= length)
2523 && width <= length)
2524 return _PyUnicodeWriter_WriteStr(writer, str);
2525
2526 if (precision != -1)
2527 length = Py_MIN(precision, length);
2528
2529 arglen = Py_MAX(length, width);
2530 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2531 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2532 else
2533 maxchar = writer->maxchar;
2534
2535 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2536 return -1;
2537
2538 if (width > length) {
2539 fill = width - length;
2540 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2541 return -1;
2542 writer->pos += fill;
2543 }
2544
2545 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2546 str, 0, length);
2547 writer->pos += length;
2548 return 0;
2549}
2550
2551static int
2552unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2553 Py_ssize_t width, Py_ssize_t precision)
2554{
2555 /* UTF-8 */
2556 Py_ssize_t length;
2557 PyObject *unicode;
2558 int res;
2559
2560 length = strlen(str);
2561 if (precision != -1)
2562 length = Py_MIN(length, precision);
2563 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2564 if (unicode == NULL)
2565 return -1;
2566
2567 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2568 Py_DECREF(unicode);
2569 return res;
2570}
2571
Victor Stinner96865452011-03-01 23:44:09 +00002572static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002573unicode_fromformat_arg(_PyUnicodeWriter *writer,
2574 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002575{
Victor Stinnere215d962012-10-06 23:03:36 +02002576 const char *p;
2577 Py_ssize_t len;
2578 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 Py_ssize_t width;
2580 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002581 int longflag;
2582 int longlongflag;
2583 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002584 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002585
2586 p = f;
2587 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002588 zeropad = 0;
2589 if (*f == '0') {
2590 zeropad = 1;
2591 f++;
2592 }
Victor Stinner96865452011-03-01 23:44:09 +00002593
2594 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 width = -1;
2596 if (Py_ISDIGIT((unsigned)*f)) {
2597 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002598 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002599 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002600 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002601 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002602 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002603 return NULL;
2604 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002605 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002606 f++;
2607 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002608 }
2609 precision = -1;
2610 if (*f == '.') {
2611 f++;
2612 if (Py_ISDIGIT((unsigned)*f)) {
2613 precision = (*f - '0');
2614 f++;
2615 while (Py_ISDIGIT((unsigned)*f)) {
2616 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2617 PyErr_SetString(PyExc_ValueError,
2618 "precision too big");
2619 return NULL;
2620 }
2621 precision = (precision * 10) + (*f - '0');
2622 f++;
2623 }
2624 }
Victor Stinner96865452011-03-01 23:44:09 +00002625 if (*f == '%') {
2626 /* "%.3%s" => f points to "3" */
2627 f--;
2628 }
2629 }
2630 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002631 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002632 f--;
2633 }
Victor Stinner96865452011-03-01 23:44:09 +00002634
2635 /* Handle %ld, %lu, %lld and %llu. */
2636 longflag = 0;
2637 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002638 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002639 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002640 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002641 longflag = 1;
2642 ++f;
2643 }
Victor Stinner96865452011-03-01 23:44:09 +00002644 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002645 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002646 longlongflag = 1;
2647 f += 2;
2648 }
Victor Stinner96865452011-03-01 23:44:09 +00002649 }
2650 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002651 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002652 size_tflag = 1;
2653 ++f;
2654 }
Victor Stinnere215d962012-10-06 23:03:36 +02002655
2656 if (f[1] == '\0')
2657 writer->overallocate = 0;
2658
2659 switch (*f) {
2660 case 'c':
2661 {
2662 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002663 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002664 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002665 "character argument not in range(0x110000)");
2666 return NULL;
2667 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002668 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002669 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002670 break;
2671 }
2672
2673 case 'i':
2674 case 'd':
2675 case 'u':
2676 case 'x':
2677 {
2678 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002679 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002680 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002681
2682 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002683 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002684 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002685 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002686 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002687 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002688 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002689 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002691 va_arg(*vargs, size_t));
2692 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002693 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002694 va_arg(*vargs, unsigned int));
2695 }
2696 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002697 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002698 }
2699 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002700 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002701 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002702 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002703 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002704 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002705 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002706 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002707 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002708 va_arg(*vargs, Py_ssize_t));
2709 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002710 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002711 va_arg(*vargs, int));
2712 }
2713 assert(len >= 0);
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (precision < len)
2716 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002717
2718 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002719 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2720 return NULL;
2721
Victor Stinnere215d962012-10-06 23:03:36 +02002722 if (width > precision) {
2723 Py_UCS4 fillchar;
2724 fill = width - precision;
2725 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002726 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2727 return NULL;
2728 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002729 }
Victor Stinner15a11362012-10-06 23:48:20 +02002730 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002731 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002732 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2733 return NULL;
2734 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002735 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002736
Victor Stinner4a587072013-11-19 12:54:53 +01002737 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2738 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002739 break;
2740 }
2741
2742 case 'p':
2743 {
2744 char number[MAX_LONG_LONG_CHARS];
2745
2746 len = sprintf(number, "%p", va_arg(*vargs, void*));
2747 assert(len >= 0);
2748
2749 /* %p is ill-defined: ensure leading 0x. */
2750 if (number[1] == 'X')
2751 number[1] = 'x';
2752 else if (number[1] != 'x') {
2753 memmove(number + 2, number,
2754 strlen(number) + 1);
2755 number[0] = '0';
2756 number[1] = 'x';
2757 len += 2;
2758 }
2759
Victor Stinner4a587072013-11-19 12:54:53 +01002760 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002761 return NULL;
2762 break;
2763 }
2764
2765 case 's':
2766 {
2767 /* UTF-8 */
2768 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002769 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002770 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002771 break;
2772 }
2773
2774 case 'U':
2775 {
2776 PyObject *obj = va_arg(*vargs, PyObject *);
2777 assert(obj && _PyUnicode_CHECK(obj));
2778
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002779 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002780 return NULL;
2781 break;
2782 }
2783
2784 case 'V':
2785 {
2786 PyObject *obj = va_arg(*vargs, PyObject *);
2787 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002788 if (obj) {
2789 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002790 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002791 return NULL;
2792 }
2793 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002794 assert(str != NULL);
2795 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002796 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002797 }
2798 break;
2799 }
2800
2801 case 'S':
2802 {
2803 PyObject *obj = va_arg(*vargs, PyObject *);
2804 PyObject *str;
2805 assert(obj);
2806 str = PyObject_Str(obj);
2807 if (!str)
2808 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002809 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002810 Py_DECREF(str);
2811 return NULL;
2812 }
2813 Py_DECREF(str);
2814 break;
2815 }
2816
2817 case 'R':
2818 {
2819 PyObject *obj = va_arg(*vargs, PyObject *);
2820 PyObject *repr;
2821 assert(obj);
2822 repr = PyObject_Repr(obj);
2823 if (!repr)
2824 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002825 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002826 Py_DECREF(repr);
2827 return NULL;
2828 }
2829 Py_DECREF(repr);
2830 break;
2831 }
2832
2833 case 'A':
2834 {
2835 PyObject *obj = va_arg(*vargs, PyObject *);
2836 PyObject *ascii;
2837 assert(obj);
2838 ascii = PyObject_ASCII(obj);
2839 if (!ascii)
2840 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002841 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002842 Py_DECREF(ascii);
2843 return NULL;
2844 }
2845 Py_DECREF(ascii);
2846 break;
2847 }
2848
2849 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002850 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002851 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002852 break;
2853
2854 default:
2855 /* if we stumble upon an unknown formatting code, copy the rest
2856 of the format string to the output string. (we cannot just
2857 skip the code, since there's no way to know what's in the
2858 argument list) */
2859 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002860 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002861 return NULL;
2862 f = p+len;
2863 return f;
2864 }
2865
2866 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002867 return f;
2868}
2869
Walter Dörwaldd2034312007-05-18 16:29:38 +00002870PyObject *
2871PyUnicode_FromFormatV(const char *format, va_list vargs)
2872{
Victor Stinnere215d962012-10-06 23:03:36 +02002873 va_list vargs2;
2874 const char *f;
2875 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002876
Victor Stinner8f674cc2013-04-17 23:02:17 +02002877 _PyUnicodeWriter_Init(&writer);
2878 writer.min_length = strlen(format) + 100;
2879 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002880
Benjamin Peterson0c212142016-09-20 20:39:33 -07002881 // Copy varags to be able to pass a reference to a subfunction.
2882 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002883
2884 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002885 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002886 f = unicode_fromformat_arg(&writer, f, &vargs2);
2887 if (f == NULL)
2888 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002890 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002891 const char *p;
2892 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002893
Victor Stinnere215d962012-10-06 23:03:36 +02002894 p = f;
2895 do
2896 {
2897 if ((unsigned char)*p > 127) {
2898 PyErr_Format(PyExc_ValueError,
2899 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2900 "string, got a non-ASCII byte: 0x%02x",
2901 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002902 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002903 }
2904 p++;
2905 }
2906 while (*p != '\0' && *p != '%');
2907 len = p - f;
2908
2909 if (*p == '\0')
2910 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002911
2912 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002913 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002914
2915 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002916 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002918 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002919 return _PyUnicodeWriter_Finish(&writer);
2920
2921 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002922 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002923 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002924 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925}
2926
Walter Dörwaldd2034312007-05-18 16:29:38 +00002927PyObject *
2928PyUnicode_FromFormat(const char *format, ...)
2929{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 PyObject* ret;
2931 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002932
2933#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002934 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002935#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002936 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002937#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 ret = PyUnicode_FromFormatV(format, vargs);
2939 va_end(vargs);
2940 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002941}
2942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002943#ifdef HAVE_WCHAR_H
2944
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2946 convert a Unicode object to a wide character string.
2947
Victor Stinnerd88d9832011-09-06 02:00:05 +02002948 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002949 character) required to convert the unicode object. Ignore size argument.
2950
Victor Stinnerd88d9832011-09-06 02:00:05 +02002951 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002952 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002953 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002954static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002955unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002956 wchar_t *w,
2957 Py_ssize_t size)
2958{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002959 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002960 const wchar_t *wstr;
2961
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002962 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002963 if (wstr == NULL)
2964 return -1;
2965
Victor Stinner5593d8a2010-10-02 11:11:27 +00002966 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002967 if (size > res)
2968 size = res + 1;
2969 else
2970 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002971 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002972 return res;
2973 }
2974 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002975 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002976}
2977
2978Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002979PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 wchar_t *w,
2981 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982{
2983 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002984 PyErr_BadInternalCall();
2985 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002986 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002987 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002988}
2989
Victor Stinner137c34c2010-09-29 10:25:54 +00002990wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002991PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002992 Py_ssize_t *size)
2993{
2994 wchar_t* buffer;
2995 Py_ssize_t buflen;
2996
2997 if (unicode == NULL) {
2998 PyErr_BadInternalCall();
2999 return NULL;
3000 }
3001
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003002 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003003 if (buflen == -1)
3004 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003005 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003006 if (buffer == NULL) {
3007 PyErr_NoMemory();
3008 return NULL;
3009 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003010 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003011 if (buflen == -1) {
3012 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003013 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003014 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003015 if (size != NULL)
3016 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003017 return buffer;
3018}
3019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003020#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
3023PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003024{
Victor Stinner8faf8212011-12-08 22:14:11 +01003025 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyErr_SetString(PyExc_ValueError,
3027 "chr() arg not in range(0x110000)");
3028 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003029 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003030
Victor Stinner985a82a2014-01-03 12:53:47 +01003031 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003032}
3033
Alexander Belopolsky40018472011-02-26 01:02:56 +00003034PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003035PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003036{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003039 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003040 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003041 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 Py_INCREF(obj);
3043 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003044 }
3045 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 /* For a Unicode subtype that's not a Unicode object,
3047 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003048 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003049 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003050 PyErr_Format(PyExc_TypeError,
3051 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003052 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003053 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003054}
3055
Alexander Belopolsky40018472011-02-26 01:02:56 +00003056PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003057PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003058 const char *encoding,
3059 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003060{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003061 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003062 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003063
Guido van Rossumd57fd912000-03-10 22:53:23 +00003064 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003065 PyErr_BadInternalCall();
3066 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003067 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003068
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003069 /* Decoding bytes objects is the most common case and should be fast */
3070 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003071 if (PyBytes_GET_SIZE(obj) == 0)
3072 _Py_RETURN_UNICODE_EMPTY();
3073 v = PyUnicode_Decode(
3074 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3075 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003076 return v;
3077 }
3078
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003079 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003080 PyErr_SetString(PyExc_TypeError,
3081 "decoding str is not supported");
3082 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003083 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003084
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003085 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3086 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3087 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003088 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003089 Py_TYPE(obj)->tp_name);
3090 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003091 }
Tim Petersced69f82003-09-16 20:30:58 +00003092
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003093 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003094 PyBuffer_Release(&buffer);
3095 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003096 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003097
Serhiy Storchaka05997252013-01-26 12:14:02 +02003098 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003099 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003100 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003101}
3102
Victor Stinner942889a2016-09-05 15:40:10 -07003103/* Normalize an encoding name: C implementation of
3104 encodings.normalize_encoding(). Return 1 on success, or 0 on error (encoding
3105 is longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003106int
3107_Py_normalize_encoding(const char *encoding,
3108 char *lower,
3109 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003110{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003111 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003112 char *l;
3113 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003114 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003115
Victor Stinner942889a2016-09-05 15:40:10 -07003116 assert(encoding != NULL);
3117
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003118 e = encoding;
3119 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003120 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003121 punct = 0;
3122 while (1) {
3123 char c = *e;
3124 if (c == 0) {
3125 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003126 }
Victor Stinner942889a2016-09-05 15:40:10 -07003127
3128 if (Py_ISALNUM(c) || c == '.') {
3129 if (punct && l != lower) {
3130 if (l == l_end) {
3131 return 0;
3132 }
3133 *l++ = '_';
3134 }
3135 punct = 0;
3136
3137 if (l == l_end) {
3138 return 0;
3139 }
3140 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003141 }
3142 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003143 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003144 }
Victor Stinner942889a2016-09-05 15:40:10 -07003145
3146 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003147 }
3148 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003149 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003150}
3151
Alexander Belopolsky40018472011-02-26 01:02:56 +00003152PyObject *
3153PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003154 Py_ssize_t size,
3155 const char *encoding,
3156 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003157{
3158 PyObject *buffer = NULL, *unicode;
3159 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003160 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3161
3162 if (encoding == NULL) {
3163 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3164 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003165
Fred Drakee4315f52000-05-09 19:53:39 +00003166 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003167 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3168 char *lower = buflower;
3169
3170 /* Fast paths */
3171 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3172 lower += 3;
3173 if (*lower == '_') {
3174 /* Match "utf8" and "utf_8" */
3175 lower++;
3176 }
3177
3178 if (lower[0] == '8' && lower[1] == 0) {
3179 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3180 }
3181 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3182 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3183 }
3184 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3185 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3186 }
3187 }
3188 else {
3189 if (strcmp(lower, "ascii") == 0
3190 || strcmp(lower, "us_ascii") == 0) {
3191 return PyUnicode_DecodeASCII(s, size, errors);
3192 }
Steve Dowercc16be82016-09-08 10:35:16 -07003193 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003194 else if (strcmp(lower, "mbcs") == 0) {
3195 return PyUnicode_DecodeMBCS(s, size, errors);
3196 }
3197 #endif
3198 else if (strcmp(lower, "latin1") == 0
3199 || strcmp(lower, "latin_1") == 0
3200 || strcmp(lower, "iso_8859_1") == 0
3201 || strcmp(lower, "iso8859_1") == 0) {
3202 return PyUnicode_DecodeLatin1(s, size, errors);
3203 }
3204 }
Victor Stinner37296e82010-06-10 13:36:23 +00003205 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206
3207 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003208 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003209 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003210 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003211 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003212 if (buffer == NULL)
3213 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003214 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003215 if (unicode == NULL)
3216 goto onError;
3217 if (!PyUnicode_Check(unicode)) {
3218 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003219 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3220 "use codecs.decode() to decode to arbitrary types",
3221 encoding,
3222 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003223 Py_DECREF(unicode);
3224 goto onError;
3225 }
3226 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003227 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003228
Benjamin Peterson29060642009-01-31 22:14:21 +00003229 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003230 Py_XDECREF(buffer);
3231 return NULL;
3232}
3233
Alexander Belopolsky40018472011-02-26 01:02:56 +00003234PyObject *
3235PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003236 const char *encoding,
3237 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003238{
3239 PyObject *v;
3240
3241 if (!PyUnicode_Check(unicode)) {
3242 PyErr_BadArgument();
3243 goto onError;
3244 }
3245
3246 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003247 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003248
3249 /* Decode via the codec registry */
3250 v = PyCodec_Decode(unicode, encoding, errors);
3251 if (v == NULL)
3252 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003253 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003254
Benjamin Peterson29060642009-01-31 22:14:21 +00003255 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003256 return NULL;
3257}
3258
Alexander Belopolsky40018472011-02-26 01:02:56 +00003259PyObject *
3260PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003261 const char *encoding,
3262 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003263{
3264 PyObject *v;
3265
3266 if (!PyUnicode_Check(unicode)) {
3267 PyErr_BadArgument();
3268 goto onError;
3269 }
3270
3271 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003272 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003273
3274 /* Decode via the codec registry */
3275 v = PyCodec_Decode(unicode, encoding, errors);
3276 if (v == NULL)
3277 goto onError;
3278 if (!PyUnicode_Check(v)) {
3279 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003280 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3281 "use codecs.decode() to decode to arbitrary types",
3282 encoding,
3283 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003284 Py_DECREF(v);
3285 goto onError;
3286 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003287 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003288
Benjamin Peterson29060642009-01-31 22:14:21 +00003289 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003290 return NULL;
3291}
3292
Alexander Belopolsky40018472011-02-26 01:02:56 +00003293PyObject *
3294PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003295 Py_ssize_t size,
3296 const char *encoding,
3297 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003298{
3299 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003300
Guido van Rossumd57fd912000-03-10 22:53:23 +00003301 unicode = PyUnicode_FromUnicode(s, size);
3302 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003304 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3305 Py_DECREF(unicode);
3306 return v;
3307}
3308
Alexander Belopolsky40018472011-02-26 01:02:56 +00003309PyObject *
3310PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003311 const char *encoding,
3312 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003313{
3314 PyObject *v;
3315
3316 if (!PyUnicode_Check(unicode)) {
3317 PyErr_BadArgument();
3318 goto onError;
3319 }
3320
3321 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003322 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003323
3324 /* Encode via the codec registry */
3325 v = PyCodec_Encode(unicode, encoding, errors);
3326 if (v == NULL)
3327 goto onError;
3328 return v;
3329
Benjamin Peterson29060642009-01-31 22:14:21 +00003330 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003331 return NULL;
3332}
3333
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003334static size_t
3335wcstombs_errorpos(const wchar_t *wstr)
3336{
3337 size_t len;
3338#if SIZEOF_WCHAR_T == 2
3339 wchar_t buf[3];
3340#else
3341 wchar_t buf[2];
3342#endif
3343 char outbuf[MB_LEN_MAX];
3344 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003345
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003346#if SIZEOF_WCHAR_T == 2
3347 buf[2] = 0;
3348#else
3349 buf[1] = 0;
3350#endif
3351 start = wstr;
3352 while (*wstr != L'\0')
3353 {
3354 previous = wstr;
3355#if SIZEOF_WCHAR_T == 2
3356 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3357 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3358 {
3359 buf[0] = wstr[0];
3360 buf[1] = wstr[1];
3361 wstr += 2;
3362 }
3363 else {
3364 buf[0] = *wstr;
3365 buf[1] = 0;
3366 wstr++;
3367 }
3368#else
3369 buf[0] = *wstr;
3370 wstr++;
3371#endif
3372 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003373 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003375 }
3376
3377 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003378 return 0;
3379}
3380
Victor Stinner1b579672011-12-17 05:47:23 +01003381static int
3382locale_error_handler(const char *errors, int *surrogateescape)
3383{
Victor Stinner50149202015-09-22 00:26:54 +02003384 _Py_error_handler error_handler = get_error_handler(errors);
3385 switch (error_handler)
3386 {
3387 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003388 *surrogateescape = 0;
3389 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003390 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003391 *surrogateescape = 1;
3392 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003393 default:
3394 PyErr_Format(PyExc_ValueError,
3395 "only 'strict' and 'surrogateescape' error handlers "
3396 "are supported, not '%s'",
3397 errors);
3398 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003399 }
Victor Stinner1b579672011-12-17 05:47:23 +01003400}
3401
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003402PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003403PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003404{
3405 Py_ssize_t wlen, wlen2;
3406 wchar_t *wstr;
3407 PyObject *bytes = NULL;
3408 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003409 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410 PyObject *exc;
3411 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003412 int surrogateescape;
3413
3414 if (locale_error_handler(errors, &surrogateescape) < 0)
3415 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003416
3417 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3418 if (wstr == NULL)
3419 return NULL;
3420
3421 wlen2 = wcslen(wstr);
3422 if (wlen2 != wlen) {
3423 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003424 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003425 return NULL;
3426 }
3427
3428 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003429 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003430 char *str;
3431
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003432 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003433 if (str == NULL) {
3434 if (error_pos == (size_t)-1) {
3435 PyErr_NoMemory();
3436 PyMem_Free(wstr);
3437 return NULL;
3438 }
3439 else {
3440 goto encode_error;
3441 }
3442 }
3443 PyMem_Free(wstr);
3444
3445 bytes = PyBytes_FromString(str);
3446 PyMem_Free(str);
3447 }
3448 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003449 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003450 size_t len, len2;
3451
3452 len = wcstombs(NULL, wstr, 0);
3453 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003454 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003455 goto encode_error;
3456 }
3457
3458 bytes = PyBytes_FromStringAndSize(NULL, len);
3459 if (bytes == NULL) {
3460 PyMem_Free(wstr);
3461 return NULL;
3462 }
3463
3464 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3465 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003466 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003467 goto encode_error;
3468 }
3469 PyMem_Free(wstr);
3470 }
3471 return bytes;
3472
3473encode_error:
3474 errmsg = strerror(errno);
3475 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003476
3477 if (error_pos == (size_t)-1)
3478 error_pos = wcstombs_errorpos(wstr);
3479
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003480 PyMem_Free(wstr);
3481 Py_XDECREF(bytes);
3482
Victor Stinner2f197072011-12-17 07:08:30 +01003483 if (errmsg != NULL) {
3484 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003485 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003486 if (wstr != NULL) {
3487 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003488 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003489 } else
3490 errmsg = NULL;
3491 }
3492 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003493 reason = PyUnicode_FromString(
3494 "wcstombs() encountered an unencodable "
3495 "wide character");
3496 if (reason == NULL)
3497 return NULL;
3498
3499 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3500 "locale", unicode,
3501 (Py_ssize_t)error_pos,
3502 (Py_ssize_t)(error_pos+1),
3503 reason);
3504 Py_DECREF(reason);
3505 if (exc != NULL) {
3506 PyCodec_StrictErrors(exc);
3507 Py_XDECREF(exc);
3508 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003509 return NULL;
3510}
3511
Victor Stinnerad158722010-10-27 00:25:46 +00003512PyObject *
3513PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003514{
Steve Dowercc16be82016-09-08 10:35:16 -07003515#if defined(__APPLE__)
3516 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003517#else
Victor Stinner793b5312011-04-27 00:24:21 +02003518 PyInterpreterState *interp = PyThreadState_GET()->interp;
3519 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3520 cannot use it to encode and decode filenames before it is loaded. Load
3521 the Python codec requires to encode at least its own filename. Use the C
3522 version of the locale codec until the codec registry is initialized and
3523 the Python codec is loaded.
3524
3525 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3526 cannot only rely on it: check also interp->fscodec_initialized for
3527 subinterpreters. */
3528 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003529 return PyUnicode_AsEncodedString(unicode,
3530 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003531 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003532 }
3533 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003534 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003535 }
Victor Stinnerad158722010-10-27 00:25:46 +00003536#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003537}
3538
Alexander Belopolsky40018472011-02-26 01:02:56 +00003539PyObject *
3540PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003541 const char *encoding,
3542 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543{
3544 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003545 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003546
Guido van Rossumd57fd912000-03-10 22:53:23 +00003547 if (!PyUnicode_Check(unicode)) {
3548 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003549 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003550 }
Fred Drakee4315f52000-05-09 19:53:39 +00003551
Victor Stinner942889a2016-09-05 15:40:10 -07003552 if (encoding == NULL) {
3553 return _PyUnicode_AsUTF8String(unicode, errors);
3554 }
3555
Fred Drakee4315f52000-05-09 19:53:39 +00003556 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003557 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3558 char *lower = buflower;
3559
3560 /* Fast paths */
3561 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3562 lower += 3;
3563 if (*lower == '_') {
3564 /* Match "utf8" and "utf_8" */
3565 lower++;
3566 }
3567
3568 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003569 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003570 }
3571 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3572 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3573 }
3574 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3575 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3576 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003577 }
Victor Stinner942889a2016-09-05 15:40:10 -07003578 else {
3579 if (strcmp(lower, "ascii") == 0
3580 || strcmp(lower, "us_ascii") == 0) {
3581 return _PyUnicode_AsASCIIString(unicode, errors);
3582 }
Steve Dowercc16be82016-09-08 10:35:16 -07003583#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003584 else if (strcmp(lower, "mbcs") == 0) {
3585 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3586 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003587#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003588 else if (strcmp(lower, "latin1") == 0 ||
3589 strcmp(lower, "latin_1") == 0 ||
3590 strcmp(lower, "iso_8859_1") == 0 ||
3591 strcmp(lower, "iso8859_1") == 0) {
3592 return _PyUnicode_AsLatin1String(unicode, errors);
3593 }
3594 }
Victor Stinner37296e82010-06-10 13:36:23 +00003595 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003596
3597 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003598 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003599 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003600 return NULL;
3601
3602 /* The normal path */
3603 if (PyBytes_Check(v))
3604 return v;
3605
3606 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003607 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003608 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003609 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003610
3611 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003612 "encoder %s returned bytearray instead of bytes; "
3613 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003614 encoding);
3615 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003616 Py_DECREF(v);
3617 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003618 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003619
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003620 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3621 Py_DECREF(v);
3622 return b;
3623 }
3624
3625 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003626 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3627 "use codecs.encode() to encode to arbitrary types",
3628 encoding,
3629 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003630 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003631 return NULL;
3632}
3633
Alexander Belopolsky40018472011-02-26 01:02:56 +00003634PyObject *
3635PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003636 const char *encoding,
3637 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003638{
3639 PyObject *v;
3640
3641 if (!PyUnicode_Check(unicode)) {
3642 PyErr_BadArgument();
3643 goto onError;
3644 }
3645
3646 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003647 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003648
3649 /* Encode via the codec registry */
3650 v = PyCodec_Encode(unicode, encoding, errors);
3651 if (v == NULL)
3652 goto onError;
3653 if (!PyUnicode_Check(v)) {
3654 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003655 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3656 "use codecs.encode() to encode to arbitrary types",
3657 encoding,
3658 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003659 Py_DECREF(v);
3660 goto onError;
3661 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003662 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003663
Benjamin Peterson29060642009-01-31 22:14:21 +00003664 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003665 return NULL;
3666}
3667
Victor Stinner2f197072011-12-17 07:08:30 +01003668static size_t
3669mbstowcs_errorpos(const char *str, size_t len)
3670{
3671#ifdef HAVE_MBRTOWC
3672 const char *start = str;
3673 mbstate_t mbs;
3674 size_t converted;
3675 wchar_t ch;
3676
3677 memset(&mbs, 0, sizeof mbs);
3678 while (len)
3679 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003680 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003681 if (converted == 0)
3682 /* Reached end of string */
3683 break;
3684 if (converted == (size_t)-1 || converted == (size_t)-2) {
3685 /* Conversion error or incomplete character */
3686 return str - start;
3687 }
3688 else {
3689 str += converted;
3690 len -= converted;
3691 }
3692 }
3693 /* failed to find the undecodable byte sequence */
3694 return 0;
3695#endif
3696 return 0;
3697}
3698
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003699PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003700PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003701 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003702{
3703 wchar_t smallbuf[256];
3704 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3705 wchar_t *wstr;
3706 size_t wlen, wlen2;
3707 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003708 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003709 size_t error_pos;
3710 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003711 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3712 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003713
3714 if (locale_error_handler(errors, &surrogateescape) < 0)
3715 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003716
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003717 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3718 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003719 return NULL;
3720 }
3721
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003722 if (surrogateescape) {
3723 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003724 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003725 if (wstr == NULL) {
3726 if (wlen == (size_t)-1)
3727 PyErr_NoMemory();
3728 else
3729 PyErr_SetFromErrno(PyExc_OSError);
3730 return NULL;
3731 }
3732
3733 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003734 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003735 }
3736 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003737 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003738#ifndef HAVE_BROKEN_MBSTOWCS
3739 wlen = mbstowcs(NULL, str, 0);
3740#else
3741 wlen = len;
3742#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003743 if (wlen == (size_t)-1)
3744 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003745 if (wlen+1 <= smallbuf_len) {
3746 wstr = smallbuf;
3747 }
3748 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003749 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003750 if (!wstr)
3751 return PyErr_NoMemory();
3752 }
3753
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003754 wlen2 = mbstowcs(wstr, str, wlen+1);
3755 if (wlen2 == (size_t)-1) {
3756 if (wstr != smallbuf)
3757 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003758 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003759 }
3760#ifdef HAVE_BROKEN_MBSTOWCS
3761 assert(wlen2 == wlen);
3762#endif
3763 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3764 if (wstr != smallbuf)
3765 PyMem_Free(wstr);
3766 }
3767 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003768
3769decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003770 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003771 errmsg = strerror(errno);
3772 assert(errmsg != NULL);
3773
3774 error_pos = mbstowcs_errorpos(str, len);
3775 if (errmsg != NULL) {
3776 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003777 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003778 if (wstr != NULL) {
3779 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003780 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003781 }
Victor Stinner2f197072011-12-17 07:08:30 +01003782 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003783 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003784 reason = PyUnicode_FromString(
3785 "mbstowcs() encountered an invalid multibyte sequence");
3786 if (reason == NULL)
3787 return NULL;
3788
3789 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3790 "locale", str, len,
3791 (Py_ssize_t)error_pos,
3792 (Py_ssize_t)(error_pos+1),
3793 reason);
3794 Py_DECREF(reason);
3795 if (exc != NULL) {
3796 PyCodec_StrictErrors(exc);
3797 Py_XDECREF(exc);
3798 }
3799 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003800}
3801
3802PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003803PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003804{
3805 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003806 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003807}
3808
3809
3810PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003811PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003812 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003813 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3814}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003815
Christian Heimes5894ba72007-11-04 11:43:14 +00003816PyObject*
3817PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3818{
Steve Dowercc16be82016-09-08 10:35:16 -07003819#if defined(__APPLE__)
3820 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003821#else
Victor Stinner793b5312011-04-27 00:24:21 +02003822 PyInterpreterState *interp = PyThreadState_GET()->interp;
3823 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3824 cannot use it to encode and decode filenames before it is loaded. Load
3825 the Python codec requires to encode at least its own filename. Use the C
3826 version of the locale codec until the codec registry is initialized and
3827 the Python codec is loaded.
3828
3829 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3830 cannot only rely on it: check also interp->fscodec_initialized for
3831 subinterpreters. */
3832 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dowercc16be82016-09-08 10:35:16 -07003833 PyObject *res = PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003834 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003835 Py_FileSystemDefaultEncodeErrors);
3836#ifdef MS_WINDOWS
3837 if (!res && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
3838 PyObject *exc, *val, *tb;
3839 PyErr_Fetch(&exc, &val, &tb);
3840 PyErr_Format(PyExc_RuntimeError,
3841 "filesystem path bytes were not correctly encoded with '%s'. " \
3842 "Please report this at http://bugs.python.org/issue27781",
3843 Py_FileSystemDefaultEncoding);
3844 _PyErr_ChainExceptions(exc, val, tb);
3845 }
3846#endif
3847 return res;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003848 }
3849 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003850 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003851 }
Victor Stinnerad158722010-10-27 00:25:46 +00003852#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003853}
3854
Martin v. Löwis011e8422009-05-05 04:43:17 +00003855
3856int
3857PyUnicode_FSConverter(PyObject* arg, void* addr)
3858{
Brett Cannonec6ce872016-09-06 15:50:29 -07003859 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003860 PyObject *output = NULL;
3861 Py_ssize_t size;
3862 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003863 if (arg == NULL) {
3864 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003865 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003866 return 1;
3867 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003868 path = PyOS_FSPath(arg);
3869 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003870 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003871 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003872 if (PyBytes_Check(path)) {
3873 output = path;
3874 }
3875 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3876 output = PyUnicode_EncodeFSDefault(path);
3877 Py_DECREF(path);
3878 if (!output) {
3879 return 0;
3880 }
3881 assert(PyBytes_Check(output));
3882 }
3883
Victor Stinner0ea2a462010-04-30 00:22:08 +00003884 size = PyBytes_GET_SIZE(output);
3885 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003886 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003887 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003888 Py_DECREF(output);
3889 return 0;
3890 }
3891 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003892 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003893}
3894
3895
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003896int
3897PyUnicode_FSDecoder(PyObject* arg, void* addr)
3898{
Brett Cannona5711202016-09-06 19:36:01 -07003899 int is_buffer = 0;
3900 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003901 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003902 if (arg == NULL) {
3903 Py_DECREF(*(PyObject**)addr);
3904 return 1;
3905 }
Brett Cannona5711202016-09-06 19:36:01 -07003906
3907 is_buffer = PyObject_CheckBuffer(arg);
3908 if (!is_buffer) {
3909 path = PyOS_FSPath(arg);
3910 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003911 return 0;
3912 }
Brett Cannona5711202016-09-06 19:36:01 -07003913 }
3914 else {
3915 path = arg;
3916 Py_INCREF(arg);
3917 }
3918
3919 if (PyUnicode_Check(path)) {
3920 if (PyUnicode_READY(path) == -1) {
3921 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003922 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003923 }
3924 output = path;
3925 }
3926 else if (PyBytes_Check(path) || is_buffer) {
3927 PyObject *path_bytes = NULL;
3928
3929 if (!PyBytes_Check(path) &&
3930 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3931 "path should be string, bytes, or os.PathLike, not %.200s",
3932 Py_TYPE(arg)->tp_name)) {
3933 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003934 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003935 }
3936 path_bytes = PyBytes_FromObject(path);
3937 Py_DECREF(path);
3938 if (!path_bytes) {
3939 return 0;
3940 }
3941 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3942 PyBytes_GET_SIZE(path_bytes));
3943 Py_DECREF(path_bytes);
3944 if (!output) {
3945 return 0;
3946 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003947 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003948 else {
3949 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003950 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003951 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003952 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003953 return 0;
3954 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003955 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003956 Py_DECREF(output);
3957 return 0;
3958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003960 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003961 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003962 Py_DECREF(output);
3963 return 0;
3964 }
3965 *(PyObject**)addr = output;
3966 return Py_CLEANUP_SUPPORTED;
3967}
3968
3969
Martin v. Löwis5b222132007-06-10 09:51:05 +00003970char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003972{
Christian Heimesf3863112007-11-22 07:46:41 +00003973 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003975 if (!PyUnicode_Check(unicode)) {
3976 PyErr_BadArgument();
3977 return NULL;
3978 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003979 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003980 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003982 if (PyUnicode_UTF8(unicode) == NULL) {
3983 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003984 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985 if (bytes == NULL)
3986 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003987 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3988 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003989 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990 Py_DECREF(bytes);
3991 return NULL;
3992 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003993 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003994 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003995 PyBytes_AS_STRING(bytes),
3996 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003997 Py_DECREF(bytes);
3998 }
3999
4000 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004001 *psize = PyUnicode_UTF8_LENGTH(unicode);
4002 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004003}
4004
4005char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004006PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4009}
4010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011Py_UNICODE *
4012PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004014 const unsigned char *one_byte;
4015#if SIZEOF_WCHAR_T == 4
4016 const Py_UCS2 *two_bytes;
4017#else
4018 const Py_UCS4 *four_bytes;
4019 const Py_UCS4 *ucs4_end;
4020 Py_ssize_t num_surrogates;
4021#endif
4022 wchar_t *w;
4023 wchar_t *wchar_end;
4024
4025 if (!PyUnicode_Check(unicode)) {
4026 PyErr_BadArgument();
4027 return NULL;
4028 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004029 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004030 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004031 assert(_PyUnicode_KIND(unicode) != 0);
4032 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004033
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004034 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004035#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004036 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4037 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 num_surrogates = 0;
4039
4040 for (; four_bytes < ucs4_end; ++four_bytes) {
4041 if (*four_bytes > 0xFFFF)
4042 ++num_surrogates;
4043 }
4044
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004045 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4046 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4047 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004048 PyErr_NoMemory();
4049 return NULL;
4050 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004051 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004053 w = _PyUnicode_WSTR(unicode);
4054 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4055 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004056 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4057 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004058 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004059 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004060 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4061 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004062 }
4063 else
4064 *w = *four_bytes;
4065
4066 if (w > wchar_end) {
4067 assert(0 && "Miscalculated string end");
4068 }
4069 }
4070 *w = 0;
4071#else
4072 /* sizeof(wchar_t) == 4 */
4073 Py_FatalError("Impossible unicode object state, wstr and str "
4074 "should share memory already.");
4075 return NULL;
4076#endif
4077 }
4078 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004079 if ((size_t)_PyUnicode_LENGTH(unicode) >
4080 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4081 PyErr_NoMemory();
4082 return NULL;
4083 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004084 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4085 (_PyUnicode_LENGTH(unicode) + 1));
4086 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087 PyErr_NoMemory();
4088 return NULL;
4089 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004090 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4091 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4092 w = _PyUnicode_WSTR(unicode);
4093 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004094
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004095 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4096 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097 for (; w < wchar_end; ++one_byte, ++w)
4098 *w = *one_byte;
4099 /* null-terminate the wstr */
4100 *w = 0;
4101 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004102 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004103#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004104 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004105 for (; w < wchar_end; ++two_bytes, ++w)
4106 *w = *two_bytes;
4107 /* null-terminate the wstr */
4108 *w = 0;
4109#else
4110 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004111 PyObject_FREE(_PyUnicode_WSTR(unicode));
4112 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004113 Py_FatalError("Impossible unicode object state, wstr "
4114 "and str should share memory already.");
4115 return NULL;
4116#endif
4117 }
4118 else {
4119 assert(0 && "This should never happen.");
4120 }
4121 }
4122 }
4123 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004124 *size = PyUnicode_WSTR_LENGTH(unicode);
4125 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004126}
4127
Alexander Belopolsky40018472011-02-26 01:02:56 +00004128Py_UNICODE *
4129PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004130{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004131 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004132}
4133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004134
Alexander Belopolsky40018472011-02-26 01:02:56 +00004135Py_ssize_t
4136PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004137{
4138 if (!PyUnicode_Check(unicode)) {
4139 PyErr_BadArgument();
4140 goto onError;
4141 }
4142 return PyUnicode_GET_SIZE(unicode);
4143
Benjamin Peterson29060642009-01-31 22:14:21 +00004144 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004145 return -1;
4146}
4147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004148Py_ssize_t
4149PyUnicode_GetLength(PyObject *unicode)
4150{
Victor Stinner07621332012-06-16 04:53:46 +02004151 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004152 PyErr_BadArgument();
4153 return -1;
4154 }
Victor Stinner07621332012-06-16 04:53:46 +02004155 if (PyUnicode_READY(unicode) == -1)
4156 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004157 return PyUnicode_GET_LENGTH(unicode);
4158}
4159
4160Py_UCS4
4161PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4162{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004163 void *data;
4164 int kind;
4165
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004166 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4167 PyErr_BadArgument();
4168 return (Py_UCS4)-1;
4169 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004170 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004171 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004172 return (Py_UCS4)-1;
4173 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004174 data = PyUnicode_DATA(unicode);
4175 kind = PyUnicode_KIND(unicode);
4176 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177}
4178
4179int
4180PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4181{
4182 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004183 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004184 return -1;
4185 }
Victor Stinner488fa492011-12-12 00:01:39 +01004186 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004187 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004188 PyErr_SetString(PyExc_IndexError, "string index out of range");
4189 return -1;
4190 }
Victor Stinner488fa492011-12-12 00:01:39 +01004191 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004192 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004193 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4194 PyErr_SetString(PyExc_ValueError, "character out of range");
4195 return -1;
4196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004197 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4198 index, ch);
4199 return 0;
4200}
4201
Alexander Belopolsky40018472011-02-26 01:02:56 +00004202const char *
4203PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004204{
Victor Stinner42cb4622010-09-01 19:39:01 +00004205 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004206}
4207
Victor Stinner554f3f02010-06-16 23:33:54 +00004208/* create or adjust a UnicodeDecodeError */
4209static void
4210make_decode_exception(PyObject **exceptionObject,
4211 const char *encoding,
4212 const char *input, Py_ssize_t length,
4213 Py_ssize_t startpos, Py_ssize_t endpos,
4214 const char *reason)
4215{
4216 if (*exceptionObject == NULL) {
4217 *exceptionObject = PyUnicodeDecodeError_Create(
4218 encoding, input, length, startpos, endpos, reason);
4219 }
4220 else {
4221 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4222 goto onError;
4223 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4224 goto onError;
4225 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4226 goto onError;
4227 }
4228 return;
4229
4230onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004231 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004232}
4233
Steve Dowercc16be82016-09-08 10:35:16 -07004234#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004235/* error handling callback helper:
4236 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004237 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004238 and adjust various state variables.
4239 return 0 on success, -1 on error
4240*/
4241
Alexander Belopolsky40018472011-02-26 01:02:56 +00004242static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004243unicode_decode_call_errorhandler_wchar(
4244 const char *errors, PyObject **errorHandler,
4245 const char *encoding, const char *reason,
4246 const char **input, const char **inend, Py_ssize_t *startinpos,
4247 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4248 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004249{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004250 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004251
4252 PyObject *restuple = NULL;
4253 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004254 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004255 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004256 Py_ssize_t requiredsize;
4257 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004258 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004259 wchar_t *repwstr;
4260 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004261
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004262 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4263 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004264
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004265 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004266 *errorHandler = PyCodec_LookupError(errors);
4267 if (*errorHandler == NULL)
4268 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004269 }
4270
Victor Stinner554f3f02010-06-16 23:33:54 +00004271 make_decode_exception(exceptionObject,
4272 encoding,
4273 *input, *inend - *input,
4274 *startinpos, *endinpos,
4275 reason);
4276 if (*exceptionObject == NULL)
4277 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004278
4279 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4280 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004281 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004282 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004283 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004284 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285 }
4286 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004287 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004288
4289 /* Copy back the bytes variables, which might have been modified by the
4290 callback */
4291 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4292 if (!inputobj)
4293 goto onError;
4294 if (!PyBytes_Check(inputobj)) {
4295 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4296 }
4297 *input = PyBytes_AS_STRING(inputobj);
4298 insize = PyBytes_GET_SIZE(inputobj);
4299 *inend = *input + insize;
4300 /* we can DECREF safely, as the exception has another reference,
4301 so the object won't go away. */
4302 Py_DECREF(inputobj);
4303
4304 if (newpos<0)
4305 newpos = insize+newpos;
4306 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004307 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004308 goto onError;
4309 }
4310
4311 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4312 if (repwstr == NULL)
4313 goto onError;
4314 /* need more space? (at least enough for what we
4315 have+the replacement+the rest of the string (starting
4316 at the new input position), so we won't have to check space
4317 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004318 requiredsize = *outpos;
4319 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4320 goto overflow;
4321 requiredsize += repwlen;
4322 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4323 goto overflow;
4324 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004326 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004327 requiredsize = 2*outsize;
4328 if (unicode_resize(output, requiredsize) < 0)
4329 goto onError;
4330 }
4331 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4332 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004333 *endinpos = newpos;
4334 *inptr = *input + newpos;
4335
4336 /* we made it! */
4337 Py_XDECREF(restuple);
4338 return 0;
4339
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004340 overflow:
4341 PyErr_SetString(PyExc_OverflowError,
4342 "decoded result is too long for a Python string");
4343
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004344 onError:
4345 Py_XDECREF(restuple);
4346 return -1;
4347}
Steve Dowercc16be82016-09-08 10:35:16 -07004348#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004349
4350static int
4351unicode_decode_call_errorhandler_writer(
4352 const char *errors, PyObject **errorHandler,
4353 const char *encoding, const char *reason,
4354 const char **input, const char **inend, Py_ssize_t *startinpos,
4355 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4356 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4357{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004358 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004359
4360 PyObject *restuple = NULL;
4361 PyObject *repunicode = NULL;
4362 Py_ssize_t insize;
4363 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004364 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004365 PyObject *inputobj = NULL;
4366
4367 if (*errorHandler == NULL) {
4368 *errorHandler = PyCodec_LookupError(errors);
4369 if (*errorHandler == NULL)
4370 goto onError;
4371 }
4372
4373 make_decode_exception(exceptionObject,
4374 encoding,
4375 *input, *inend - *input,
4376 *startinpos, *endinpos,
4377 reason);
4378 if (*exceptionObject == NULL)
4379 goto onError;
4380
4381 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4382 if (restuple == NULL)
4383 goto onError;
4384 if (!PyTuple_Check(restuple)) {
4385 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4386 goto onError;
4387 }
4388 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004389 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004390
4391 /* Copy back the bytes variables, which might have been modified by the
4392 callback */
4393 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4394 if (!inputobj)
4395 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004396 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004397 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004398 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004399 *input = PyBytes_AS_STRING(inputobj);
4400 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004401 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004402 /* we can DECREF safely, as the exception has another reference,
4403 so the object won't go away. */
4404 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004405
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004406 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004407 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004408 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004409 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004410 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004411 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004412
Victor Stinner8f674cc2013-04-17 23:02:17 +02004413 if (PyUnicode_READY(repunicode) < 0)
4414 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004415 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004416 if (replen > 1) {
4417 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004418 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004419 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4420 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4421 goto onError;
4422 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004423 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004424 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004426 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004427 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004428
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004429 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004430 Py_XDECREF(restuple);
4431 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004432
Benjamin Peterson29060642009-01-31 22:14:21 +00004433 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004434 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004435 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004436}
4437
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438/* --- UTF-7 Codec -------------------------------------------------------- */
4439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440/* See RFC2152 for details. We encode conservatively and decode liberally. */
4441
4442/* Three simple macros defining base-64. */
4443
4444/* Is c a base-64 character? */
4445
4446#define IS_BASE64(c) \
4447 (((c) >= 'A' && (c) <= 'Z') || \
4448 ((c) >= 'a' && (c) <= 'z') || \
4449 ((c) >= '0' && (c) <= '9') || \
4450 (c) == '+' || (c) == '/')
4451
4452/* given that c is a base-64 character, what is its base-64 value? */
4453
4454#define FROM_BASE64(c) \
4455 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4456 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4457 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4458 (c) == '+' ? 62 : 63)
4459
4460/* What is the base-64 character of the bottom 6 bits of n? */
4461
4462#define TO_BASE64(n) \
4463 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4464
4465/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4466 * decoded as itself. We are permissive on decoding; the only ASCII
4467 * byte not decoding to itself is the + which begins a base64
4468 * string. */
4469
4470#define DECODE_DIRECT(c) \
4471 ((c) <= 127 && (c) != '+')
4472
4473/* The UTF-7 encoder treats ASCII characters differently according to
4474 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4475 * the above). See RFC2152. This array identifies these different
4476 * sets:
4477 * 0 : "Set D"
4478 * alphanumeric and '(),-./:?
4479 * 1 : "Set O"
4480 * !"#$%&*;<=>@[]^_`{|}
4481 * 2 : "whitespace"
4482 * ht nl cr sp
4483 * 3 : special (must be base64 encoded)
4484 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4485 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486
Tim Petersced69f82003-09-16 20:30:58 +00004487static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004488char utf7_category[128] = {
4489/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4490 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4491/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4492 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4493/* sp ! " # $ % & ' ( ) * + , - . / */
4494 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4495/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4496 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4497/* @ A B C D E F G H I J K L M N O */
4498 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4499/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4500 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4501/* ` a b c d e f g h i j k l m n o */
4502 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4503/* p q r s t u v w x y z { | } ~ del */
4504 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505};
4506
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507/* ENCODE_DIRECT: this character should be encoded as itself. The
4508 * answer depends on whether we are encoding set O as itself, and also
4509 * on whether we are encoding whitespace as itself. RFC2152 makes it
4510 * clear that the answers to these questions vary between
4511 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004512
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513#define ENCODE_DIRECT(c, directO, directWS) \
4514 ((c) < 128 && (c) > 0 && \
4515 ((utf7_category[(c)] == 0) || \
4516 (directWS && (utf7_category[(c)] == 2)) || \
4517 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518
Alexander Belopolsky40018472011-02-26 01:02:56 +00004519PyObject *
4520PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004521 Py_ssize_t size,
4522 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004523{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004524 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4525}
4526
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527/* The decoder. The only state we preserve is our read position,
4528 * i.e. how many characters we have consumed. So if we end in the
4529 * middle of a shift sequence we have to back off the read position
4530 * and the output to the beginning of the sequence, otherwise we lose
4531 * all the shift state (seen bits, number of bits seen, high
4532 * surrogate). */
4533
Alexander Belopolsky40018472011-02-26 01:02:56 +00004534PyObject *
4535PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004536 Py_ssize_t size,
4537 const char *errors,
4538 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004539{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004540 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004541 Py_ssize_t startinpos;
4542 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004543 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004544 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545 const char *errmsg = "";
4546 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004547 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004548 unsigned int base64bits = 0;
4549 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004550 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004551 PyObject *errorHandler = NULL;
4552 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004553
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004554 if (size == 0) {
4555 if (consumed)
4556 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004557 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004558 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004560 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004561 _PyUnicodeWriter_Init(&writer);
4562 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004563
4564 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004565 e = s + size;
4566
4567 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004568 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004569 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004570 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004571
Antoine Pitrou244651a2009-05-04 18:56:13 +00004572 if (inShift) { /* in a base-64 section */
4573 if (IS_BASE64(ch)) { /* consume a base-64 character */
4574 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4575 base64bits += 6;
4576 s++;
4577 if (base64bits >= 16) {
4578 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004579 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 base64bits -= 16;
4581 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004582 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 if (surrogate) {
4584 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004585 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4586 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004587 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004588 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004589 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004590 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004591 }
4592 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004593 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004594 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004595 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 }
4597 }
Victor Stinner551ac952011-11-29 22:58:13 +01004598 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 /* first surrogate */
4600 surrogate = outCh;
4601 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004603 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004604 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 }
4606 }
4607 }
4608 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004609 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004610 if (base64bits > 0) { /* left-over bits */
4611 if (base64bits >= 6) {
4612 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004613 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 errmsg = "partial character in shift sequence";
4615 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004616 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004617 else {
4618 /* Some bits remain; they should be zero */
4619 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004620 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004621 errmsg = "non-zero padding bits in shift sequence";
4622 goto utf7Error;
4623 }
4624 }
4625 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004626 if (surrogate && DECODE_DIRECT(ch)) {
4627 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4628 goto onError;
4629 }
4630 surrogate = 0;
4631 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004632 /* '-' is absorbed; other terminating
4633 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004634 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004635 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004636 }
4637 }
4638 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004639 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004640 s++; /* consume '+' */
4641 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004642 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004643 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004644 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004645 }
4646 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004647 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004648 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004649 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004650 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004651 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004652 }
4653 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004654 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004655 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004656 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004657 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004658 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004659 else {
4660 startinpos = s-starts;
4661 s++;
4662 errmsg = "unexpected special character";
4663 goto utf7Error;
4664 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004665 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004667 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004668 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004669 errors, &errorHandler,
4670 "utf7", errmsg,
4671 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004672 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004673 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004674 }
4675
Antoine Pitrou244651a2009-05-04 18:56:13 +00004676 /* end of string */
4677
4678 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4679 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004680 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681 if (surrogate ||
4682 (base64bits >= 6) ||
4683 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004684 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004685 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004686 errors, &errorHandler,
4687 "utf7", "unterminated shift sequence",
4688 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004689 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004690 goto onError;
4691 if (s < e)
4692 goto restart;
4693 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004694 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695
4696 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004697 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004698 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004699 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004700 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004701 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004702 writer.kind, writer.data, shiftOutStart);
4703 Py_XDECREF(errorHandler);
4704 Py_XDECREF(exc);
4705 _PyUnicodeWriter_Dealloc(&writer);
4706 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004707 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004708 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004709 }
4710 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004711 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004712 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004713 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004714
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004715 Py_XDECREF(errorHandler);
4716 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004717 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004718
Benjamin Peterson29060642009-01-31 22:14:21 +00004719 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004720 Py_XDECREF(errorHandler);
4721 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004722 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004723 return NULL;
4724}
4725
4726
Alexander Belopolsky40018472011-02-26 01:02:56 +00004727PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004728_PyUnicode_EncodeUTF7(PyObject *str,
4729 int base64SetO,
4730 int base64WhiteSpace,
4731 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004732{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004733 int kind;
4734 void *data;
4735 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004736 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004737 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004738 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004739 unsigned int base64bits = 0;
4740 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004741 char * out;
4742 char * start;
4743
Benjamin Petersonbac79492012-01-14 13:34:47 -05004744 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004745 return NULL;
4746 kind = PyUnicode_KIND(str);
4747 data = PyUnicode_DATA(str);
4748 len = PyUnicode_GET_LENGTH(str);
4749
4750 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004751 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004752
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004753 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004754 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004755 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004756 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004757 if (v == NULL)
4758 return NULL;
4759
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004760 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004761 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004762 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004763
Antoine Pitrou244651a2009-05-04 18:56:13 +00004764 if (inShift) {
4765 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4766 /* shifting out */
4767 if (base64bits) { /* output remaining bits */
4768 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4769 base64buffer = 0;
4770 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004771 }
4772 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004773 /* Characters not in the BASE64 set implicitly unshift the sequence
4774 so no '-' is required, except if the character is itself a '-' */
4775 if (IS_BASE64(ch) || ch == '-') {
4776 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004777 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004778 *out++ = (char) ch;
4779 }
4780 else {
4781 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004782 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004783 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004784 else { /* not in a shift sequence */
4785 if (ch == '+') {
4786 *out++ = '+';
4787 *out++ = '-';
4788 }
4789 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4790 *out++ = (char) ch;
4791 }
4792 else {
4793 *out++ = '+';
4794 inShift = 1;
4795 goto encode_char;
4796 }
4797 }
4798 continue;
4799encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004800 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004801 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004802
Antoine Pitrou244651a2009-05-04 18:56:13 +00004803 /* code first surrogate */
4804 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004805 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004806 while (base64bits >= 6) {
4807 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4808 base64bits -= 6;
4809 }
4810 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004811 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004812 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004813 base64bits += 16;
4814 base64buffer = (base64buffer << 16) | ch;
4815 while (base64bits >= 6) {
4816 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4817 base64bits -= 6;
4818 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004819 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004820 if (base64bits)
4821 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4822 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004823 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004824 if (_PyBytes_Resize(&v, out - start) < 0)
4825 return NULL;
4826 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004827}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004828PyObject *
4829PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4830 Py_ssize_t size,
4831 int base64SetO,
4832 int base64WhiteSpace,
4833 const char *errors)
4834{
4835 PyObject *result;
4836 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4837 if (tmp == NULL)
4838 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004839 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004840 base64WhiteSpace, errors);
4841 Py_DECREF(tmp);
4842 return result;
4843}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004844
Antoine Pitrou244651a2009-05-04 18:56:13 +00004845#undef IS_BASE64
4846#undef FROM_BASE64
4847#undef TO_BASE64
4848#undef DECODE_DIRECT
4849#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004850
Guido van Rossumd57fd912000-03-10 22:53:23 +00004851/* --- UTF-8 Codec -------------------------------------------------------- */
4852
Alexander Belopolsky40018472011-02-26 01:02:56 +00004853PyObject *
4854PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004855 Py_ssize_t size,
4856 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004857{
Walter Dörwald69652032004-09-07 20:24:22 +00004858 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4859}
4860
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004861#include "stringlib/asciilib.h"
4862#include "stringlib/codecs.h"
4863#include "stringlib/undef.h"
4864
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004865#include "stringlib/ucs1lib.h"
4866#include "stringlib/codecs.h"
4867#include "stringlib/undef.h"
4868
4869#include "stringlib/ucs2lib.h"
4870#include "stringlib/codecs.h"
4871#include "stringlib/undef.h"
4872
4873#include "stringlib/ucs4lib.h"
4874#include "stringlib/codecs.h"
4875#include "stringlib/undef.h"
4876
Antoine Pitrouab868312009-01-10 15:40:25 +00004877/* Mask to quickly check whether a C 'long' contains a
4878 non-ASCII, UTF8-encoded char. */
4879#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004880# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004881#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004882# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004883#else
4884# error C 'long' size should be either 4 or 8!
4885#endif
4886
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004887static Py_ssize_t
4888ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004890 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004891 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004892
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004893 /*
4894 * Issue #17237: m68k is a bit different from most architectures in
4895 * that objects do not use "natural alignment" - for example, int and
4896 * long are only aligned at 2-byte boundaries. Therefore the assert()
4897 * won't work; also, tests have shown that skipping the "optimised
4898 * version" will even speed up m68k.
4899 */
4900#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004902 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4903 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004904 /* Fast path, see in STRINGLIB(utf8_decode) for
4905 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004906 /* Help allocation */
4907 const char *_p = p;
4908 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004909 while (_p < aligned_end) {
4910 unsigned long value = *(const unsigned long *) _p;
4911 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004912 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004913 *((unsigned long *)q) = value;
4914 _p += SIZEOF_LONG;
4915 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004916 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004917 p = _p;
4918 while (p < end) {
4919 if ((unsigned char)*p & 0x80)
4920 break;
4921 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004922 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004923 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004924 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004925#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004926#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004927 while (p < end) {
4928 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4929 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004930 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004931 /* Help allocation */
4932 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004933 while (_p < aligned_end) {
4934 unsigned long value = *(unsigned long *) _p;
4935 if (value & ASCII_CHAR_MASK)
4936 break;
4937 _p += SIZEOF_LONG;
4938 }
4939 p = _p;
4940 if (_p == end)
4941 break;
4942 }
4943 if ((unsigned char)*p & 0x80)
4944 break;
4945 ++p;
4946 }
4947 memcpy(dest, start, p - start);
4948 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004949}
Antoine Pitrouab868312009-01-10 15:40:25 +00004950
Victor Stinner785938e2011-12-11 20:09:03 +01004951PyObject *
4952PyUnicode_DecodeUTF8Stateful(const char *s,
4953 Py_ssize_t size,
4954 const char *errors,
4955 Py_ssize_t *consumed)
4956{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004957 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004958 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960
4961 Py_ssize_t startinpos;
4962 Py_ssize_t endinpos;
4963 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004964 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004966 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004967
4968 if (size == 0) {
4969 if (consumed)
4970 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004971 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004972 }
4973
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4975 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004976 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977 *consumed = 1;
4978 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004979 }
4980
Victor Stinner8f674cc2013-04-17 23:02:17 +02004981 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004982 writer.min_length = size;
4983 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004985
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004986 writer.pos = ascii_decode(s, end, writer.data);
4987 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004988 while (s < end) {
4989 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004990 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004991
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004992 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004993 if (PyUnicode_IS_ASCII(writer.buffer))
4994 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004995 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004996 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004997 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004998 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999 } else {
5000 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005001 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 }
5003
5004 switch (ch) {
5005 case 0:
5006 if (s == end || consumed)
5007 goto End;
5008 errmsg = "unexpected end of data";
5009 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005010 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005011 break;
5012 case 1:
5013 errmsg = "invalid start byte";
5014 startinpos = s - starts;
5015 endinpos = startinpos + 1;
5016 break;
5017 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005018 case 3:
5019 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005020 errmsg = "invalid continuation byte";
5021 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005022 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 break;
5024 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005025 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005026 goto onError;
5027 continue;
5028 }
5029
Victor Stinner1d65d912015-10-05 13:43:50 +02005030 if (error_handler == _Py_ERROR_UNKNOWN)
5031 error_handler = get_error_handler(errors);
5032
5033 switch (error_handler) {
5034 case _Py_ERROR_IGNORE:
5035 s += (endinpos - startinpos);
5036 break;
5037
5038 case _Py_ERROR_REPLACE:
5039 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5040 goto onError;
5041 s += (endinpos - startinpos);
5042 break;
5043
5044 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005045 {
5046 Py_ssize_t i;
5047
Victor Stinner1d65d912015-10-05 13:43:50 +02005048 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5049 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005050 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005051 ch = (Py_UCS4)(unsigned char)(starts[i]);
5052 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5053 ch + 0xdc00);
5054 writer.pos++;
5055 }
5056 s += (endinpos - startinpos);
5057 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005058 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005059
5060 default:
5061 if (unicode_decode_call_errorhandler_writer(
5062 errors, &error_handler_obj,
5063 "utf-8", errmsg,
5064 &starts, &end, &startinpos, &endinpos, &exc, &s,
5065 &writer))
5066 goto onError;
5067 }
Victor Stinner785938e2011-12-11 20:09:03 +01005068 }
5069
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005070End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005071 if (consumed)
5072 *consumed = s - starts;
5073
Victor Stinner1d65d912015-10-05 13:43:50 +02005074 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005075 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005076 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077
5078onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005079 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005080 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005081 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005082 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005083}
5084
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005085#ifdef __APPLE__
5086
5087/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005088 used to decode the command line arguments on Mac OS X.
5089
5090 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005091 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005092
5093wchar_t*
5094_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5095{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005096 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005097 wchar_t *unicode;
5098 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005099
5100 /* Note: size will always be longer than the resulting Unicode
5101 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005102 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005103 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005104 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005105 if (!unicode)
5106 return NULL;
5107
5108 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005109 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005110 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005111 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005112 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005113#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005114 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005115#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005116 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005117#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005118 if (ch > 0xFF) {
5119#if SIZEOF_WCHAR_T == 4
5120 assert(0);
5121#else
5122 assert(Py_UNICODE_IS_SURROGATE(ch));
5123 /* compute and append the two surrogates: */
5124 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5125 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5126#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005127 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005128 else {
5129 if (!ch && s == e)
5130 break;
5131 /* surrogateescape */
5132 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5133 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005134 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005135 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005136 return unicode;
5137}
5138
5139#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005141/* Primary internal function which creates utf8 encoded bytes objects.
5142
5143 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005144 and allocate exactly as much space needed at the end. Else allocate the
5145 maximum possible needed (4 result bytes per Unicode character), and return
5146 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005147*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005148PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005149_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005150{
Victor Stinner6099a032011-12-18 14:22:26 +01005151 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005152 void *data;
5153 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005154
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005155 if (!PyUnicode_Check(unicode)) {
5156 PyErr_BadArgument();
5157 return NULL;
5158 }
5159
5160 if (PyUnicode_READY(unicode) == -1)
5161 return NULL;
5162
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005163 if (PyUnicode_UTF8(unicode))
5164 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5165 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005166
5167 kind = PyUnicode_KIND(unicode);
5168 data = PyUnicode_DATA(unicode);
5169 size = PyUnicode_GET_LENGTH(unicode);
5170
Benjamin Petersonead6b532011-12-20 17:23:42 -06005171 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005172 default:
5173 assert(0);
5174 case PyUnicode_1BYTE_KIND:
5175 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5176 assert(!PyUnicode_IS_ASCII(unicode));
5177 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5178 case PyUnicode_2BYTE_KIND:
5179 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5180 case PyUnicode_4BYTE_KIND:
5181 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005182 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183}
5184
Alexander Belopolsky40018472011-02-26 01:02:56 +00005185PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005186PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5187 Py_ssize_t size,
5188 const char *errors)
5189{
5190 PyObject *v, *unicode;
5191
5192 unicode = PyUnicode_FromUnicode(s, size);
5193 if (unicode == NULL)
5194 return NULL;
5195 v = _PyUnicode_AsUTF8String(unicode, errors);
5196 Py_DECREF(unicode);
5197 return v;
5198}
5199
5200PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005201PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005203 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005204}
5205
Walter Dörwald41980ca2007-08-16 21:55:45 +00005206/* --- UTF-32 Codec ------------------------------------------------------- */
5207
5208PyObject *
5209PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 Py_ssize_t size,
5211 const char *errors,
5212 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005213{
5214 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5215}
5216
5217PyObject *
5218PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005219 Py_ssize_t size,
5220 const char *errors,
5221 int *byteorder,
5222 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005223{
5224 const char *starts = s;
5225 Py_ssize_t startinpos;
5226 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005227 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005228 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005229 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005230 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005231 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005232 PyObject *errorHandler = NULL;
5233 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005234
Walter Dörwald41980ca2007-08-16 21:55:45 +00005235 q = (unsigned char *)s;
5236 e = q + size;
5237
5238 if (byteorder)
5239 bo = *byteorder;
5240
5241 /* Check for BOM marks (U+FEFF) in the input and adjust current
5242 byte order setting accordingly. In native mode, the leading BOM
5243 mark is skipped, in all other modes, it is copied to the output
5244 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005245 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005246 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005247 if (bom == 0x0000FEFF) {
5248 bo = -1;
5249 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005250 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005251 else if (bom == 0xFFFE0000) {
5252 bo = 1;
5253 q += 4;
5254 }
5255 if (byteorder)
5256 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257 }
5258
Victor Stinnere64322e2012-10-30 23:12:47 +01005259 if (q == e) {
5260 if (consumed)
5261 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005262 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005263 }
5264
Victor Stinnere64322e2012-10-30 23:12:47 +01005265#ifdef WORDS_BIGENDIAN
5266 le = bo < 0;
5267#else
5268 le = bo <= 0;
5269#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005270 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005271
Victor Stinner8f674cc2013-04-17 23:02:17 +02005272 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005273 writer.min_length = (e - q + 3) / 4;
5274 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005275 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005276
Victor Stinnere64322e2012-10-30 23:12:47 +01005277 while (1) {
5278 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005280
Victor Stinnere64322e2012-10-30 23:12:47 +01005281 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005282 enum PyUnicode_Kind kind = writer.kind;
5283 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005284 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005285 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 if (le) {
5287 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005288 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005289 if (ch > maxch)
5290 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005291 if (kind != PyUnicode_1BYTE_KIND &&
5292 Py_UNICODE_IS_SURROGATE(ch))
5293 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005294 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005295 q += 4;
5296 } while (q <= last);
5297 }
5298 else {
5299 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005300 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005301 if (ch > maxch)
5302 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005303 if (kind != PyUnicode_1BYTE_KIND &&
5304 Py_UNICODE_IS_SURROGATE(ch))
5305 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005306 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005307 q += 4;
5308 } while (q <= last);
5309 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005310 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005311 }
5312
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005313 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005314 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005315 startinpos = ((const char *)q) - starts;
5316 endinpos = startinpos + 4;
5317 }
5318 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005319 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005321 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005322 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005323 startinpos = ((const char *)q) - starts;
5324 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005326 else {
5327 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005328 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005329 goto onError;
5330 q += 4;
5331 continue;
5332 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005333 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005334 startinpos = ((const char *)q) - starts;
5335 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005337
5338 /* The remaining input chars are ignored if the callback
5339 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005340 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005341 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005342 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005344 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005345 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005346 }
5347
Walter Dörwald41980ca2007-08-16 21:55:45 +00005348 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005350
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351 Py_XDECREF(errorHandler);
5352 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005354
Benjamin Peterson29060642009-01-31 22:14:21 +00005355 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005356 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005357 Py_XDECREF(errorHandler);
5358 Py_XDECREF(exc);
5359 return NULL;
5360}
5361
5362PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005363_PyUnicode_EncodeUTF32(PyObject *str,
5364 const char *errors,
5365 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005366{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 enum PyUnicode_Kind kind;
5368 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005369 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005370 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005371 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005372#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005373 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005374#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005375 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005376#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005377 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005378 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005379 PyObject *errorHandler = NULL;
5380 PyObject *exc = NULL;
5381 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005382
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005383 if (!PyUnicode_Check(str)) {
5384 PyErr_BadArgument();
5385 return NULL;
5386 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005387 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005388 return NULL;
5389 kind = PyUnicode_KIND(str);
5390 data = PyUnicode_DATA(str);
5391 len = PyUnicode_GET_LENGTH(str);
5392
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005393 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005394 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005395 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005396 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005397 if (v == NULL)
5398 return NULL;
5399
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005400 /* output buffer is 4-bytes aligned */
5401 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005402 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005403 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005404 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005405 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005406 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005407
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005408 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005409 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005410 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005411 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005412 else
5413 encoding = "utf-32";
5414
5415 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005416 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5417 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005418 }
5419
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005420 pos = 0;
5421 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005422 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005423
5424 if (kind == PyUnicode_2BYTE_KIND) {
5425 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5426 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005428 else {
5429 assert(kind == PyUnicode_4BYTE_KIND);
5430 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5431 &out, native_ordering);
5432 }
5433 if (pos == len)
5434 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005435
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005436 rep = unicode_encode_call_errorhandler(
5437 errors, &errorHandler,
5438 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005439 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005440 if (!rep)
5441 goto error;
5442
5443 if (PyBytes_Check(rep)) {
5444 repsize = PyBytes_GET_SIZE(rep);
5445 if (repsize & 3) {
5446 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005447 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005448 "surrogates not allowed");
5449 goto error;
5450 }
5451 moreunits = repsize / 4;
5452 }
5453 else {
5454 assert(PyUnicode_Check(rep));
5455 if (PyUnicode_READY(rep) < 0)
5456 goto error;
5457 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5458 if (!PyUnicode_IS_ASCII(rep)) {
5459 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005460 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005461 "surrogates not allowed");
5462 goto error;
5463 }
5464 }
5465
5466 /* four bytes are reserved for each surrogate */
5467 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005468 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 Py_ssize_t morebytes = 4 * (moreunits - 1);
5470 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5471 /* integer overflow */
5472 PyErr_NoMemory();
5473 goto error;
5474 }
5475 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5476 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005477 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 }
5479
5480 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005481 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005482 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005483 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005484 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005485 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5486 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 }
5488
5489 Py_CLEAR(rep);
5490 }
5491
5492 /* Cut back to size actually needed. This is necessary for, for example,
5493 encoding of a string containing isolated surrogates and the 'ignore'
5494 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005495 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005496 if (nsize != PyBytes_GET_SIZE(v))
5497 _PyBytes_Resize(&v, nsize);
5498 Py_XDECREF(errorHandler);
5499 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005500 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005501 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005502 error:
5503 Py_XDECREF(rep);
5504 Py_XDECREF(errorHandler);
5505 Py_XDECREF(exc);
5506 Py_XDECREF(v);
5507 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005508}
5509
Alexander Belopolsky40018472011-02-26 01:02:56 +00005510PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005511PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5512 Py_ssize_t size,
5513 const char *errors,
5514 int byteorder)
5515{
5516 PyObject *result;
5517 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5518 if (tmp == NULL)
5519 return NULL;
5520 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5521 Py_DECREF(tmp);
5522 return result;
5523}
5524
5525PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005526PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005527{
Victor Stinnerb960b342011-11-20 19:12:52 +01005528 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005529}
5530
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531/* --- UTF-16 Codec ------------------------------------------------------- */
5532
Tim Peters772747b2001-08-09 22:21:55 +00005533PyObject *
5534PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005535 Py_ssize_t size,
5536 const char *errors,
5537 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005538{
Walter Dörwald69652032004-09-07 20:24:22 +00005539 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5540}
5541
5542PyObject *
5543PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005544 Py_ssize_t size,
5545 const char *errors,
5546 int *byteorder,
5547 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005548{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005549 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005550 Py_ssize_t startinpos;
5551 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005552 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005553 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005554 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005555 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005556 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005557 PyObject *errorHandler = NULL;
5558 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005559 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560
Tim Peters772747b2001-08-09 22:21:55 +00005561 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005562 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005563
5564 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005565 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005567 /* Check for BOM marks (U+FEFF) in the input and adjust current
5568 byte order setting accordingly. In native mode, the leading BOM
5569 mark is skipped, in all other modes, it is copied to the output
5570 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005571 if (bo == 0 && size >= 2) {
5572 const Py_UCS4 bom = (q[1] << 8) | q[0];
5573 if (bom == 0xFEFF) {
5574 q += 2;
5575 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005577 else if (bom == 0xFFFE) {
5578 q += 2;
5579 bo = 1;
5580 }
5581 if (byteorder)
5582 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005583 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005584
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 if (q == e) {
5586 if (consumed)
5587 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005588 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005589 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590
Christian Heimes743e0cd2012-10-17 23:52:17 +02005591#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005592 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005593 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005594#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005595 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005596 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005597#endif
Tim Peters772747b2001-08-09 22:21:55 +00005598
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 /* Note: size will always be longer than the resulting Unicode
5600 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005601 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005602 writer.min_length = (e - q + 1) / 2;
5603 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005604 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005605
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 while (1) {
5607 Py_UCS4 ch = 0;
5608 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005609 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005610 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005611 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005612 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005613 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005614 native_ordering);
5615 else
5616 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005617 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005618 native_ordering);
5619 } else if (kind == PyUnicode_2BYTE_KIND) {
5620 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005621 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005622 native_ordering);
5623 } else {
5624 assert(kind == PyUnicode_4BYTE_KIND);
5625 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005626 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005627 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005628 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005629 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005630
Antoine Pitrou63065d72012-05-15 23:48:04 +02005631 switch (ch)
5632 {
5633 case 0:
5634 /* remaining byte at the end? (size should be even) */
5635 if (q == e || consumed)
5636 goto End;
5637 errmsg = "truncated data";
5638 startinpos = ((const char *)q) - starts;
5639 endinpos = ((const char *)e) - starts;
5640 break;
5641 /* The remaining input chars are ignored if the callback
5642 chooses to skip the input */
5643 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005644 q -= 2;
5645 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005646 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005647 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005648 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005649 endinpos = ((const char *)e) - starts;
5650 break;
5651 case 2:
5652 errmsg = "illegal encoding";
5653 startinpos = ((const char *)q) - 2 - starts;
5654 endinpos = startinpos + 2;
5655 break;
5656 case 3:
5657 errmsg = "illegal UTF-16 surrogate";
5658 startinpos = ((const char *)q) - 4 - starts;
5659 endinpos = startinpos + 2;
5660 break;
5661 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005662 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005663 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 continue;
5665 }
5666
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005667 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005668 errors,
5669 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005670 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005671 &starts,
5672 (const char **)&e,
5673 &startinpos,
5674 &endinpos,
5675 &exc,
5676 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005677 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005678 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679 }
5680
Antoine Pitrou63065d72012-05-15 23:48:04 +02005681End:
Walter Dörwald69652032004-09-07 20:24:22 +00005682 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005684
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005685 Py_XDECREF(errorHandler);
5686 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005687 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005690 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005691 Py_XDECREF(errorHandler);
5692 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 return NULL;
5694}
5695
Tim Peters772747b2001-08-09 22:21:55 +00005696PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005697_PyUnicode_EncodeUTF16(PyObject *str,
5698 const char *errors,
5699 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005701 enum PyUnicode_Kind kind;
5702 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005703 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005704 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005705 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005706 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005707#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005708 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005709#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005710 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005711#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005712 const char *encoding;
5713 Py_ssize_t nsize, pos;
5714 PyObject *errorHandler = NULL;
5715 PyObject *exc = NULL;
5716 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005717
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005718 if (!PyUnicode_Check(str)) {
5719 PyErr_BadArgument();
5720 return NULL;
5721 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005722 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005723 return NULL;
5724 kind = PyUnicode_KIND(str);
5725 data = PyUnicode_DATA(str);
5726 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005727
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005728 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005729 if (kind == PyUnicode_4BYTE_KIND) {
5730 const Py_UCS4 *in = (const Py_UCS4 *)data;
5731 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005732 while (in < end) {
5733 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005734 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005735 }
5736 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005737 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005738 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005739 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005740 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005741 nsize = len + pairs + (byteorder == 0);
5742 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005743 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005745 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005747 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005748 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005749 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005750 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005751 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005752 }
5753 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005754 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005755 }
Tim Peters772747b2001-08-09 22:21:55 +00005756
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757 if (kind == PyUnicode_1BYTE_KIND) {
5758 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5759 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005760 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005761
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005762 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005763 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005764 }
5765 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005766 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005767 }
5768 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005769 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005770 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005771
5772 pos = 0;
5773 while (pos < len) {
5774 Py_ssize_t repsize, moreunits;
5775
5776 if (kind == PyUnicode_2BYTE_KIND) {
5777 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5778 &out, native_ordering);
5779 }
5780 else {
5781 assert(kind == PyUnicode_4BYTE_KIND);
5782 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5783 &out, native_ordering);
5784 }
5785 if (pos == len)
5786 break;
5787
5788 rep = unicode_encode_call_errorhandler(
5789 errors, &errorHandler,
5790 encoding, "surrogates not allowed",
5791 str, &exc, pos, pos + 1, &pos);
5792 if (!rep)
5793 goto error;
5794
5795 if (PyBytes_Check(rep)) {
5796 repsize = PyBytes_GET_SIZE(rep);
5797 if (repsize & 1) {
5798 raise_encode_exception(&exc, encoding,
5799 str, pos - 1, pos,
5800 "surrogates not allowed");
5801 goto error;
5802 }
5803 moreunits = repsize / 2;
5804 }
5805 else {
5806 assert(PyUnicode_Check(rep));
5807 if (PyUnicode_READY(rep) < 0)
5808 goto error;
5809 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5810 if (!PyUnicode_IS_ASCII(rep)) {
5811 raise_encode_exception(&exc, encoding,
5812 str, pos - 1, pos,
5813 "surrogates not allowed");
5814 goto error;
5815 }
5816 }
5817
5818 /* two bytes are reserved for each surrogate */
5819 if (moreunits > 1) {
5820 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5821 Py_ssize_t morebytes = 2 * (moreunits - 1);
5822 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5823 /* integer overflow */
5824 PyErr_NoMemory();
5825 goto error;
5826 }
5827 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5828 goto error;
5829 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5830 }
5831
5832 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005833 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005834 out += moreunits;
5835 } else /* rep is unicode */ {
5836 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5837 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5838 &out, native_ordering);
5839 }
5840
5841 Py_CLEAR(rep);
5842 }
5843
5844 /* Cut back to size actually needed. This is necessary for, for example,
5845 encoding of a string containing isolated surrogates and the 'ignore' handler
5846 is used. */
5847 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5848 if (nsize != PyBytes_GET_SIZE(v))
5849 _PyBytes_Resize(&v, nsize);
5850 Py_XDECREF(errorHandler);
5851 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005852 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005853 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005854 error:
5855 Py_XDECREF(rep);
5856 Py_XDECREF(errorHandler);
5857 Py_XDECREF(exc);
5858 Py_XDECREF(v);
5859 return NULL;
5860#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861}
5862
Alexander Belopolsky40018472011-02-26 01:02:56 +00005863PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005864PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5865 Py_ssize_t size,
5866 const char *errors,
5867 int byteorder)
5868{
5869 PyObject *result;
5870 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5871 if (tmp == NULL)
5872 return NULL;
5873 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5874 Py_DECREF(tmp);
5875 return result;
5876}
5877
5878PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005879PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005881 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882}
5883
5884/* --- Unicode Escape Codec ----------------------------------------------- */
5885
Fredrik Lundh06d12682001-01-24 07:59:11 +00005886static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005887
Alexander Belopolsky40018472011-02-26 01:02:56 +00005888PyObject *
5889PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005890 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005891 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005893 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005894 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005896 PyObject *errorHandler = NULL;
5897 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005898
Victor Stinner62ec3312016-09-06 17:04:34 -07005899 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005900 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005901 }
5902 /* Escaped strings will always be longer than the resulting
5903 Unicode string, so we start with size here and then reduce the
5904 length after conversion to the true value.
5905 (but if the error callback returns a long replacement string
5906 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005907 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005908 writer.min_length = size;
5909 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5910 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005911 }
5912
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 end = s + size;
5914 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005915 unsigned char c = (unsigned char) *s++;
5916 Py_UCS4 ch;
5917 int count;
5918 Py_ssize_t startinpos;
5919 Py_ssize_t endinpos;
5920 const char *message;
5921
5922#define WRITE_ASCII_CHAR(ch) \
5923 do { \
5924 assert(ch <= 127); \
5925 assert(writer.pos < writer.size); \
5926 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5927 } while(0)
5928
5929#define WRITE_CHAR(ch) \
5930 do { \
5931 if (ch <= writer.maxchar) { \
5932 assert(writer.pos < writer.size); \
5933 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5934 } \
5935 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5936 goto onError; \
5937 } \
5938 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939
5940 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005941 if (c != '\\') {
5942 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943 continue;
5944 }
5945
Victor Stinner62ec3312016-09-06 17:04:34 -07005946 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005947 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005948 if (s >= end) {
5949 message = "\\ at end of string";
5950 goto error;
5951 }
5952 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005953
Victor Stinner62ec3312016-09-06 17:04:34 -07005954 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005955 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005956
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005958 case '\n': continue;
5959 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5960 case '\'': WRITE_ASCII_CHAR('\''); continue;
5961 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5962 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005963 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5965 case 't': WRITE_ASCII_CHAR('\t'); continue;
5966 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5967 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005968 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005969 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005970 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005971 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974 case '0': case '1': case '2': case '3':
5975 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005976 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005977 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005978 ch = (ch<<3) + *s++ - '0';
5979 if (s < end && '0' <= *s && *s <= '7') {
5980 ch = (ch<<3) + *s++ - '0';
5981 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005983 WRITE_CHAR(ch);
5984 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 /* hex escapes */
5987 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005989 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005990 message = "truncated \\xXX escape";
5991 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005995 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005996 message = "truncated \\uXXXX escape";
5997 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006000 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006002 message = "truncated \\UXXXXXXXX escape";
6003 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006004 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006005 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006006 ch <<= 4;
6007 if (c >= '0' && c <= '9') {
6008 ch += c - '0';
6009 }
6010 else if (c >= 'a' && c <= 'f') {
6011 ch += c - ('a' - 10);
6012 }
6013 else if (c >= 'A' && c <= 'F') {
6014 ch += c - ('A' - 10);
6015 }
6016 else {
6017 break;
6018 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006019 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006020 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006021 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006022 }
6023
6024 /* when we get here, ch is a 32-bit unicode character */
6025 if (ch > MAX_UNICODE) {
6026 message = "illegal Unicode character";
6027 goto error;
6028 }
6029
6030 WRITE_CHAR(ch);
6031 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006032
Benjamin Peterson29060642009-01-31 22:14:21 +00006033 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006034 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 if (ucnhash_CAPI == NULL) {
6036 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006037 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6038 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006039 if (ucnhash_CAPI == NULL) {
6040 PyErr_SetString(
6041 PyExc_UnicodeError,
6042 "\\N escapes not supported (can't load unicodedata module)"
6043 );
6044 goto onError;
6045 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006047
6048 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 const char *start = ++s;
6051 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006052 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006053 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006055 namelen = s - start;
6056 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006058 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006059 ch = 0xffffffff; /* in case 'getcode' messes up */
6060 if (namelen <= INT_MAX &&
6061 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6062 &ch, 0)) {
6063 assert(ch <= MAX_UNICODE);
6064 WRITE_CHAR(ch);
6065 continue;
6066 }
6067 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006068 }
6069 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006070 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006071
6072 default:
R David Murray110b6fe2016-09-08 15:34:08 -04006073 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6074 "invalid escape sequence '\\%c'", c) < 0)
6075 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006076 WRITE_ASCII_CHAR('\\');
6077 WRITE_CHAR(c);
6078 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006080
6081 error:
6082 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006083 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006084 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006085 errors, &errorHandler,
6086 "unicodeescape", message,
6087 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006088 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006089 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006090 }
6091 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6092 goto onError;
6093 }
6094
6095#undef WRITE_ASCII_CHAR
6096#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006098
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006099 Py_XDECREF(errorHandler);
6100 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006101 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006102
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006104 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006105 Py_XDECREF(errorHandler);
6106 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 return NULL;
6108}
6109
6110/* Return a Unicode-Escape string version of the Unicode object.
6111
6112 If quotes is true, the string is enclosed in u"" or u'' quotes as
6113 appropriate.
6114
6115*/
6116
Alexander Belopolsky40018472011-02-26 01:02:56 +00006117PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006118PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006119{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006120 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006121 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006123 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006124 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006125 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126
Ezio Melottie7f90372012-10-05 03:33:31 +03006127 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006128 escape.
6129
Ezio Melottie7f90372012-10-05 03:33:31 +03006130 For UCS1 strings it's '\xxx', 4 bytes per source character.
6131 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6132 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006133 */
6134
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135 if (!PyUnicode_Check(unicode)) {
6136 PyErr_BadArgument();
6137 return NULL;
6138 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006140 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006141 }
Victor Stinner358af132015-10-12 22:36:57 +02006142
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006144 if (len == 0) {
6145 return PyBytes_FromStringAndSize(NULL, 0);
6146 }
6147
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006148 kind = PyUnicode_KIND(unicode);
6149 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006150 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6151 bytes, and 1 byte characters 4. */
6152 expandsize = kind * 2 + 2;
6153 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6154 return PyErr_NoMemory();
6155 }
6156 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6157 if (repr == NULL) {
6158 return NULL;
6159 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160
Victor Stinner62ec3312016-09-06 17:04:34 -07006161 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006163 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006164
Victor Stinner62ec3312016-09-06 17:04:34 -07006165 /* U+0000-U+00ff range */
6166 if (ch < 0x100) {
6167 if (ch >= ' ' && ch < 127) {
6168 if (ch != '\\') {
6169 /* Copy printable US ASCII as-is */
6170 *p++ = (char) ch;
6171 }
6172 /* Escape backslashes */
6173 else {
6174 *p++ = '\\';
6175 *p++ = '\\';
6176 }
6177 }
Victor Stinner358af132015-10-12 22:36:57 +02006178
Victor Stinner62ec3312016-09-06 17:04:34 -07006179 /* Map special whitespace to '\t', \n', '\r' */
6180 else if (ch == '\t') {
6181 *p++ = '\\';
6182 *p++ = 't';
6183 }
6184 else if (ch == '\n') {
6185 *p++ = '\\';
6186 *p++ = 'n';
6187 }
6188 else if (ch == '\r') {
6189 *p++ = '\\';
6190 *p++ = 'r';
6191 }
6192
6193 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6194 else {
6195 *p++ = '\\';
6196 *p++ = 'x';
6197 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6198 *p++ = Py_hexdigits[ch & 0x000F];
6199 }
Tim Petersced69f82003-09-16 20:30:58 +00006200 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006201 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6202 else if (ch < 0x10000) {
6203 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006204 *p++ = '\\';
6205 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006206 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6207 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6208 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6209 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006210 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006211 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6212 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006213
Victor Stinner62ec3312016-09-06 17:04:34 -07006214 /* Make sure that the first two digits are zero */
6215 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006216 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006217 *p++ = 'U';
6218 *p++ = '0';
6219 *p++ = '0';
6220 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6221 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6222 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6223 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6224 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6225 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006226 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228
Victor Stinner62ec3312016-09-06 17:04:34 -07006229 assert(p - PyBytes_AS_STRING(repr) > 0);
6230 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6231 return NULL;
6232 }
6233 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234}
6235
Alexander Belopolsky40018472011-02-26 01:02:56 +00006236PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6238 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006240 PyObject *result;
6241 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006242 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006244 }
6245
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006246 result = PyUnicode_AsUnicodeEscapeString(tmp);
6247 Py_DECREF(tmp);
6248 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249}
6250
6251/* --- Raw Unicode Escape Codec ------------------------------------------- */
6252
Alexander Belopolsky40018472011-02-26 01:02:56 +00006253PyObject *
6254PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006255 Py_ssize_t size,
6256 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006257{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006258 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006259 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006260 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006261 PyObject *errorHandler = NULL;
6262 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006263
Victor Stinner62ec3312016-09-06 17:04:34 -07006264 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006265 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006266 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006267
Guido van Rossumd57fd912000-03-10 22:53:23 +00006268 /* Escaped strings will always be longer than the resulting
6269 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006270 length after conversion to the true value. (But decoding error
6271 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006272 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006273 writer.min_length = size;
6274 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6275 goto onError;
6276 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006277
Guido van Rossumd57fd912000-03-10 22:53:23 +00006278 end = s + size;
6279 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006280 unsigned char c = (unsigned char) *s++;
6281 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006282 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006283 Py_ssize_t startinpos;
6284 Py_ssize_t endinpos;
6285 const char *message;
6286
6287#define WRITE_CHAR(ch) \
6288 do { \
6289 if (ch <= writer.maxchar) { \
6290 assert(writer.pos < writer.size); \
6291 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6292 } \
6293 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6294 goto onError; \
6295 } \
6296 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006297
Benjamin Peterson29060642009-01-31 22:14:21 +00006298 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006299 if (c != '\\' || s >= end) {
6300 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006301 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006302 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006303
Victor Stinner62ec3312016-09-06 17:04:34 -07006304 c = (unsigned char) *s++;
6305 if (c == 'u') {
6306 count = 4;
6307 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006308 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006309 else if (c == 'U') {
6310 count = 8;
6311 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006312 }
6313 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 assert(writer.pos < writer.size);
6315 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6316 WRITE_CHAR(c);
6317 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006318 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 startinpos = s - starts - 2;
6320
6321 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6322 for (ch = 0; count && s < end; ++s, --count) {
6323 c = (unsigned char)*s;
6324 ch <<= 4;
6325 if (c >= '0' && c <= '9') {
6326 ch += c - '0';
6327 }
6328 else if (c >= 'a' && c <= 'f') {
6329 ch += c - ('a' - 10);
6330 }
6331 else if (c >= 'A' && c <= 'F') {
6332 ch += c - ('A' - 10);
6333 }
6334 else {
6335 break;
6336 }
6337 }
6338 if (!count) {
6339 if (ch <= MAX_UNICODE) {
6340 WRITE_CHAR(ch);
6341 continue;
6342 }
6343 message = "\\Uxxxxxxxx out of range";
6344 }
6345
6346 endinpos = s-starts;
6347 writer.min_length = end - s + writer.pos;
6348 if (unicode_decode_call_errorhandler_writer(
6349 errors, &errorHandler,
6350 "rawunicodeescape", message,
6351 &starts, &end, &startinpos, &endinpos, &exc, &s,
6352 &writer)) {
6353 goto onError;
6354 }
6355 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6356 goto onError;
6357 }
6358
6359#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006360 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006361 Py_XDECREF(errorHandler);
6362 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006363 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006364
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006366 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367 Py_XDECREF(errorHandler);
6368 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006369 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006370
Guido van Rossumd57fd912000-03-10 22:53:23 +00006371}
6372
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006373
Alexander Belopolsky40018472011-02-26 01:02:56 +00006374PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006375PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376{
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006379 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006380 int kind;
6381 void *data;
6382 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006383
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006384 if (!PyUnicode_Check(unicode)) {
6385 PyErr_BadArgument();
6386 return NULL;
6387 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006388 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006389 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006390 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006391 kind = PyUnicode_KIND(unicode);
6392 data = PyUnicode_DATA(unicode);
6393 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006394 if (kind == PyUnicode_1BYTE_KIND) {
6395 return PyBytes_FromStringAndSize(data, len);
6396 }
Victor Stinner0e368262011-11-10 20:12:49 +01006397
Victor Stinner62ec3312016-09-06 17:04:34 -07006398 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6399 bytes, and 1 byte characters 4. */
6400 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006401
Victor Stinner62ec3312016-09-06 17:04:34 -07006402 if (len > PY_SSIZE_T_MAX / expandsize) {
6403 return PyErr_NoMemory();
6404 }
6405 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6406 if (repr == NULL) {
6407 return NULL;
6408 }
6409 if (len == 0) {
6410 return repr;
6411 }
6412
6413 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006414 for (pos = 0; pos < len; pos++) {
6415 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006416
Victor Stinner62ec3312016-09-06 17:04:34 -07006417 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6418 if (ch < 0x100) {
6419 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006420 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006421 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6422 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006423 *p++ = '\\';
6424 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006425 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6426 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6427 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6428 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006429 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006430 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6431 else {
6432 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6433 *p++ = '\\';
6434 *p++ = 'U';
6435 *p++ = '0';
6436 *p++ = '0';
6437 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6438 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6439 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6440 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6441 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6442 *p++ = Py_hexdigits[ch & 15];
6443 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006444 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006445
Victor Stinner62ec3312016-09-06 17:04:34 -07006446 assert(p > PyBytes_AS_STRING(repr));
6447 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6448 return NULL;
6449 }
6450 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006451}
6452
Alexander Belopolsky40018472011-02-26 01:02:56 +00006453PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006454PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6455 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006456{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006457 PyObject *result;
6458 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6459 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006460 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006461 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6462 Py_DECREF(tmp);
6463 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006464}
6465
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006466/* --- Unicode Internal Codec ------------------------------------------- */
6467
Alexander Belopolsky40018472011-02-26 01:02:56 +00006468PyObject *
6469_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006470 Py_ssize_t size,
6471 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006472{
6473 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006474 Py_ssize_t startinpos;
6475 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006476 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006477 const char *end;
6478 const char *reason;
6479 PyObject *errorHandler = NULL;
6480 PyObject *exc = NULL;
6481
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006482 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006483 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006484 1))
6485 return NULL;
6486
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006487 if (size == 0)
6488 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006489
Victor Stinner8f674cc2013-04-17 23:02:17 +02006490 _PyUnicodeWriter_Init(&writer);
6491 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6492 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006493 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006494 }
6495 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006496
Victor Stinner8f674cc2013-04-17 23:02:17 +02006497 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006498 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006499 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006500 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006501 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006502 endinpos = end-starts;
6503 reason = "truncated input";
6504 goto error;
6505 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006506 /* We copy the raw representation one byte at a time because the
6507 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006508 ((char *) &uch)[0] = s[0];
6509 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006510#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006511 ((char *) &uch)[2] = s[2];
6512 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006513#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006514 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006515#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006516 /* We have to sanity check the raw data, otherwise doom looms for
6517 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006518 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006519 endinpos = s - starts + Py_UNICODE_SIZE;
6520 reason = "illegal code point (> 0x10FFFF)";
6521 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006522 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006523#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006524 s += Py_UNICODE_SIZE;
6525#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006526 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006527 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006528 Py_UNICODE uch2;
6529 ((char *) &uch2)[0] = s[0];
6530 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006531 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532 {
Victor Stinner551ac952011-11-29 22:58:13 +01006533 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006534 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006535 }
6536 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006537#endif
6538
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006539 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006540 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006541 continue;
6542
6543 error:
6544 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006545 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006546 errors, &errorHandler,
6547 "unicode_internal", reason,
6548 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006549 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006550 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006551 }
6552
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006553 Py_XDECREF(errorHandler);
6554 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006555 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006556
Benjamin Peterson29060642009-01-31 22:14:21 +00006557 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006558 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006559 Py_XDECREF(errorHandler);
6560 Py_XDECREF(exc);
6561 return NULL;
6562}
6563
Guido van Rossumd57fd912000-03-10 22:53:23 +00006564/* --- Latin-1 Codec ------------------------------------------------------ */
6565
Alexander Belopolsky40018472011-02-26 01:02:56 +00006566PyObject *
6567PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006568 Py_ssize_t size,
6569 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006570{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006571 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006572 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006573}
6574
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006576static void
6577make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006578 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006579 PyObject *unicode,
6580 Py_ssize_t startpos, Py_ssize_t endpos,
6581 const char *reason)
6582{
6583 if (*exceptionObject == NULL) {
6584 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006585 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006586 encoding, unicode, startpos, endpos, reason);
6587 }
6588 else {
6589 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6590 goto onError;
6591 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6592 goto onError;
6593 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6594 goto onError;
6595 return;
6596 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006597 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006598 }
6599}
6600
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006602static void
6603raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006604 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006605 PyObject *unicode,
6606 Py_ssize_t startpos, Py_ssize_t endpos,
6607 const char *reason)
6608{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006609 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006610 encoding, unicode, startpos, endpos, reason);
6611 if (*exceptionObject != NULL)
6612 PyCodec_StrictErrors(*exceptionObject);
6613}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614
6615/* error handling callback helper:
6616 build arguments, call the callback and check the arguments,
6617 put the result into newpos and return the replacement string, which
6618 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006619static PyObject *
6620unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006621 PyObject **errorHandler,
6622 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006623 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006624 Py_ssize_t startpos, Py_ssize_t endpos,
6625 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006626{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006627 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006628 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006629 PyObject *restuple;
6630 PyObject *resunicode;
6631
6632 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006635 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 }
6637
Benjamin Petersonbac79492012-01-14 13:34:47 -05006638 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006639 return NULL;
6640 len = PyUnicode_GET_LENGTH(unicode);
6641
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006642 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646
6647 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006650 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006652 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 Py_DECREF(restuple);
6654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006656 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 &resunicode, newpos)) {
6658 Py_DECREF(restuple);
6659 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006661 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6662 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6663 Py_DECREF(restuple);
6664 return NULL;
6665 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006667 *newpos = len + *newpos;
6668 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006669 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 Py_DECREF(restuple);
6671 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006672 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673 Py_INCREF(resunicode);
6674 Py_DECREF(restuple);
6675 return resunicode;
6676}
6677
Alexander Belopolsky40018472011-02-26 01:02:56 +00006678static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006679unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006680 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006681 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006683 /* input state */
6684 Py_ssize_t pos=0, size;
6685 int kind;
6686 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006687 /* pointer into the output */
6688 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006689 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6690 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006691 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006693 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006694 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006695 /* output object */
6696 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697
Benjamin Petersonbac79492012-01-14 13:34:47 -05006698 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006699 return NULL;
6700 size = PyUnicode_GET_LENGTH(unicode);
6701 kind = PyUnicode_KIND(unicode);
6702 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006703 /* allocate enough for a simple encoding without
6704 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006705 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006706 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006707
6708 _PyBytesWriter_Init(&writer);
6709 str = _PyBytesWriter_Alloc(&writer, size);
6710 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006711 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006712
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006713 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006714 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006715
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006717 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006719 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006720 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006721 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006723 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006725 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006726 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006728
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006729 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006731
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006732 /* Only overallocate the buffer if it's not the last write */
6733 writer.overallocate = (collend < size);
6734
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006736 if (error_handler == _Py_ERROR_UNKNOWN)
6737 error_handler = get_error_handler(errors);
6738
6739 switch (error_handler) {
6740 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006741 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006743
6744 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006745 memset(str, '?', collend - collstart);
6746 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006747 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006748 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006749 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 break;
Victor Stinner50149202015-09-22 00:26:54 +02006751
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006752 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006753 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006754 writer.min_size -= (collend - collstart);
6755 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006756 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006757 if (str == NULL)
6758 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006759 pos = collend;
6760 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006761
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006762 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006763 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006764 writer.min_size -= (collend - collstart);
6765 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006766 unicode, collstart, collend);
6767 if (str == NULL)
6768 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006769 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 break;
Victor Stinner50149202015-09-22 00:26:54 +02006771
Victor Stinnerc3713e92015-09-29 12:32:13 +02006772 case _Py_ERROR_SURROGATEESCAPE:
6773 for (i = collstart; i < collend; ++i) {
6774 ch = PyUnicode_READ(kind, data, i);
6775 if (ch < 0xdc80 || 0xdcff < ch) {
6776 /* Not a UTF-8b surrogate */
6777 break;
6778 }
6779 *str++ = (char)(ch - 0xdc00);
6780 ++pos;
6781 }
6782 if (i >= collend)
6783 break;
6784 collstart = pos;
6785 assert(collstart != collend);
6786 /* fallback to general error handling */
6787
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006789 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6790 encoding, reason, unicode, &exc,
6791 collstart, collend, &newpos);
6792 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006794
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006795 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006796 writer.min_size -= 1;
6797
Victor Stinner6bd525b2015-10-09 13:10:05 +02006798 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006799 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006800 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006801 PyBytes_AS_STRING(rep),
6802 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006803 if (str == NULL)
6804 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006805 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006806 else {
6807 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006808
Victor Stinner6bd525b2015-10-09 13:10:05 +02006809 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006811
6812 if (PyUnicode_IS_ASCII(rep)) {
6813 /* Fast path: all characters are smaller than limit */
6814 assert(limit >= 128);
6815 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6816 str = _PyBytesWriter_WriteBytes(&writer, str,
6817 PyUnicode_DATA(rep),
6818 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006820 else {
6821 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6822
6823 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6824 if (str == NULL)
6825 goto onError;
6826
6827 /* check if there is anything unencodable in the
6828 replacement and copy it to the output */
6829 for (i = 0; repsize-->0; ++i, ++str) {
6830 ch = PyUnicode_READ_CHAR(rep, i);
6831 if (ch >= limit) {
6832 raise_encode_exception(&exc, encoding, unicode,
6833 pos, pos+1, reason);
6834 goto onError;
6835 }
6836 *str = (char)ch;
6837 }
6838 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006839 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006840 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006841 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006842 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006843
6844 /* If overallocation was disabled, ensure that it was the last
6845 write. Otherwise, we missed an optimization */
6846 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006847 }
6848 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006849
Victor Stinner50149202015-09-22 00:26:54 +02006850 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006851 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006852 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006853
6854 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006855 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006856 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006857 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006858 Py_XDECREF(exc);
6859 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006860}
6861
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006862/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006863PyObject *
6864PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006865 Py_ssize_t size,
6866 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006867{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006868 PyObject *result;
6869 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6870 if (unicode == NULL)
6871 return NULL;
6872 result = unicode_encode_ucs1(unicode, errors, 256);
6873 Py_DECREF(unicode);
6874 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006875}
6876
Alexander Belopolsky40018472011-02-26 01:02:56 +00006877PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006878_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006879{
6880 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 PyErr_BadArgument();
6882 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006883 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006884 if (PyUnicode_READY(unicode) == -1)
6885 return NULL;
6886 /* Fast path: if it is a one-byte string, construct
6887 bytes object directly. */
6888 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6889 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6890 PyUnicode_GET_LENGTH(unicode));
6891 /* Non-Latin-1 characters present. Defer to above function to
6892 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006893 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006894}
6895
6896PyObject*
6897PyUnicode_AsLatin1String(PyObject *unicode)
6898{
6899 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006900}
6901
6902/* --- 7-bit ASCII Codec -------------------------------------------------- */
6903
Alexander Belopolsky40018472011-02-26 01:02:56 +00006904PyObject *
6905PyUnicode_DecodeASCII(const char *s,
6906 Py_ssize_t size,
6907 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006909 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006910 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006911 int kind;
6912 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006913 Py_ssize_t startinpos;
6914 Py_ssize_t endinpos;
6915 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006916 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006917 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006918 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006919 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006920
Guido van Rossumd57fd912000-03-10 22:53:23 +00006921 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006922 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006923
Guido van Rossumd57fd912000-03-10 22:53:23 +00006924 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006925 if (size == 1 && (unsigned char)s[0] < 128)
6926 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006927
Victor Stinner8f674cc2013-04-17 23:02:17 +02006928 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006929 writer.min_length = size;
6930 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006931 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006932
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006934 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006935 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006936 writer.pos = outpos;
6937 if (writer.pos == size)
6938 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006939
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006940 s += writer.pos;
6941 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006942 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006943 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006945 PyUnicode_WRITE(kind, data, writer.pos, c);
6946 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006947 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006948 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006949 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006950
6951 /* byte outsize range 0x00..0x7f: call the error handler */
6952
6953 if (error_handler == _Py_ERROR_UNKNOWN)
6954 error_handler = get_error_handler(errors);
6955
6956 switch (error_handler)
6957 {
6958 case _Py_ERROR_REPLACE:
6959 case _Py_ERROR_SURROGATEESCAPE:
6960 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006961 but we may switch to UCS2 at the first write */
6962 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6963 goto onError;
6964 kind = writer.kind;
6965 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006966
6967 if (error_handler == _Py_ERROR_REPLACE)
6968 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6969 else
6970 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6971 writer.pos++;
6972 ++s;
6973 break;
6974
6975 case _Py_ERROR_IGNORE:
6976 ++s;
6977 break;
6978
6979 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006980 startinpos = s-starts;
6981 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006982 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 "ascii", "ordinal not in range(128)",
6985 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006986 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006988 kind = writer.kind;
6989 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006990 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006991 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006992 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006993 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006994 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006995
Benjamin Peterson29060642009-01-31 22:14:21 +00006996 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006997 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006998 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006999 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007000 return NULL;
7001}
7002
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007003/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007004PyObject *
7005PyUnicode_EncodeASCII(const Py_UNICODE *p,
7006 Py_ssize_t size,
7007 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007008{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007009 PyObject *result;
7010 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7011 if (unicode == NULL)
7012 return NULL;
7013 result = unicode_encode_ucs1(unicode, errors, 128);
7014 Py_DECREF(unicode);
7015 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007016}
7017
Alexander Belopolsky40018472011-02-26 01:02:56 +00007018PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007019_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007020{
7021 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 PyErr_BadArgument();
7023 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007025 if (PyUnicode_READY(unicode) == -1)
7026 return NULL;
7027 /* Fast path: if it is an ASCII-only string, construct bytes object
7028 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007029 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007030 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7031 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007032 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007033}
7034
7035PyObject *
7036PyUnicode_AsASCIIString(PyObject *unicode)
7037{
7038 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007039}
7040
Steve Dowercc16be82016-09-08 10:35:16 -07007041#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007042
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007043/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007044
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007045#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046#define NEED_RETRY
7047#endif
7048
Victor Stinner3a50e702011-10-18 21:21:00 +02007049#ifndef WC_ERR_INVALID_CHARS
7050# define WC_ERR_INVALID_CHARS 0x0080
7051#endif
7052
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007053static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007054code_page_name(UINT code_page, PyObject **obj)
7055{
7056 *obj = NULL;
7057 if (code_page == CP_ACP)
7058 return "mbcs";
7059 if (code_page == CP_UTF7)
7060 return "CP_UTF7";
7061 if (code_page == CP_UTF8)
7062 return "CP_UTF8";
7063
7064 *obj = PyBytes_FromFormat("cp%u", code_page);
7065 if (*obj == NULL)
7066 return NULL;
7067 return PyBytes_AS_STRING(*obj);
7068}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069
Victor Stinner3a50e702011-10-18 21:21:00 +02007070static DWORD
7071decode_code_page_flags(UINT code_page)
7072{
7073 if (code_page == CP_UTF7) {
7074 /* The CP_UTF7 decoder only supports flags=0 */
7075 return 0;
7076 }
7077 else
7078 return MB_ERR_INVALID_CHARS;
7079}
7080
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 * Decode a byte string from a Windows code page into unicode object in strict
7083 * mode.
7084 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007085 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7086 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007088static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007089decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007090 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 const char *in,
7092 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007093{
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007095 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007096 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097
7098 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 assert(insize > 0);
7100 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7101 if (outsize <= 0)
7102 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103
7104 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007105 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007106 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007107 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007108 if (*v == NULL)
7109 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007110 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111 }
7112 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007113 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007114 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007115 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007116 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007117 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118 }
7119
7120 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7122 if (outsize <= 0)
7123 goto error;
7124 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007125
Victor Stinner3a50e702011-10-18 21:21:00 +02007126error:
7127 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7128 return -2;
7129 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007130 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007131}
7132
Victor Stinner3a50e702011-10-18 21:21:00 +02007133/*
7134 * Decode a byte string from a code page into unicode object with an error
7135 * handler.
7136 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007137 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 * UnicodeDecodeError exception and returns -1 on error.
7139 */
7140static int
7141decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007142 PyObject **v,
7143 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007144 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007145{
7146 const char *startin = in;
7147 const char *endin = in + size;
7148 const DWORD flags = decode_code_page_flags(code_page);
7149 /* Ideally, we should get reason from FormatMessage. This is the Windows
7150 2000 English version of the message. */
7151 const char *reason = "No mapping for the Unicode character exists "
7152 "in the target code page.";
7153 /* each step cannot decode more than 1 character, but a character can be
7154 represented as a surrogate pair */
7155 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007156 int insize;
7157 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 PyObject *errorHandler = NULL;
7159 PyObject *exc = NULL;
7160 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007161 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 DWORD err;
7163 int ret = -1;
7164
7165 assert(size > 0);
7166
7167 encoding = code_page_name(code_page, &encoding_obj);
7168 if (encoding == NULL)
7169 return -1;
7170
Victor Stinner7d00cc12014-03-17 23:08:06 +01007171 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007172 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7173 UnicodeDecodeError. */
7174 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7175 if (exc != NULL) {
7176 PyCodec_StrictErrors(exc);
7177 Py_CLEAR(exc);
7178 }
7179 goto error;
7180 }
7181
7182 if (*v == NULL) {
7183 /* Create unicode object */
7184 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7185 PyErr_NoMemory();
7186 goto error;
7187 }
Victor Stinnerab595942011-12-17 04:59:06 +01007188 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007189 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 if (*v == NULL)
7191 goto error;
7192 startout = PyUnicode_AS_UNICODE(*v);
7193 }
7194 else {
7195 /* Extend unicode object */
7196 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7197 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7198 PyErr_NoMemory();
7199 goto error;
7200 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007201 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 goto error;
7203 startout = PyUnicode_AS_UNICODE(*v) + n;
7204 }
7205
7206 /* Decode the byte string character per character */
7207 out = startout;
7208 while (in < endin)
7209 {
7210 /* Decode a character */
7211 insize = 1;
7212 do
7213 {
7214 outsize = MultiByteToWideChar(code_page, flags,
7215 in, insize,
7216 buffer, Py_ARRAY_LENGTH(buffer));
7217 if (outsize > 0)
7218 break;
7219 err = GetLastError();
7220 if (err != ERROR_NO_UNICODE_TRANSLATION
7221 && err != ERROR_INSUFFICIENT_BUFFER)
7222 {
7223 PyErr_SetFromWindowsErr(0);
7224 goto error;
7225 }
7226 insize++;
7227 }
7228 /* 4=maximum length of a UTF-8 sequence */
7229 while (insize <= 4 && (in + insize) <= endin);
7230
7231 if (outsize <= 0) {
7232 Py_ssize_t startinpos, endinpos, outpos;
7233
Victor Stinner7d00cc12014-03-17 23:08:06 +01007234 /* last character in partial decode? */
7235 if (in + insize >= endin && !final)
7236 break;
7237
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 startinpos = in - startin;
7239 endinpos = startinpos + 1;
7240 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007241 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 errors, &errorHandler,
7243 encoding, reason,
7244 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007245 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 {
7247 goto error;
7248 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007249 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 }
7251 else {
7252 in += insize;
7253 memcpy(out, buffer, outsize * sizeof(wchar_t));
7254 out += outsize;
7255 }
7256 }
7257
7258 /* write a NUL character at the end */
7259 *out = 0;
7260
7261 /* Extend unicode object */
7262 outsize = out - startout;
7263 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007264 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007266 /* (in - startin) <= size and size is an int */
7267 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007268
7269error:
7270 Py_XDECREF(encoding_obj);
7271 Py_XDECREF(errorHandler);
7272 Py_XDECREF(exc);
7273 return ret;
7274}
7275
Victor Stinner3a50e702011-10-18 21:21:00 +02007276static PyObject *
7277decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 const char *s, Py_ssize_t size,
7279 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007280{
Victor Stinner76a31a62011-11-04 00:05:13 +01007281 PyObject *v = NULL;
7282 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 if (code_page < 0) {
7285 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7286 return NULL;
7287 }
7288
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007289 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007290 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007291
Victor Stinner76a31a62011-11-04 00:05:13 +01007292 do
7293 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007294#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 if (size > INT_MAX) {
7296 chunk_size = INT_MAX;
7297 final = 0;
7298 done = 0;
7299 }
7300 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007301#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007302 {
7303 chunk_size = (int)size;
7304 final = (consumed == NULL);
7305 done = 1;
7306 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007307
Victor Stinner76a31a62011-11-04 00:05:13 +01007308 if (chunk_size == 0 && done) {
7309 if (v != NULL)
7310 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007311 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007312 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313
Victor Stinner76a31a62011-11-04 00:05:13 +01007314 converted = decode_code_page_strict(code_page, &v,
7315 s, chunk_size);
7316 if (converted == -2)
7317 converted = decode_code_page_errors(code_page, &v,
7318 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007319 errors, final);
7320 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007321
7322 if (converted < 0) {
7323 Py_XDECREF(v);
7324 return NULL;
7325 }
7326
7327 if (consumed)
7328 *consumed += converted;
7329
7330 s += converted;
7331 size -= converted;
7332 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007333
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007334 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007335}
7336
Alexander Belopolsky40018472011-02-26 01:02:56 +00007337PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007338PyUnicode_DecodeCodePageStateful(int code_page,
7339 const char *s,
7340 Py_ssize_t size,
7341 const char *errors,
7342 Py_ssize_t *consumed)
7343{
7344 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7345}
7346
7347PyObject *
7348PyUnicode_DecodeMBCSStateful(const char *s,
7349 Py_ssize_t size,
7350 const char *errors,
7351 Py_ssize_t *consumed)
7352{
7353 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7354}
7355
7356PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007357PyUnicode_DecodeMBCS(const char *s,
7358 Py_ssize_t size,
7359 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007360{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007361 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7362}
7363
Victor Stinner3a50e702011-10-18 21:21:00 +02007364static DWORD
7365encode_code_page_flags(UINT code_page, const char *errors)
7366{
7367 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007368 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007369 }
7370 else if (code_page == CP_UTF7) {
7371 /* CP_UTF7 only supports flags=0 */
7372 return 0;
7373 }
7374 else {
7375 if (errors != NULL && strcmp(errors, "replace") == 0)
7376 return 0;
7377 else
7378 return WC_NO_BEST_FIT_CHARS;
7379 }
7380}
7381
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007382/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 * Encode a Unicode string to a Windows code page into a byte string in strict
7384 * mode.
7385 *
7386 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007387 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007388 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007389static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007390encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007391 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007393{
Victor Stinner554f3f02010-06-16 23:33:54 +00007394 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 BOOL *pusedDefaultChar = &usedDefaultChar;
7396 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007397 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007398 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007399 const DWORD flags = encode_code_page_flags(code_page, NULL);
7400 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007401 /* Create a substring so that we can get the UTF-16 representation
7402 of just the slice under consideration. */
7403 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007404
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007406
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007408 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007410 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007411
Victor Stinner2fc507f2011-11-04 20:06:39 +01007412 substring = PyUnicode_Substring(unicode, offset, offset+len);
7413 if (substring == NULL)
7414 return -1;
7415 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7416 if (p == NULL) {
7417 Py_DECREF(substring);
7418 return -1;
7419 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007420 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007421
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007422 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007424 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 NULL, 0,
7426 NULL, pusedDefaultChar);
7427 if (outsize <= 0)
7428 goto error;
7429 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007430 if (pusedDefaultChar && *pusedDefaultChar) {
7431 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007434
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007438 if (*outbytes == NULL) {
7439 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007440 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007441 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007443 }
7444 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007445 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 const Py_ssize_t n = PyBytes_Size(*outbytes);
7447 if (outsize > PY_SSIZE_T_MAX - n) {
7448 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007449 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007450 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007452 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7453 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007457 }
7458
7459 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007460 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007461 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 out, outsize,
7463 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007464 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 if (outsize <= 0)
7466 goto error;
7467 if (pusedDefaultChar && *pusedDefaultChar)
7468 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007469 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007470
Victor Stinner3a50e702011-10-18 21:21:00 +02007471error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007472 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007473 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7474 return -2;
7475 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007476 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007477}
7478
Victor Stinner3a50e702011-10-18 21:21:00 +02007479/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007480 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 * error handler.
7482 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007483 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007484 * -1 on other error.
7485 */
7486static int
7487encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007488 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007490{
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007492 Py_ssize_t pos = unicode_offset;
7493 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 /* Ideally, we should get reason from FormatMessage. This is the Windows
7495 2000 English version of the message. */
7496 const char *reason = "invalid character";
7497 /* 4=maximum length of a UTF-8 sequence */
7498 char buffer[4];
7499 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7500 Py_ssize_t outsize;
7501 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007502 PyObject *errorHandler = NULL;
7503 PyObject *exc = NULL;
7504 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007505 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007506 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007507 PyObject *rep;
7508 int ret = -1;
7509
7510 assert(insize > 0);
7511
7512 encoding = code_page_name(code_page, &encoding_obj);
7513 if (encoding == NULL)
7514 return -1;
7515
7516 if (errors == NULL || strcmp(errors, "strict") == 0) {
7517 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7518 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007519 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007520 if (exc != NULL) {
7521 PyCodec_StrictErrors(exc);
7522 Py_DECREF(exc);
7523 }
7524 Py_XDECREF(encoding_obj);
7525 return -1;
7526 }
7527
7528 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7529 pusedDefaultChar = &usedDefaultChar;
7530 else
7531 pusedDefaultChar = NULL;
7532
7533 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7534 PyErr_NoMemory();
7535 goto error;
7536 }
7537 outsize = insize * Py_ARRAY_LENGTH(buffer);
7538
7539 if (*outbytes == NULL) {
7540 /* Create string object */
7541 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7542 if (*outbytes == NULL)
7543 goto error;
7544 out = PyBytes_AS_STRING(*outbytes);
7545 }
7546 else {
7547 /* Extend string object */
7548 Py_ssize_t n = PyBytes_Size(*outbytes);
7549 if (n > PY_SSIZE_T_MAX - outsize) {
7550 PyErr_NoMemory();
7551 goto error;
7552 }
7553 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7554 goto error;
7555 out = PyBytes_AS_STRING(*outbytes) + n;
7556 }
7557
7558 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007559 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007560 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007561 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7562 wchar_t chars[2];
7563 int charsize;
7564 if (ch < 0x10000) {
7565 chars[0] = (wchar_t)ch;
7566 charsize = 1;
7567 }
7568 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007569 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7570 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007571 charsize = 2;
7572 }
7573
Victor Stinner3a50e702011-10-18 21:21:00 +02007574 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007575 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007576 buffer, Py_ARRAY_LENGTH(buffer),
7577 NULL, pusedDefaultChar);
7578 if (outsize > 0) {
7579 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7580 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007581 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007582 memcpy(out, buffer, outsize);
7583 out += outsize;
7584 continue;
7585 }
7586 }
7587 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7588 PyErr_SetFromWindowsErr(0);
7589 goto error;
7590 }
7591
Victor Stinner3a50e702011-10-18 21:21:00 +02007592 rep = unicode_encode_call_errorhandler(
7593 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007594 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007595 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007596 if (rep == NULL)
7597 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007598 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007599
7600 if (PyBytes_Check(rep)) {
7601 outsize = PyBytes_GET_SIZE(rep);
7602 if (outsize != 1) {
7603 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7604 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7605 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7606 Py_DECREF(rep);
7607 goto error;
7608 }
7609 out = PyBytes_AS_STRING(*outbytes) + offset;
7610 }
7611 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7612 out += outsize;
7613 }
7614 else {
7615 Py_ssize_t i;
7616 enum PyUnicode_Kind kind;
7617 void *data;
7618
Benjamin Petersonbac79492012-01-14 13:34:47 -05007619 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007620 Py_DECREF(rep);
7621 goto error;
7622 }
7623
7624 outsize = PyUnicode_GET_LENGTH(rep);
7625 if (outsize != 1) {
7626 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7627 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7628 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7629 Py_DECREF(rep);
7630 goto error;
7631 }
7632 out = PyBytes_AS_STRING(*outbytes) + offset;
7633 }
7634 kind = PyUnicode_KIND(rep);
7635 data = PyUnicode_DATA(rep);
7636 for (i=0; i < outsize; i++) {
7637 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7638 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007639 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007640 encoding, unicode,
7641 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007642 "unable to encode error handler result to ASCII");
7643 Py_DECREF(rep);
7644 goto error;
7645 }
7646 *out = (unsigned char)ch;
7647 out++;
7648 }
7649 }
7650 Py_DECREF(rep);
7651 }
7652 /* write a NUL byte */
7653 *out = 0;
7654 outsize = out - PyBytes_AS_STRING(*outbytes);
7655 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7656 if (_PyBytes_Resize(outbytes, outsize) < 0)
7657 goto error;
7658 ret = 0;
7659
7660error:
7661 Py_XDECREF(encoding_obj);
7662 Py_XDECREF(errorHandler);
7663 Py_XDECREF(exc);
7664 return ret;
7665}
7666
Victor Stinner3a50e702011-10-18 21:21:00 +02007667static PyObject *
7668encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007669 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007670 const char *errors)
7671{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007672 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007673 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007674 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007675 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007676
Victor Stinner29dacf22015-01-26 16:41:32 +01007677 if (!PyUnicode_Check(unicode)) {
7678 PyErr_BadArgument();
7679 return NULL;
7680 }
7681
Benjamin Petersonbac79492012-01-14 13:34:47 -05007682 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007683 return NULL;
7684 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007685
Victor Stinner3a50e702011-10-18 21:21:00 +02007686 if (code_page < 0) {
7687 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7688 return NULL;
7689 }
7690
Martin v. Löwis3d325192011-11-04 18:23:06 +01007691 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007692 return PyBytes_FromStringAndSize(NULL, 0);
7693
Victor Stinner7581cef2011-11-03 22:32:33 +01007694 offset = 0;
7695 do
7696 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007697#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007698 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007699 chunks. */
7700 if (len > INT_MAX/2) {
7701 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007702 done = 0;
7703 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007704 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007705#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007706 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007707 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007708 done = 1;
7709 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007710
Victor Stinner76a31a62011-11-04 00:05:13 +01007711 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007712 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007713 errors);
7714 if (ret == -2)
7715 ret = encode_code_page_errors(code_page, &outbytes,
7716 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007717 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007718 if (ret < 0) {
7719 Py_XDECREF(outbytes);
7720 return NULL;
7721 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007722
Victor Stinner7581cef2011-11-03 22:32:33 +01007723 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007724 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007725 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007726
Victor Stinner3a50e702011-10-18 21:21:00 +02007727 return outbytes;
7728}
7729
7730PyObject *
7731PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7732 Py_ssize_t size,
7733 const char *errors)
7734{
Victor Stinner7581cef2011-11-03 22:32:33 +01007735 PyObject *unicode, *res;
7736 unicode = PyUnicode_FromUnicode(p, size);
7737 if (unicode == NULL)
7738 return NULL;
7739 res = encode_code_page(CP_ACP, unicode, errors);
7740 Py_DECREF(unicode);
7741 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007742}
7743
7744PyObject *
7745PyUnicode_EncodeCodePage(int code_page,
7746 PyObject *unicode,
7747 const char *errors)
7748{
Victor Stinner7581cef2011-11-03 22:32:33 +01007749 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007750}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007751
Alexander Belopolsky40018472011-02-26 01:02:56 +00007752PyObject *
7753PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007754{
Victor Stinner7581cef2011-11-03 22:32:33 +01007755 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007756}
7757
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007758#undef NEED_RETRY
7759
Steve Dowercc16be82016-09-08 10:35:16 -07007760#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007761
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762/* --- Character Mapping Codec -------------------------------------------- */
7763
Victor Stinnerfb161b12013-04-18 01:44:27 +02007764static int
7765charmap_decode_string(const char *s,
7766 Py_ssize_t size,
7767 PyObject *mapping,
7768 const char *errors,
7769 _PyUnicodeWriter *writer)
7770{
7771 const char *starts = s;
7772 const char *e;
7773 Py_ssize_t startinpos, endinpos;
7774 PyObject *errorHandler = NULL, *exc = NULL;
7775 Py_ssize_t maplen;
7776 enum PyUnicode_Kind mapkind;
7777 void *mapdata;
7778 Py_UCS4 x;
7779 unsigned char ch;
7780
7781 if (PyUnicode_READY(mapping) == -1)
7782 return -1;
7783
7784 maplen = PyUnicode_GET_LENGTH(mapping);
7785 mapdata = PyUnicode_DATA(mapping);
7786 mapkind = PyUnicode_KIND(mapping);
7787
7788 e = s + size;
7789
7790 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7791 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7792 * is disabled in encoding aliases, latin1 is preferred because
7793 * its implementation is faster. */
7794 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7795 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7796 Py_UCS4 maxchar = writer->maxchar;
7797
7798 assert (writer->kind == PyUnicode_1BYTE_KIND);
7799 while (s < e) {
7800 ch = *s;
7801 x = mapdata_ucs1[ch];
7802 if (x > maxchar) {
7803 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7804 goto onError;
7805 maxchar = writer->maxchar;
7806 outdata = (Py_UCS1 *)writer->data;
7807 }
7808 outdata[writer->pos] = x;
7809 writer->pos++;
7810 ++s;
7811 }
7812 return 0;
7813 }
7814
7815 while (s < e) {
7816 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7817 enum PyUnicode_Kind outkind = writer->kind;
7818 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7819 if (outkind == PyUnicode_1BYTE_KIND) {
7820 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7821 Py_UCS4 maxchar = writer->maxchar;
7822 while (s < e) {
7823 ch = *s;
7824 x = mapdata_ucs2[ch];
7825 if (x > maxchar)
7826 goto Error;
7827 outdata[writer->pos] = x;
7828 writer->pos++;
7829 ++s;
7830 }
7831 break;
7832 }
7833 else if (outkind == PyUnicode_2BYTE_KIND) {
7834 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7835 while (s < e) {
7836 ch = *s;
7837 x = mapdata_ucs2[ch];
7838 if (x == 0xFFFE)
7839 goto Error;
7840 outdata[writer->pos] = x;
7841 writer->pos++;
7842 ++s;
7843 }
7844 break;
7845 }
7846 }
7847 ch = *s;
7848
7849 if (ch < maplen)
7850 x = PyUnicode_READ(mapkind, mapdata, ch);
7851 else
7852 x = 0xfffe; /* invalid value */
7853Error:
7854 if (x == 0xfffe)
7855 {
7856 /* undefined mapping */
7857 startinpos = s-starts;
7858 endinpos = startinpos+1;
7859 if (unicode_decode_call_errorhandler_writer(
7860 errors, &errorHandler,
7861 "charmap", "character maps to <undefined>",
7862 &starts, &e, &startinpos, &endinpos, &exc, &s,
7863 writer)) {
7864 goto onError;
7865 }
7866 continue;
7867 }
7868
7869 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7870 goto onError;
7871 ++s;
7872 }
7873 Py_XDECREF(errorHandler);
7874 Py_XDECREF(exc);
7875 return 0;
7876
7877onError:
7878 Py_XDECREF(errorHandler);
7879 Py_XDECREF(exc);
7880 return -1;
7881}
7882
7883static int
7884charmap_decode_mapping(const char *s,
7885 Py_ssize_t size,
7886 PyObject *mapping,
7887 const char *errors,
7888 _PyUnicodeWriter *writer)
7889{
7890 const char *starts = s;
7891 const char *e;
7892 Py_ssize_t startinpos, endinpos;
7893 PyObject *errorHandler = NULL, *exc = NULL;
7894 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007895 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007896
7897 e = s + size;
7898
7899 while (s < e) {
7900 ch = *s;
7901
7902 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7903 key = PyLong_FromLong((long)ch);
7904 if (key == NULL)
7905 goto onError;
7906
7907 item = PyObject_GetItem(mapping, key);
7908 Py_DECREF(key);
7909 if (item == NULL) {
7910 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7911 /* No mapping found means: mapping is undefined. */
7912 PyErr_Clear();
7913 goto Undefined;
7914 } else
7915 goto onError;
7916 }
7917
7918 /* Apply mapping */
7919 if (item == Py_None)
7920 goto Undefined;
7921 if (PyLong_Check(item)) {
7922 long value = PyLong_AS_LONG(item);
7923 if (value == 0xFFFE)
7924 goto Undefined;
7925 if (value < 0 || value > MAX_UNICODE) {
7926 PyErr_Format(PyExc_TypeError,
7927 "character mapping must be in range(0x%lx)",
7928 (unsigned long)MAX_UNICODE + 1);
7929 goto onError;
7930 }
7931
7932 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7933 goto onError;
7934 }
7935 else if (PyUnicode_Check(item)) {
7936 if (PyUnicode_READY(item) == -1)
7937 goto onError;
7938 if (PyUnicode_GET_LENGTH(item) == 1) {
7939 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7940 if (value == 0xFFFE)
7941 goto Undefined;
7942 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7943 goto onError;
7944 }
7945 else {
7946 writer->overallocate = 1;
7947 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7948 goto onError;
7949 }
7950 }
7951 else {
7952 /* wrong return value */
7953 PyErr_SetString(PyExc_TypeError,
7954 "character mapping must return integer, None or str");
7955 goto onError;
7956 }
7957 Py_CLEAR(item);
7958 ++s;
7959 continue;
7960
7961Undefined:
7962 /* undefined mapping */
7963 Py_CLEAR(item);
7964 startinpos = s-starts;
7965 endinpos = startinpos+1;
7966 if (unicode_decode_call_errorhandler_writer(
7967 errors, &errorHandler,
7968 "charmap", "character maps to <undefined>",
7969 &starts, &e, &startinpos, &endinpos, &exc, &s,
7970 writer)) {
7971 goto onError;
7972 }
7973 }
7974 Py_XDECREF(errorHandler);
7975 Py_XDECREF(exc);
7976 return 0;
7977
7978onError:
7979 Py_XDECREF(item);
7980 Py_XDECREF(errorHandler);
7981 Py_XDECREF(exc);
7982 return -1;
7983}
7984
Alexander Belopolsky40018472011-02-26 01:02:56 +00007985PyObject *
7986PyUnicode_DecodeCharmap(const char *s,
7987 Py_ssize_t size,
7988 PyObject *mapping,
7989 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007991 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007992
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993 /* Default to Latin-1 */
7994 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007995 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007996
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007998 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007999 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008000 writer.min_length = size;
8001 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008003
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008004 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008005 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8006 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008007 }
8008 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008009 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8010 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008011 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008012 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008013
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008015 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008016 return NULL;
8017}
8018
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008019/* Charmap encoding: the lookup table */
8020
Alexander Belopolsky40018472011-02-26 01:02:56 +00008021struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 PyObject_HEAD
8023 unsigned char level1[32];
8024 int count2, count3;
8025 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026};
8027
8028static PyObject*
8029encoding_map_size(PyObject *obj, PyObject* args)
8030{
8031 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008032 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034}
8035
8036static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008037 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 PyDoc_STR("Return the size (in bytes) of this object") },
8039 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040};
8041
8042static void
8043encoding_map_dealloc(PyObject* o)
8044{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008045 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008046}
8047
8048static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008049 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 "EncodingMap", /*tp_name*/
8051 sizeof(struct encoding_map), /*tp_basicsize*/
8052 0, /*tp_itemsize*/
8053 /* methods */
8054 encoding_map_dealloc, /*tp_dealloc*/
8055 0, /*tp_print*/
8056 0, /*tp_getattr*/
8057 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008058 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 0, /*tp_repr*/
8060 0, /*tp_as_number*/
8061 0, /*tp_as_sequence*/
8062 0, /*tp_as_mapping*/
8063 0, /*tp_hash*/
8064 0, /*tp_call*/
8065 0, /*tp_str*/
8066 0, /*tp_getattro*/
8067 0, /*tp_setattro*/
8068 0, /*tp_as_buffer*/
8069 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8070 0, /*tp_doc*/
8071 0, /*tp_traverse*/
8072 0, /*tp_clear*/
8073 0, /*tp_richcompare*/
8074 0, /*tp_weaklistoffset*/
8075 0, /*tp_iter*/
8076 0, /*tp_iternext*/
8077 encoding_map_methods, /*tp_methods*/
8078 0, /*tp_members*/
8079 0, /*tp_getset*/
8080 0, /*tp_base*/
8081 0, /*tp_dict*/
8082 0, /*tp_descr_get*/
8083 0, /*tp_descr_set*/
8084 0, /*tp_dictoffset*/
8085 0, /*tp_init*/
8086 0, /*tp_alloc*/
8087 0, /*tp_new*/
8088 0, /*tp_free*/
8089 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090};
8091
8092PyObject*
8093PyUnicode_BuildEncodingMap(PyObject* string)
8094{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095 PyObject *result;
8096 struct encoding_map *mresult;
8097 int i;
8098 int need_dict = 0;
8099 unsigned char level1[32];
8100 unsigned char level2[512];
8101 unsigned char *mlevel1, *mlevel2, *mlevel3;
8102 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008103 int kind;
8104 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008105 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008108 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008109 PyErr_BadArgument();
8110 return NULL;
8111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008112 kind = PyUnicode_KIND(string);
8113 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008114 length = PyUnicode_GET_LENGTH(string);
8115 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116 memset(level1, 0xFF, sizeof level1);
8117 memset(level2, 0xFF, sizeof level2);
8118
8119 /* If there isn't a one-to-one mapping of NULL to \0,
8120 or if there are non-BMP characters, we need to use
8121 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008122 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008124 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008125 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008126 ch = PyUnicode_READ(kind, data, i);
8127 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 need_dict = 1;
8129 break;
8130 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008131 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132 /* unmapped character */
8133 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008134 l1 = ch >> 11;
8135 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 if (level1[l1] == 0xFF)
8137 level1[l1] = count2++;
8138 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008139 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140 }
8141
8142 if (count2 >= 0xFF || count3 >= 0xFF)
8143 need_dict = 1;
8144
8145 if (need_dict) {
8146 PyObject *result = PyDict_New();
8147 PyObject *key, *value;
8148 if (!result)
8149 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008150 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008151 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008152 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153 if (!key || !value)
8154 goto failed1;
8155 if (PyDict_SetItem(result, key, value) == -1)
8156 goto failed1;
8157 Py_DECREF(key);
8158 Py_DECREF(value);
8159 }
8160 return result;
8161 failed1:
8162 Py_XDECREF(key);
8163 Py_XDECREF(value);
8164 Py_DECREF(result);
8165 return NULL;
8166 }
8167
8168 /* Create a three-level trie */
8169 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8170 16*count2 + 128*count3 - 1);
8171 if (!result)
8172 return PyErr_NoMemory();
8173 PyObject_Init(result, &EncodingMapType);
8174 mresult = (struct encoding_map*)result;
8175 mresult->count2 = count2;
8176 mresult->count3 = count3;
8177 mlevel1 = mresult->level1;
8178 mlevel2 = mresult->level23;
8179 mlevel3 = mresult->level23 + 16*count2;
8180 memcpy(mlevel1, level1, 32);
8181 memset(mlevel2, 0xFF, 16*count2);
8182 memset(mlevel3, 0, 128*count3);
8183 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008184 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008185 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008186 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8187 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008188 /* unmapped character */
8189 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008190 o1 = ch>>11;
8191 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008192 i2 = 16*mlevel1[o1] + o2;
8193 if (mlevel2[i2] == 0xFF)
8194 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008195 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 i3 = 128*mlevel2[i2] + o3;
8197 mlevel3[i3] = i;
8198 }
8199 return result;
8200}
8201
8202static int
Victor Stinner22168992011-11-20 17:09:18 +01008203encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008204{
8205 struct encoding_map *map = (struct encoding_map*)mapping;
8206 int l1 = c>>11;
8207 int l2 = (c>>7) & 0xF;
8208 int l3 = c & 0x7F;
8209 int i;
8210
Victor Stinner22168992011-11-20 17:09:18 +01008211 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213 if (c == 0)
8214 return 0;
8215 /* level 1*/
8216 i = map->level1[l1];
8217 if (i == 0xFF) {
8218 return -1;
8219 }
8220 /* level 2*/
8221 i = map->level23[16*i+l2];
8222 if (i == 0xFF) {
8223 return -1;
8224 }
8225 /* level 3 */
8226 i = map->level23[16*map->count2 + 128*i + l3];
8227 if (i == 0) {
8228 return -1;
8229 }
8230 return i;
8231}
8232
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233/* Lookup the character ch in the mapping. If the character
8234 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008235 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008236static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008237charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008238{
Christian Heimes217cfd12007-12-02 14:31:20 +00008239 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008240 PyObject *x;
8241
8242 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008244 x = PyObject_GetItem(mapping, w);
8245 Py_DECREF(w);
8246 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8248 /* No mapping found means: mapping is undefined. */
8249 PyErr_Clear();
8250 x = Py_None;
8251 Py_INCREF(x);
8252 return x;
8253 } else
8254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008256 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008258 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 long value = PyLong_AS_LONG(x);
8260 if (value < 0 || value > 255) {
8261 PyErr_SetString(PyExc_TypeError,
8262 "character mapping must be in range(256)");
8263 Py_DECREF(x);
8264 return NULL;
8265 }
8266 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008267 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008268 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008270 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 /* wrong return value */
8272 PyErr_Format(PyExc_TypeError,
8273 "character mapping must return integer, bytes or None, not %.400s",
8274 x->ob_type->tp_name);
8275 Py_DECREF(x);
8276 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008277 }
8278}
8279
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008281charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008282{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008283 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8284 /* exponentially overallocate to minimize reallocations */
8285 if (requiredsize < 2*outsize)
8286 requiredsize = 2*outsize;
8287 if (_PyBytes_Resize(outobj, requiredsize))
8288 return -1;
8289 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008290}
8291
Benjamin Peterson14339b62009-01-31 16:36:08 +00008292typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008294} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008296 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008297 space is available. Return a new reference to the object that
8298 was put in the output buffer, or Py_None, if the mapping was undefined
8299 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008300 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008301static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008302charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008303 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305 PyObject *rep;
8306 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008307 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308
Christian Heimes90aa7642007-12-19 02:45:37 +00008309 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008310 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008312 if (res == -1)
8313 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 if (outsize<requiredsize)
8315 if (charmapencode_resize(outobj, outpos, requiredsize))
8316 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008317 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 outstart[(*outpos)++] = (char)res;
8319 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008320 }
8321
8322 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008325 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 Py_DECREF(rep);
8327 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008328 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 if (PyLong_Check(rep)) {
8330 Py_ssize_t requiredsize = *outpos+1;
8331 if (outsize<requiredsize)
8332 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8333 Py_DECREF(rep);
8334 return enc_EXCEPTION;
8335 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008336 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008338 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008339 else {
8340 const char *repchars = PyBytes_AS_STRING(rep);
8341 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8342 Py_ssize_t requiredsize = *outpos+repsize;
8343 if (outsize<requiredsize)
8344 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8345 Py_DECREF(rep);
8346 return enc_EXCEPTION;
8347 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008348 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 memcpy(outstart + *outpos, repchars, repsize);
8350 *outpos += repsize;
8351 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008353 Py_DECREF(rep);
8354 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355}
8356
8357/* handle an error in PyUnicode_EncodeCharmap
8358 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008359static int
8360charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008363 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008364 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365{
8366 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008367 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008368 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008369 enum PyUnicode_Kind kind;
8370 void *data;
8371 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008373 Py_ssize_t collstartpos = *inpos;
8374 Py_ssize_t collendpos = *inpos+1;
8375 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 char *encoding = "charmap";
8377 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008378 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008379 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008380 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381
Benjamin Petersonbac79492012-01-14 13:34:47 -05008382 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008383 return -1;
8384 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 /* find all unencodable characters */
8386 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008387 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008388 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008389 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008390 val = encoding_map_lookup(ch, mapping);
8391 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 break;
8393 ++collendpos;
8394 continue;
8395 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008396
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008397 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8398 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 if (rep==NULL)
8400 return -1;
8401 else if (rep!=Py_None) {
8402 Py_DECREF(rep);
8403 break;
8404 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008405 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 /* cache callback name lookup
8409 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008410 if (*error_handler == _Py_ERROR_UNKNOWN)
8411 *error_handler = get_error_handler(errors);
8412
8413 switch (*error_handler) {
8414 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008415 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008417
8418 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008419 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 x = charmapencode_output('?', mapping, res, respos);
8421 if (x==enc_EXCEPTION) {
8422 return -1;
8423 }
8424 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008425 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 return -1;
8427 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008428 }
8429 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008430 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008431 *inpos = collendpos;
8432 break;
Victor Stinner50149202015-09-22 00:26:54 +02008433
8434 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008435 /* generate replacement (temporarily (mis)uses p) */
8436 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 char buffer[2+29+1+1];
8438 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008439 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 for (cp = buffer; *cp; ++cp) {
8441 x = charmapencode_output(*cp, mapping, res, respos);
8442 if (x==enc_EXCEPTION)
8443 return -1;
8444 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008445 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 return -1;
8447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 }
8449 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008450 *inpos = collendpos;
8451 break;
Victor Stinner50149202015-09-22 00:26:54 +02008452
Benjamin Peterson14339b62009-01-31 16:36:08 +00008453 default:
Victor Stinner50149202015-09-22 00:26:54 +02008454 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008455 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008457 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008459 if (PyBytes_Check(repunicode)) {
8460 /* Directly copy bytes result to output. */
8461 Py_ssize_t outsize = PyBytes_Size(*res);
8462 Py_ssize_t requiredsize;
8463 repsize = PyBytes_Size(repunicode);
8464 requiredsize = *respos + repsize;
8465 if (requiredsize > outsize)
8466 /* Make room for all additional bytes. */
8467 if (charmapencode_resize(res, respos, requiredsize)) {
8468 Py_DECREF(repunicode);
8469 return -1;
8470 }
8471 memcpy(PyBytes_AsString(*res) + *respos,
8472 PyBytes_AsString(repunicode), repsize);
8473 *respos += repsize;
8474 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008475 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008476 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008477 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008478 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008479 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008480 Py_DECREF(repunicode);
8481 return -1;
8482 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008483 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008484 data = PyUnicode_DATA(repunicode);
8485 kind = PyUnicode_KIND(repunicode);
8486 for (index = 0; index < repsize; index++) {
8487 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8488 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008490 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return -1;
8492 }
8493 else if (x==enc_FAILED) {
8494 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008495 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 return -1;
8497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008498 }
8499 *inpos = newpos;
8500 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 }
8502 return 0;
8503}
8504
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008506_PyUnicode_EncodeCharmap(PyObject *unicode,
8507 PyObject *mapping,
8508 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 /* output object */
8511 PyObject *res = NULL;
8512 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008513 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008516 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008517 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008519 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008520 void *data;
8521 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522
Benjamin Petersonbac79492012-01-14 13:34:47 -05008523 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008524 return NULL;
8525 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008526 data = PyUnicode_DATA(unicode);
8527 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528
Guido van Rossumd57fd912000-03-10 22:53:23 +00008529 /* Default to Latin-1 */
8530 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 /* allocate enough for a simple encoding without
8534 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008535 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 if (res == NULL)
8537 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008538 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008542 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008544 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 if (x==enc_EXCEPTION) /* error */
8546 goto onError;
8547 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008548 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008550 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 &res, &respos)) {
8552 goto onError;
8553 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008554 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 else
8556 /* done with this character => adjust input position */
8557 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008561 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008562 if (_PyBytes_Resize(&res, respos) < 0)
8563 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008564
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008566 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567 return res;
8568
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 Py_XDECREF(res);
8571 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008572 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008573 return NULL;
8574}
8575
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008576/* Deprecated */
8577PyObject *
8578PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8579 Py_ssize_t size,
8580 PyObject *mapping,
8581 const char *errors)
8582{
8583 PyObject *result;
8584 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8585 if (unicode == NULL)
8586 return NULL;
8587 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8588 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008589 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008590}
8591
Alexander Belopolsky40018472011-02-26 01:02:56 +00008592PyObject *
8593PyUnicode_AsCharmapString(PyObject *unicode,
8594 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008595{
8596 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 PyErr_BadArgument();
8598 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008600 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601}
8602
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008603/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008604static void
8605make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008607 Py_ssize_t startpos, Py_ssize_t endpos,
8608 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008609{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 *exceptionObject = _PyUnicodeTranslateError_Create(
8612 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008613 }
8614 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8616 goto onError;
8617 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8618 goto onError;
8619 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8620 goto onError;
8621 return;
8622 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008623 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008624 }
8625}
8626
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627/* error handling callback helper:
8628 build arguments, call the callback and check the arguments,
8629 put the result into newpos and return the replacement string, which
8630 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008631static PyObject *
8632unicode_translate_call_errorhandler(const char *errors,
8633 PyObject **errorHandler,
8634 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008636 Py_ssize_t startpos, Py_ssize_t endpos,
8637 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008639 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008641 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 PyObject *restuple;
8643 PyObject *resunicode;
8644
8645 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 }
8650
8651 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008653 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655
8656 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008658 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008659 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008661 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 Py_DECREF(restuple);
8663 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 }
8665 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 &resunicode, &i_newpos)) {
8667 Py_DECREF(restuple);
8668 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008670 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008672 else
8673 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008675 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 Py_DECREF(restuple);
8677 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008678 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679 Py_INCREF(resunicode);
8680 Py_DECREF(restuple);
8681 return resunicode;
8682}
8683
8684/* Lookup the character ch in the mapping and put the result in result,
8685 which must be decrefed by the caller.
8686 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008687static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689{
Christian Heimes217cfd12007-12-02 14:31:20 +00008690 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 PyObject *x;
8692
8693 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008695 x = PyObject_GetItem(mapping, w);
8696 Py_DECREF(w);
8697 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8699 /* No mapping found means: use 1:1 mapping. */
8700 PyErr_Clear();
8701 *result = NULL;
8702 return 0;
8703 } else
8704 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008705 }
8706 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 *result = x;
8708 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008709 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008710 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008712 if (value < 0 || value > MAX_UNICODE) {
8713 PyErr_Format(PyExc_ValueError,
8714 "character mapping must be in range(0x%x)",
8715 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 Py_DECREF(x);
8717 return -1;
8718 }
8719 *result = x;
8720 return 0;
8721 }
8722 else if (PyUnicode_Check(x)) {
8723 *result = x;
8724 return 0;
8725 }
8726 else {
8727 /* wrong return value */
8728 PyErr_SetString(PyExc_TypeError,
8729 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008730 Py_DECREF(x);
8731 return -1;
8732 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008733}
Victor Stinner1194ea02014-04-04 19:37:40 +02008734
8735/* lookup the character, write the result into the writer.
8736 Return 1 if the result was written into the writer, return 0 if the mapping
8737 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008738static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008739charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8740 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008741{
Victor Stinner1194ea02014-04-04 19:37:40 +02008742 PyObject *item;
8743
8744 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008746
8747 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008749 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008751 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008752 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008753 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008754
8755 if (item == Py_None) {
8756 Py_DECREF(item);
8757 return 0;
8758 }
8759
8760 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008761 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8762 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8763 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008764 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8765 Py_DECREF(item);
8766 return -1;
8767 }
8768 Py_DECREF(item);
8769 return 1;
8770 }
8771
8772 if (!PyUnicode_Check(item)) {
8773 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008775 }
8776
8777 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8778 Py_DECREF(item);
8779 return -1;
8780 }
8781
8782 Py_DECREF(item);
8783 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008784}
8785
Victor Stinner89a76ab2014-04-05 11:44:04 +02008786static int
8787unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8788 Py_UCS1 *translate)
8789{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008790 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008791 int ret = 0;
8792
Victor Stinner89a76ab2014-04-05 11:44:04 +02008793 if (charmaptranslate_lookup(ch, mapping, &item)) {
8794 return -1;
8795 }
8796
8797 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008798 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008799 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008800 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008801 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008802 /* not found => default to 1:1 mapping */
8803 translate[ch] = ch;
8804 return 1;
8805 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008806 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008807 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008808 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8809 used it */
8810 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008811 /* invalid character or character outside ASCII:
8812 skip the fast translate */
8813 goto exit;
8814 }
8815 translate[ch] = (Py_UCS1)replace;
8816 }
8817 else if (PyUnicode_Check(item)) {
8818 Py_UCS4 replace;
8819
8820 if (PyUnicode_READY(item) == -1) {
8821 Py_DECREF(item);
8822 return -1;
8823 }
8824 if (PyUnicode_GET_LENGTH(item) != 1)
8825 goto exit;
8826
8827 replace = PyUnicode_READ_CHAR(item, 0);
8828 if (replace > 127)
8829 goto exit;
8830 translate[ch] = (Py_UCS1)replace;
8831 }
8832 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008833 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834 goto exit;
8835 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008836 ret = 1;
8837
Benjamin Peterson1365de72014-04-07 20:15:41 -04008838 exit:
8839 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840 return ret;
8841}
8842
8843/* Fast path for ascii => ascii translation. Return 1 if the whole string
8844 was translated into writer, return 0 if the input string was partially
8845 translated into writer, raise an exception and return -1 on error. */
8846static int
8847unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008848 _PyUnicodeWriter *writer, int ignore,
8849 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008850{
Victor Stinner872b2912014-04-05 14:27:07 +02008851 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008852 Py_ssize_t len;
8853 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008854 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855
Victor Stinner89a76ab2014-04-05 11:44:04 +02008856 len = PyUnicode_GET_LENGTH(input);
8857
Victor Stinner872b2912014-04-05 14:27:07 +02008858 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859
8860 in = PyUnicode_1BYTE_DATA(input);
8861 end = in + len;
8862
8863 assert(PyUnicode_IS_ASCII(writer->buffer));
8864 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8865 out = PyUnicode_1BYTE_DATA(writer->buffer);
8866
Victor Stinner872b2912014-04-05 14:27:07 +02008867 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008868 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008869 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008870 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008871 int translate = unicode_fast_translate_lookup(mapping, ch,
8872 ascii_table);
8873 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008874 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008875 if (translate == 0)
8876 goto exit;
8877 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878 }
Victor Stinner872b2912014-04-05 14:27:07 +02008879 if (ch2 == 0xfe) {
8880 if (ignore)
8881 continue;
8882 goto exit;
8883 }
8884 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008885 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008886 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008887 }
Victor Stinner872b2912014-04-05 14:27:07 +02008888 res = 1;
8889
8890exit:
8891 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008892 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008893 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008894}
8895
Victor Stinner3222da22015-10-01 22:07:32 +02008896static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897_PyUnicode_TranslateCharmap(PyObject *input,
8898 PyObject *mapping,
8899 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008902 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008903 Py_ssize_t size, i;
8904 int kind;
8905 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008906 _PyUnicodeWriter writer;
8907 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008908 char *reason = "character maps to <undefined>";
8909 PyObject *errorHandler = NULL;
8910 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008911 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008912 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008913
Guido van Rossumd57fd912000-03-10 22:53:23 +00008914 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 PyErr_BadArgument();
8916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008917 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008919 if (PyUnicode_READY(input) == -1)
8920 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008921 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008922 kind = PyUnicode_KIND(input);
8923 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008925 if (size == 0)
8926 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008928 /* allocate enough for a simple 1:1 translation without
8929 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008930 _PyUnicodeWriter_Init(&writer);
8931 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008933
Victor Stinner872b2912014-04-05 14:27:07 +02008934 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8935
Victor Stinner33798672016-03-01 21:59:58 +01008936 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008937 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008938 if (PyUnicode_IS_ASCII(input)) {
8939 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8940 if (res < 0) {
8941 _PyUnicodeWriter_Dealloc(&writer);
8942 return NULL;
8943 }
8944 if (res == 1)
8945 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008946 }
Victor Stinner33798672016-03-01 21:59:58 +01008947 else {
8948 i = 0;
8949 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008950
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008953 int translate;
8954 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8955 Py_ssize_t newpos;
8956 /* startpos for collecting untranslatable chars */
8957 Py_ssize_t collstart;
8958 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008959 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960
Victor Stinner1194ea02014-04-04 19:37:40 +02008961 ch = PyUnicode_READ(kind, data, i);
8962 translate = charmaptranslate_output(ch, mapping, &writer);
8963 if (translate < 0)
8964 goto onError;
8965
8966 if (translate != 0) {
8967 /* it worked => adjust input pointer */
8968 ++i;
8969 continue;
8970 }
8971
8972 /* untranslatable character */
8973 collstart = i;
8974 collend = i+1;
8975
8976 /* find all untranslatable characters */
8977 while (collend < size) {
8978 PyObject *x;
8979 ch = PyUnicode_READ(kind, data, collend);
8980 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008981 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 Py_XDECREF(x);
8983 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008984 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008985 ++collend;
8986 }
8987
8988 if (ignore) {
8989 i = collend;
8990 }
8991 else {
8992 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8993 reason, input, &exc,
8994 collstart, collend, &newpos);
8995 if (repunicode == NULL)
8996 goto onError;
8997 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008998 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008999 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009000 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009001 Py_DECREF(repunicode);
9002 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009003 }
9004 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009005 Py_XDECREF(exc);
9006 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009007 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009010 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009011 Py_XDECREF(exc);
9012 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013 return NULL;
9014}
9015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016/* Deprecated. Use PyUnicode_Translate instead. */
9017PyObject *
9018PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9019 Py_ssize_t size,
9020 PyObject *mapping,
9021 const char *errors)
9022{
Christian Heimes5f520f42012-09-11 14:03:25 +02009023 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9025 if (!unicode)
9026 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009027 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9028 Py_DECREF(unicode);
9029 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030}
9031
Alexander Belopolsky40018472011-02-26 01:02:56 +00009032PyObject *
9033PyUnicode_Translate(PyObject *str,
9034 PyObject *mapping,
9035 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009037 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009038 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009039 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040}
Tim Petersced69f82003-09-16 20:30:58 +00009041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009043fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009044{
9045 /* No need to call PyUnicode_READY(self) because this function is only
9046 called as a callback from fixup() which does it already. */
9047 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9048 const int kind = PyUnicode_KIND(self);
9049 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009050 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009051 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009052 Py_ssize_t i;
9053
9054 for (i = 0; i < len; ++i) {
9055 ch = PyUnicode_READ(kind, data, i);
9056 fixed = 0;
9057 if (ch > 127) {
9058 if (Py_UNICODE_ISSPACE(ch))
9059 fixed = ' ';
9060 else {
9061 const int decimal = Py_UNICODE_TODECIMAL(ch);
9062 if (decimal >= 0)
9063 fixed = '0' + decimal;
9064 }
9065 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009066 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009067 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 PyUnicode_WRITE(kind, data, i, fixed);
9069 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009070 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009071 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073 }
9074
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009075 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076}
9077
9078PyObject *
9079_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9080{
9081 if (!PyUnicode_Check(unicode)) {
9082 PyErr_BadInternalCall();
9083 return NULL;
9084 }
9085 if (PyUnicode_READY(unicode) == -1)
9086 return NULL;
9087 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9088 /* If the string is already ASCII, just return the same string */
9089 Py_INCREF(unicode);
9090 return unicode;
9091 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009092 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093}
9094
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009095PyObject *
9096PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9097 Py_ssize_t length)
9098{
Victor Stinnerf0124502011-11-21 23:12:56 +01009099 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009100 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009101 Py_UCS4 maxchar;
9102 enum PyUnicode_Kind kind;
9103 void *data;
9104
Victor Stinner99d7ad02012-02-22 13:37:39 +01009105 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009106 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009107 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009108 if (ch > 127) {
9109 int decimal = Py_UNICODE_TODECIMAL(ch);
9110 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009111 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009112 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009113 }
9114 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009115
9116 /* Copy to a new string */
9117 decimal = PyUnicode_New(length, maxchar);
9118 if (decimal == NULL)
9119 return decimal;
9120 kind = PyUnicode_KIND(decimal);
9121 data = PyUnicode_DATA(decimal);
9122 /* Iterate over code points */
9123 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009124 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009125 if (ch > 127) {
9126 int decimal = Py_UNICODE_TODECIMAL(ch);
9127 if (decimal >= 0)
9128 ch = '0' + decimal;
9129 }
9130 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009131 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009132 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009133}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009134/* --- Decimal Encoder ---------------------------------------------------- */
9135
Alexander Belopolsky40018472011-02-26 01:02:56 +00009136int
9137PyUnicode_EncodeDecimal(Py_UNICODE *s,
9138 Py_ssize_t length,
9139 char *output,
9140 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009141{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009142 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009143 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009144 enum PyUnicode_Kind kind;
9145 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009146
9147 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009148 PyErr_BadArgument();
9149 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009150 }
9151
Victor Stinner42bf7752011-11-21 22:52:58 +01009152 unicode = PyUnicode_FromUnicode(s, length);
9153 if (unicode == NULL)
9154 return -1;
9155
Benjamin Petersonbac79492012-01-14 13:34:47 -05009156 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009157 Py_DECREF(unicode);
9158 return -1;
9159 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009160 kind = PyUnicode_KIND(unicode);
9161 data = PyUnicode_DATA(unicode);
9162
Victor Stinnerb84d7232011-11-22 01:50:07 +01009163 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009164 PyObject *exc;
9165 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009167 Py_ssize_t startpos;
9168
9169 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009170
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009172 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009173 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009174 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009175 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 decimal = Py_UNICODE_TODECIMAL(ch);
9177 if (decimal >= 0) {
9178 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009179 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009180 continue;
9181 }
9182 if (0 < ch && ch < 256) {
9183 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009184 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009185 continue;
9186 }
Victor Stinner6345be92011-11-25 20:09:01 +01009187
Victor Stinner42bf7752011-11-21 22:52:58 +01009188 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009189 exc = NULL;
9190 raise_encode_exception(&exc, "decimal", unicode,
9191 startpos, startpos+1,
9192 "invalid decimal Unicode string");
9193 Py_XDECREF(exc);
9194 Py_DECREF(unicode);
9195 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009196 }
9197 /* 0-terminate the output string */
9198 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009199 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009200 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009201}
9202
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203/* --- Helpers ------------------------------------------------------------ */
9204
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009205/* helper macro to fixup start/end slice values */
9206#define ADJUST_INDICES(start, end, len) \
9207 if (end > len) \
9208 end = len; \
9209 else if (end < 0) { \
9210 end += len; \
9211 if (end < 0) \
9212 end = 0; \
9213 } \
9214 if (start < 0) { \
9215 start += len; \
9216 if (start < 0) \
9217 start = 0; \
9218 }
9219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009221any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009223 Py_ssize_t end,
9224 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009226 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009227 void *buf1, *buf2;
9228 Py_ssize_t len1, len2, result;
9229
9230 kind1 = PyUnicode_KIND(s1);
9231 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009232 if (kind1 < kind2)
9233 return -1;
9234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 len1 = PyUnicode_GET_LENGTH(s1);
9236 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009237 ADJUST_INDICES(start, end, len1);
9238 if (end - start < len2)
9239 return -1;
9240
9241 buf1 = PyUnicode_DATA(s1);
9242 buf2 = PyUnicode_DATA(s2);
9243 if (len2 == 1) {
9244 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9245 result = findchar((const char *)buf1 + kind1*start,
9246 kind1, end - start, ch, direction);
9247 if (result == -1)
9248 return -1;
9249 else
9250 return start + result;
9251 }
9252
9253 if (kind2 != kind1) {
9254 buf2 = _PyUnicode_AsKind(s2, kind1);
9255 if (!buf2)
9256 return -2;
9257 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258
Victor Stinner794d5672011-10-10 03:21:36 +02009259 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009260 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009261 case PyUnicode_1BYTE_KIND:
9262 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9263 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9264 else
9265 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9266 break;
9267 case PyUnicode_2BYTE_KIND:
9268 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9269 break;
9270 case PyUnicode_4BYTE_KIND:
9271 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9272 break;
9273 default:
9274 assert(0); result = -2;
9275 }
9276 }
9277 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009278 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009279 case PyUnicode_1BYTE_KIND:
9280 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9281 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9282 else
9283 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9284 break;
9285 case PyUnicode_2BYTE_KIND:
9286 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9287 break;
9288 case PyUnicode_4BYTE_KIND:
9289 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9290 break;
9291 default:
9292 assert(0); result = -2;
9293 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 }
9295
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009296 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 PyMem_Free(buf2);
9298
9299 return result;
9300}
9301
9302Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009303_PyUnicode_InsertThousandsGrouping(
9304 PyObject *unicode, Py_ssize_t index,
9305 Py_ssize_t n_buffer,
9306 void *digits, Py_ssize_t n_digits,
9307 Py_ssize_t min_width,
9308 const char *grouping, PyObject *thousands_sep,
9309 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009310{
Victor Stinner41a863c2012-02-24 00:37:51 +01009311 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009312 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009313 Py_ssize_t thousands_sep_len;
9314 Py_ssize_t len;
9315
9316 if (unicode != NULL) {
9317 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009318 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009319 }
9320 else {
9321 kind = PyUnicode_1BYTE_KIND;
9322 data = NULL;
9323 }
9324 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9325 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9326 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9327 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009328 if (thousands_sep_kind < kind) {
9329 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9330 if (!thousands_sep_data)
9331 return -1;
9332 }
9333 else {
9334 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9335 if (!data)
9336 return -1;
9337 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009338 }
9339
Benjamin Petersonead6b532011-12-20 17:23:42 -06009340 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009342 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009343 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009344 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009346 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009347 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009348 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009349 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009350 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009351 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009352 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009354 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009355 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009356 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009357 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009358 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009360 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009361 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009362 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009363 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009364 break;
9365 default:
9366 assert(0);
9367 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009369 if (unicode != NULL && thousands_sep_kind != kind) {
9370 if (thousands_sep_kind < kind)
9371 PyMem_Free(thousands_sep_data);
9372 else
9373 PyMem_Free(data);
9374 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009375 if (unicode == NULL) {
9376 *maxchar = 127;
9377 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009378 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009379 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009380 }
9381 }
9382 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383}
9384
9385
Alexander Belopolsky40018472011-02-26 01:02:56 +00009386Py_ssize_t
9387PyUnicode_Count(PyObject *str,
9388 PyObject *substr,
9389 Py_ssize_t start,
9390 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009392 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009393 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394 void *buf1 = NULL, *buf2 = NULL;
9395 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009396
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009397 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009398 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009399
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009400 kind1 = PyUnicode_KIND(str);
9401 kind2 = PyUnicode_KIND(substr);
9402 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009403 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009404
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009405 len1 = PyUnicode_GET_LENGTH(str);
9406 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009408 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009409 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009410
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009411 buf1 = PyUnicode_DATA(str);
9412 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009413 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009414 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009415 if (!buf2)
9416 goto onError;
9417 }
9418
9419 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009421 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009422 result = asciilib_count(
9423 ((Py_UCS1*)buf1) + start, end - start,
9424 buf2, len2, PY_SSIZE_T_MAX
9425 );
9426 else
9427 result = ucs1lib_count(
9428 ((Py_UCS1*)buf1) + start, end - start,
9429 buf2, len2, PY_SSIZE_T_MAX
9430 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 break;
9432 case PyUnicode_2BYTE_KIND:
9433 result = ucs2lib_count(
9434 ((Py_UCS2*)buf1) + start, end - start,
9435 buf2, len2, PY_SSIZE_T_MAX
9436 );
9437 break;
9438 case PyUnicode_4BYTE_KIND:
9439 result = ucs4lib_count(
9440 ((Py_UCS4*)buf1) + start, end - start,
9441 buf2, len2, PY_SSIZE_T_MAX
9442 );
9443 break;
9444 default:
9445 assert(0); result = 0;
9446 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009447
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009448 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 PyMem_Free(buf2);
9450
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009453 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009454 PyMem_Free(buf2);
9455 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456}
9457
Alexander Belopolsky40018472011-02-26 01:02:56 +00009458Py_ssize_t
9459PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009460 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009461 Py_ssize_t start,
9462 Py_ssize_t end,
9463 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009465 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009466 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009467
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009468 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009469}
9470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471Py_ssize_t
9472PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9473 Py_ssize_t start, Py_ssize_t end,
9474 int direction)
9475{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009477 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478 if (PyUnicode_READY(str) == -1)
9479 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009480 if (start < 0 || end < 0) {
9481 PyErr_SetString(PyExc_IndexError, "string index out of range");
9482 return -2;
9483 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 if (end > PyUnicode_GET_LENGTH(str))
9485 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009486 if (start >= end)
9487 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009489 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9490 kind, end-start, ch, direction);
9491 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009493 else
9494 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495}
9496
Alexander Belopolsky40018472011-02-26 01:02:56 +00009497static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009498tailmatch(PyObject *self,
9499 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009500 Py_ssize_t start,
9501 Py_ssize_t end,
9502 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 int kind_self;
9505 int kind_sub;
9506 void *data_self;
9507 void *data_sub;
9508 Py_ssize_t offset;
9509 Py_ssize_t i;
9510 Py_ssize_t end_sub;
9511
9512 if (PyUnicode_READY(self) == -1 ||
9513 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009514 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9517 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009519 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009521 if (PyUnicode_GET_LENGTH(substring) == 0)
9522 return 1;
9523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524 kind_self = PyUnicode_KIND(self);
9525 data_self = PyUnicode_DATA(self);
9526 kind_sub = PyUnicode_KIND(substring);
9527 data_sub = PyUnicode_DATA(substring);
9528 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9529
9530 if (direction > 0)
9531 offset = end;
9532 else
9533 offset = start;
9534
9535 if (PyUnicode_READ(kind_self, data_self, offset) ==
9536 PyUnicode_READ(kind_sub, data_sub, 0) &&
9537 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9538 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9539 /* If both are of the same kind, memcmp is sufficient */
9540 if (kind_self == kind_sub) {
9541 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009542 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 data_sub,
9544 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009545 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009547 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548 else {
9549 /* We do not need to compare 0 and len(substring)-1 because
9550 the if statement above ensured already that they are equal
9551 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 for (i = 1; i < end_sub; ++i) {
9553 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9554 PyUnicode_READ(kind_sub, data_sub, i))
9555 return 0;
9556 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009559 }
9560
9561 return 0;
9562}
9563
Alexander Belopolsky40018472011-02-26 01:02:56 +00009564Py_ssize_t
9565PyUnicode_Tailmatch(PyObject *str,
9566 PyObject *substr,
9567 Py_ssize_t start,
9568 Py_ssize_t end,
9569 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009571 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009572 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009573
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009574 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009575}
9576
Guido van Rossumd57fd912000-03-10 22:53:23 +00009577/* Apply fixfct filter to the Unicode object self and return a
9578 reference to the modified object */
9579
Alexander Belopolsky40018472011-02-26 01:02:56 +00009580static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009581fixup(PyObject *self,
9582 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 PyObject *u;
9585 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009586 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009587
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009588 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009590 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009591 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 /* fix functions return the new maximum character in a string,
9594 if the kind of the resulting unicode object does not change,
9595 everything is fine. Otherwise we need to change the string kind
9596 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009597 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009598
9599 if (maxchar_new == 0) {
9600 /* no changes */;
9601 if (PyUnicode_CheckExact(self)) {
9602 Py_DECREF(u);
9603 Py_INCREF(self);
9604 return self;
9605 }
9606 else
9607 return u;
9608 }
9609
Victor Stinnere6abb482012-05-02 01:15:40 +02009610 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611
Victor Stinnereaab6042011-12-11 22:22:39 +01009612 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009614
9615 /* In case the maximum character changed, we need to
9616 convert the string to the new category. */
9617 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9618 if (v == NULL) {
9619 Py_DECREF(u);
9620 return NULL;
9621 }
9622 if (maxchar_new > maxchar_old) {
9623 /* If the maxchar increased so that the kind changed, not all
9624 characters are representable anymore and we need to fix the
9625 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009626 _PyUnicode_FastCopyCharacters(v, 0,
9627 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009628 maxchar_old = fixfct(v);
9629 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009630 }
9631 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009632 _PyUnicode_FastCopyCharacters(v, 0,
9633 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009635 Py_DECREF(u);
9636 assert(_PyUnicode_CheckConsistency(v, 1));
9637 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009638}
9639
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009640static PyObject *
9641ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9644 char *resdata, *data = PyUnicode_DATA(self);
9645 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009646
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647 res = PyUnicode_New(len, 127);
9648 if (res == NULL)
9649 return NULL;
9650 resdata = PyUnicode_DATA(res);
9651 if (lower)
9652 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009654 _Py_bytes_upper(resdata, data, len);
9655 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656}
9657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009660{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661 Py_ssize_t j;
9662 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009663 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009664 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009665
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009666 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9667
9668 where ! is a negation and \p{xxx} is a character with property xxx.
9669 */
9670 for (j = i - 1; j >= 0; j--) {
9671 c = PyUnicode_READ(kind, data, j);
9672 if (!_PyUnicode_IsCaseIgnorable(c))
9673 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009674 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009675 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9676 if (final_sigma) {
9677 for (j = i + 1; j < length; j++) {
9678 c = PyUnicode_READ(kind, data, j);
9679 if (!_PyUnicode_IsCaseIgnorable(c))
9680 break;
9681 }
9682 final_sigma = j == length || !_PyUnicode_IsCased(c);
9683 }
9684 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685}
9686
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687static int
9688lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9689 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 /* Obscure special case. */
9692 if (c == 0x3A3) {
9693 mapped[0] = handle_capital_sigma(kind, data, length, i);
9694 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009695 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009696 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697}
9698
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009699static Py_ssize_t
9700do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009701{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009702 Py_ssize_t i, k = 0;
9703 int n_res, j;
9704 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009705
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706 c = PyUnicode_READ(kind, data, 0);
9707 n_res = _PyUnicode_ToUpperFull(c, mapped);
9708 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009709 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009710 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009712 for (i = 1; i < length; i++) {
9713 c = PyUnicode_READ(kind, data, i);
9714 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9715 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009716 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009717 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009718 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009719 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009720 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009721}
9722
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723static Py_ssize_t
9724do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9725 Py_ssize_t i, k = 0;
9726
9727 for (i = 0; i < length; i++) {
9728 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9729 int n_res, j;
9730 if (Py_UNICODE_ISUPPER(c)) {
9731 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9732 }
9733 else if (Py_UNICODE_ISLOWER(c)) {
9734 n_res = _PyUnicode_ToUpperFull(c, mapped);
9735 }
9736 else {
9737 n_res = 1;
9738 mapped[0] = c;
9739 }
9740 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009741 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742 res[k++] = mapped[j];
9743 }
9744 }
9745 return k;
9746}
9747
9748static Py_ssize_t
9749do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9750 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009751{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009752 Py_ssize_t i, k = 0;
9753
9754 for (i = 0; i < length; i++) {
9755 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9756 int n_res, j;
9757 if (lower)
9758 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9759 else
9760 n_res = _PyUnicode_ToUpperFull(c, mapped);
9761 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009762 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009763 res[k++] = mapped[j];
9764 }
9765 }
9766 return k;
9767}
9768
9769static Py_ssize_t
9770do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9771{
9772 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9773}
9774
9775static Py_ssize_t
9776do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9777{
9778 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9779}
9780
Benjamin Petersone51757f2012-01-12 21:10:29 -05009781static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009782do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9783{
9784 Py_ssize_t i, k = 0;
9785
9786 for (i = 0; i < length; i++) {
9787 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9788 Py_UCS4 mapped[3];
9789 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9790 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009791 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009792 res[k++] = mapped[j];
9793 }
9794 }
9795 return k;
9796}
9797
9798static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009799do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9800{
9801 Py_ssize_t i, k = 0;
9802 int previous_is_cased;
9803
9804 previous_is_cased = 0;
9805 for (i = 0; i < length; i++) {
9806 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9807 Py_UCS4 mapped[3];
9808 int n_res, j;
9809
9810 if (previous_is_cased)
9811 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9812 else
9813 n_res = _PyUnicode_ToTitleFull(c, mapped);
9814
9815 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009816 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009817 res[k++] = mapped[j];
9818 }
9819
9820 previous_is_cased = _PyUnicode_IsCased(c);
9821 }
9822 return k;
9823}
9824
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009825static PyObject *
9826case_operation(PyObject *self,
9827 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9828{
9829 PyObject *res = NULL;
9830 Py_ssize_t length, newlength = 0;
9831 int kind, outkind;
9832 void *data, *outdata;
9833 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9834
Benjamin Petersoneea48462012-01-16 14:28:50 -05009835 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009836
9837 kind = PyUnicode_KIND(self);
9838 data = PyUnicode_DATA(self);
9839 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009840 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009841 PyErr_SetString(PyExc_OverflowError, "string is too long");
9842 return NULL;
9843 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009844 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009845 if (tmp == NULL)
9846 return PyErr_NoMemory();
9847 newlength = perform(kind, data, length, tmp, &maxchar);
9848 res = PyUnicode_New(newlength, maxchar);
9849 if (res == NULL)
9850 goto leave;
9851 tmpend = tmp + newlength;
9852 outdata = PyUnicode_DATA(res);
9853 outkind = PyUnicode_KIND(res);
9854 switch (outkind) {
9855 case PyUnicode_1BYTE_KIND:
9856 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9857 break;
9858 case PyUnicode_2BYTE_KIND:
9859 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9860 break;
9861 case PyUnicode_4BYTE_KIND:
9862 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9863 break;
9864 default:
9865 assert(0);
9866 break;
9867 }
9868 leave:
9869 PyMem_FREE(tmp);
9870 return res;
9871}
9872
Tim Peters8ce9f162004-08-27 01:49:32 +00009873PyObject *
9874PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009875{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009876 PyObject *res;
9877 PyObject *fseq;
9878 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009879 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009881 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009882 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009883 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009884 }
9885
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009886 /* NOTE: the following code can't call back into Python code,
9887 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009888 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009889
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009890 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009891 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009892 res = _PyUnicode_JoinArray(separator, items, seqlen);
9893 Py_DECREF(fseq);
9894 return res;
9895}
9896
9897PyObject *
9898_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9899{
9900 PyObject *res = NULL; /* the result */
9901 PyObject *sep = NULL;
9902 Py_ssize_t seplen;
9903 PyObject *item;
9904 Py_ssize_t sz, i, res_offset;
9905 Py_UCS4 maxchar;
9906 Py_UCS4 item_maxchar;
9907 int use_memcpy;
9908 unsigned char *res_data = NULL, *sep_data = NULL;
9909 PyObject *last_obj;
9910 unsigned int kind = 0;
9911
Tim Peters05eba1f2004-08-27 21:32:02 +00009912 /* If empty sequence, return u"". */
9913 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009914 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009915 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009916
Tim Peters05eba1f2004-08-27 21:32:02 +00009917 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009918 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009919 if (seqlen == 1) {
9920 if (PyUnicode_CheckExact(items[0])) {
9921 res = items[0];
9922 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009923 return res;
9924 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009925 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009926 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009927 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009929 /* Set up sep and seplen */
9930 if (separator == NULL) {
9931 /* fall back to a blank space separator */
9932 sep = PyUnicode_FromOrdinal(' ');
9933 if (!sep)
9934 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009935 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009936 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009937 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009938 else {
9939 if (!PyUnicode_Check(separator)) {
9940 PyErr_Format(PyExc_TypeError,
9941 "separator: expected str instance,"
9942 " %.80s found",
9943 Py_TYPE(separator)->tp_name);
9944 goto onError;
9945 }
9946 if (PyUnicode_READY(separator))
9947 goto onError;
9948 sep = separator;
9949 seplen = PyUnicode_GET_LENGTH(separator);
9950 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9951 /* inc refcount to keep this code path symmetric with the
9952 above case of a blank separator */
9953 Py_INCREF(sep);
9954 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009955 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009956 }
9957
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009958 /* There are at least two things to join, or else we have a subclass
9959 * of str in the sequence.
9960 * Do a pre-pass to figure out the total amount of space we'll
9961 * need (sz), and see whether all argument are strings.
9962 */
9963 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009964#ifdef Py_DEBUG
9965 use_memcpy = 0;
9966#else
9967 use_memcpy = 1;
9968#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009969 for (i = 0; i < seqlen; i++) {
9970 const Py_ssize_t old_sz = sz;
9971 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009972 if (!PyUnicode_Check(item)) {
9973 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009974 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009975 " %.80s found",
9976 i, Py_TYPE(item)->tp_name);
9977 goto onError;
9978 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979 if (PyUnicode_READY(item) == -1)
9980 goto onError;
9981 sz += PyUnicode_GET_LENGTH(item);
9982 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009983 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009984 if (i != 0)
9985 sz += seplen;
9986 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9987 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009988 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009989 goto onError;
9990 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009991 if (use_memcpy && last_obj != NULL) {
9992 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9993 use_memcpy = 0;
9994 }
9995 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009996 }
Tim Petersced69f82003-09-16 20:30:58 +00009997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009999 if (res == NULL)
10000 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010001
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010002 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010003#ifdef Py_DEBUG
10004 use_memcpy = 0;
10005#else
10006 if (use_memcpy) {
10007 res_data = PyUnicode_1BYTE_DATA(res);
10008 kind = PyUnicode_KIND(res);
10009 if (seplen != 0)
10010 sep_data = PyUnicode_1BYTE_DATA(sep);
10011 }
10012#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010013 if (use_memcpy) {
10014 for (i = 0; i < seqlen; ++i) {
10015 Py_ssize_t itemlen;
10016 item = items[i];
10017
10018 /* Copy item, and maybe the separator. */
10019 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010020 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010021 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010022 kind * seplen);
10023 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010024 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010025
10026 itemlen = PyUnicode_GET_LENGTH(item);
10027 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010028 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010029 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010030 kind * itemlen);
10031 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010032 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010033 }
10034 assert(res_data == PyUnicode_1BYTE_DATA(res)
10035 + kind * PyUnicode_GET_LENGTH(res));
10036 }
10037 else {
10038 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10039 Py_ssize_t itemlen;
10040 item = items[i];
10041
10042 /* Copy item, and maybe the separator. */
10043 if (i && seplen != 0) {
10044 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10045 res_offset += seplen;
10046 }
10047
10048 itemlen = PyUnicode_GET_LENGTH(item);
10049 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010050 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010051 res_offset += itemlen;
10052 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010053 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010054 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010055 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010058 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010060
Benjamin Peterson29060642009-01-31 22:14:21 +000010061 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010063 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010064 return NULL;
10065}
10066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067#define FILL(kind, data, value, start, length) \
10068 do { \
10069 Py_ssize_t i_ = 0; \
10070 assert(kind != PyUnicode_WCHAR_KIND); \
10071 switch ((kind)) { \
10072 case PyUnicode_1BYTE_KIND: { \
10073 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010074 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075 break; \
10076 } \
10077 case PyUnicode_2BYTE_KIND: { \
10078 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10079 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10080 break; \
10081 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010082 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10084 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10085 break; \
10086 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010087 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 } \
10089 } while (0)
10090
Victor Stinnerd3f08822012-05-29 12:57:52 +020010091void
10092_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10093 Py_UCS4 fill_char)
10094{
10095 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10096 const void *data = PyUnicode_DATA(unicode);
10097 assert(PyUnicode_IS_READY(unicode));
10098 assert(unicode_modifiable(unicode));
10099 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10100 assert(start >= 0);
10101 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10102 FILL(kind, data, fill_char, start, length);
10103}
10104
Victor Stinner3fe55312012-01-04 00:33:50 +010010105Py_ssize_t
10106PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10107 Py_UCS4 fill_char)
10108{
10109 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010110
10111 if (!PyUnicode_Check(unicode)) {
10112 PyErr_BadInternalCall();
10113 return -1;
10114 }
10115 if (PyUnicode_READY(unicode) == -1)
10116 return -1;
10117 if (unicode_check_modifiable(unicode))
10118 return -1;
10119
Victor Stinnerd3f08822012-05-29 12:57:52 +020010120 if (start < 0) {
10121 PyErr_SetString(PyExc_IndexError, "string index out of range");
10122 return -1;
10123 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010124 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10125 PyErr_SetString(PyExc_ValueError,
10126 "fill character is bigger than "
10127 "the string maximum character");
10128 return -1;
10129 }
10130
10131 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10132 length = Py_MIN(maxlen, length);
10133 if (length <= 0)
10134 return 0;
10135
Victor Stinnerd3f08822012-05-29 12:57:52 +020010136 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010137 return length;
10138}
10139
Victor Stinner9310abb2011-10-05 00:59:23 +020010140static PyObject *
10141pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010142 Py_ssize_t left,
10143 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 PyObject *u;
10147 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010148 int kind;
10149 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010150
10151 if (left < 0)
10152 left = 0;
10153 if (right < 0)
10154 right = 0;
10155
Victor Stinnerc4b49542011-12-11 22:44:26 +010010156 if (left == 0 && right == 0)
10157 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10160 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010161 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10162 return NULL;
10163 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010165 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010167 if (!u)
10168 return NULL;
10169
10170 kind = PyUnicode_KIND(u);
10171 data = PyUnicode_DATA(u);
10172 if (left)
10173 FILL(kind, data, fill, 0, left);
10174 if (right)
10175 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010176 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010177 assert(_PyUnicode_CheckConsistency(u, 1));
10178 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179}
10180
Alexander Belopolsky40018472011-02-26 01:02:56 +000010181PyObject *
10182PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010184 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010185
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010186 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010187 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010188
Benjamin Petersonead6b532011-12-20 17:23:42 -060010189 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 if (PyUnicode_IS_ASCII(string))
10192 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010193 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010194 PyUnicode_GET_LENGTH(string), keepends);
10195 else
10196 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010198 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 break;
10200 case PyUnicode_2BYTE_KIND:
10201 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 PyUnicode_GET_LENGTH(string), keepends);
10204 break;
10205 case PyUnicode_4BYTE_KIND:
10206 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010207 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 PyUnicode_GET_LENGTH(string), keepends);
10209 break;
10210 default:
10211 assert(0);
10212 list = 0;
10213 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215}
10216
Alexander Belopolsky40018472011-02-26 01:02:56 +000010217static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010218split(PyObject *self,
10219 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010220 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010222 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 void *buf1, *buf2;
10224 Py_ssize_t len1, len2;
10225 PyObject* out;
10226
Guido van Rossumd57fd912000-03-10 22:53:23 +000010227 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010228 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 if (PyUnicode_READY(self) == -1)
10231 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010234 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010236 if (PyUnicode_IS_ASCII(self))
10237 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010239 PyUnicode_GET_LENGTH(self), maxcount
10240 );
10241 else
10242 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010243 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010244 PyUnicode_GET_LENGTH(self), maxcount
10245 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 case PyUnicode_2BYTE_KIND:
10247 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 PyUnicode_GET_LENGTH(self), maxcount
10250 );
10251 case PyUnicode_4BYTE_KIND:
10252 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010253 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 PyUnicode_GET_LENGTH(self), maxcount
10255 );
10256 default:
10257 assert(0);
10258 return NULL;
10259 }
10260
10261 if (PyUnicode_READY(substring) == -1)
10262 return NULL;
10263
10264 kind1 = PyUnicode_KIND(self);
10265 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 len1 = PyUnicode_GET_LENGTH(self);
10267 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010268 if (kind1 < kind2 || len1 < len2) {
10269 out = PyList_New(1);
10270 if (out == NULL)
10271 return NULL;
10272 Py_INCREF(self);
10273 PyList_SET_ITEM(out, 0, self);
10274 return out;
10275 }
10276 buf1 = PyUnicode_DATA(self);
10277 buf2 = PyUnicode_DATA(substring);
10278 if (kind2 != kind1) {
10279 buf2 = _PyUnicode_AsKind(substring, kind1);
10280 if (!buf2)
10281 return NULL;
10282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010284 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010286 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10287 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010288 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010289 else
10290 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010291 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 break;
10293 case PyUnicode_2BYTE_KIND:
10294 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010295 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 break;
10297 case PyUnicode_4BYTE_KIND:
10298 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010299 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 break;
10301 default:
10302 out = NULL;
10303 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010304 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 PyMem_Free(buf2);
10306 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307}
10308
Alexander Belopolsky40018472011-02-26 01:02:56 +000010309static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010310rsplit(PyObject *self,
10311 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010312 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010313{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010314 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 void *buf1, *buf2;
10316 Py_ssize_t len1, len2;
10317 PyObject* out;
10318
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010319 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010320 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 if (PyUnicode_READY(self) == -1)
10323 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010326 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010328 if (PyUnicode_IS_ASCII(self))
10329 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010330 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010331 PyUnicode_GET_LENGTH(self), maxcount
10332 );
10333 else
10334 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010335 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010336 PyUnicode_GET_LENGTH(self), maxcount
10337 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 case PyUnicode_2BYTE_KIND:
10339 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010340 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 PyUnicode_GET_LENGTH(self), maxcount
10342 );
10343 case PyUnicode_4BYTE_KIND:
10344 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010345 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 PyUnicode_GET_LENGTH(self), maxcount
10347 );
10348 default:
10349 assert(0);
10350 return NULL;
10351 }
10352
10353 if (PyUnicode_READY(substring) == -1)
10354 return NULL;
10355
10356 kind1 = PyUnicode_KIND(self);
10357 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 len1 = PyUnicode_GET_LENGTH(self);
10359 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010360 if (kind1 < kind2 || len1 < len2) {
10361 out = PyList_New(1);
10362 if (out == NULL)
10363 return NULL;
10364 Py_INCREF(self);
10365 PyList_SET_ITEM(out, 0, self);
10366 return out;
10367 }
10368 buf1 = PyUnicode_DATA(self);
10369 buf2 = PyUnicode_DATA(substring);
10370 if (kind2 != kind1) {
10371 buf2 = _PyUnicode_AsKind(substring, kind1);
10372 if (!buf2)
10373 return NULL;
10374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010376 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010378 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10379 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010380 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010381 else
10382 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010383 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 break;
10385 case PyUnicode_2BYTE_KIND:
10386 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010387 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 break;
10389 case PyUnicode_4BYTE_KIND:
10390 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010391 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 break;
10393 default:
10394 out = NULL;
10395 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010396 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 PyMem_Free(buf2);
10398 return out;
10399}
10400
10401static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010402anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10403 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010405 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010407 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10408 return asciilib_find(buf1, len1, buf2, len2, offset);
10409 else
10410 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 case PyUnicode_2BYTE_KIND:
10412 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10413 case PyUnicode_4BYTE_KIND:
10414 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10415 }
10416 assert(0);
10417 return -1;
10418}
10419
10420static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010421anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10422 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010424 switch (kind) {
10425 case PyUnicode_1BYTE_KIND:
10426 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10427 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10428 else
10429 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10430 case PyUnicode_2BYTE_KIND:
10431 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10432 case PyUnicode_4BYTE_KIND:
10433 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10434 }
10435 assert(0);
10436 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010437}
10438
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010439static void
10440replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10441 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10442{
10443 int kind = PyUnicode_KIND(u);
10444 void *data = PyUnicode_DATA(u);
10445 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10446 if (kind == PyUnicode_1BYTE_KIND) {
10447 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10448 (Py_UCS1 *)data + len,
10449 u1, u2, maxcount);
10450 }
10451 else if (kind == PyUnicode_2BYTE_KIND) {
10452 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10453 (Py_UCS2 *)data + len,
10454 u1, u2, maxcount);
10455 }
10456 else {
10457 assert(kind == PyUnicode_4BYTE_KIND);
10458 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10459 (Py_UCS4 *)data + len,
10460 u1, u2, maxcount);
10461 }
10462}
10463
Alexander Belopolsky40018472011-02-26 01:02:56 +000010464static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465replace(PyObject *self, PyObject *str1,
10466 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 PyObject *u;
10469 char *sbuf = PyUnicode_DATA(self);
10470 char *buf1 = PyUnicode_DATA(str1);
10471 char *buf2 = PyUnicode_DATA(str2);
10472 int srelease = 0, release1 = 0, release2 = 0;
10473 int skind = PyUnicode_KIND(self);
10474 int kind1 = PyUnicode_KIND(str1);
10475 int kind2 = PyUnicode_KIND(str2);
10476 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10477 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10478 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010479 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010480 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481
10482 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010483 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010485 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486
Victor Stinner59de0ee2011-10-07 10:01:28 +020010487 if (str1 == str2)
10488 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010491 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10492 if (maxchar < maxchar_str1)
10493 /* substring too wide to be present */
10494 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010495 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10496 /* Replacing str1 with str2 may cause a maxchar reduction in the
10497 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010498 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010499 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010502 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010504 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010506 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010507 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010508 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010509
Victor Stinner69ed0f42013-04-09 21:48:24 +020010510 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010511 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010512 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010513 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010514 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010516 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010518
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010519 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10520 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010521 }
10522 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 int rkind = skind;
10524 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010525 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010527 if (kind1 < rkind) {
10528 /* widen substring */
10529 buf1 = _PyUnicode_AsKind(str1, rkind);
10530 if (!buf1) goto error;
10531 release1 = 1;
10532 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010533 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010534 if (i < 0)
10535 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 if (rkind > kind2) {
10537 /* widen replacement */
10538 buf2 = _PyUnicode_AsKind(str2, rkind);
10539 if (!buf2) goto error;
10540 release2 = 1;
10541 }
10542 else if (rkind < kind2) {
10543 /* widen self and buf1 */
10544 rkind = kind2;
10545 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010546 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 sbuf = _PyUnicode_AsKind(self, rkind);
10548 if (!sbuf) goto error;
10549 srelease = 1;
10550 buf1 = _PyUnicode_AsKind(str1, rkind);
10551 if (!buf1) goto error;
10552 release1 = 1;
10553 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010554 u = PyUnicode_New(slen, maxchar);
10555 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010557 assert(PyUnicode_KIND(u) == rkind);
10558 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010559
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010561 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010562 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010564 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010566
10567 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010568 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010570 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010571 if (i == -1)
10572 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010573 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010575 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010578 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010579 }
10580 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010582 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 int rkind = skind;
10584 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010587 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 buf1 = _PyUnicode_AsKind(str1, rkind);
10589 if (!buf1) goto error;
10590 release1 = 1;
10591 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010592 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 if (n == 0)
10594 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 buf2 = _PyUnicode_AsKind(str2, rkind);
10598 if (!buf2) goto error;
10599 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010602 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 rkind = kind2;
10604 sbuf = _PyUnicode_AsKind(self, rkind);
10605 if (!sbuf) goto error;
10606 srelease = 1;
10607 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010608 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 buf1 = _PyUnicode_AsKind(str1, rkind);
10610 if (!buf1) goto error;
10611 release1 = 1;
10612 }
10613 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10614 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010615 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 PyErr_SetString(PyExc_OverflowError,
10617 "replace string is too long");
10618 goto error;
10619 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010620 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010621 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010622 _Py_INCREF_UNICODE_EMPTY();
10623 if (!unicode_empty)
10624 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010625 u = unicode_empty;
10626 goto done;
10627 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010628 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 PyErr_SetString(PyExc_OverflowError,
10630 "replace string is too long");
10631 goto error;
10632 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010633 u = PyUnicode_New(new_size, maxchar);
10634 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010636 assert(PyUnicode_KIND(u) == rkind);
10637 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 ires = i = 0;
10639 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010640 while (n-- > 0) {
10641 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010642 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010643 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010644 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010645 if (j == -1)
10646 break;
10647 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010649 memcpy(res + rkind * ires,
10650 sbuf + rkind * i,
10651 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010653 }
10654 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010656 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010658 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010660 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010665 memcpy(res + rkind * ires,
10666 sbuf + rkind * i,
10667 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010668 }
10669 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 /* interleave */
10671 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010672 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010674 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010676 if (--n <= 0)
10677 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010678 memcpy(res + rkind * ires,
10679 sbuf + rkind * i,
10680 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 ires++;
10682 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010683 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010684 memcpy(res + rkind * ires,
10685 sbuf + rkind * i,
10686 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010687 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010688 }
10689
10690 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010691 unicode_adjust_maxchar(&u);
10692 if (u == NULL)
10693 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010694 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010695
10696 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010697 if (srelease)
10698 PyMem_FREE(sbuf);
10699 if (release1)
10700 PyMem_FREE(buf1);
10701 if (release2)
10702 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010703 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010704 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010705
Benjamin Peterson29060642009-01-31 22:14:21 +000010706 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010707 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010708 if (srelease)
10709 PyMem_FREE(sbuf);
10710 if (release1)
10711 PyMem_FREE(buf1);
10712 if (release2)
10713 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010714 return unicode_result_unchanged(self);
10715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 error:
10717 if (srelease && sbuf)
10718 PyMem_FREE(sbuf);
10719 if (release1 && buf1)
10720 PyMem_FREE(buf1);
10721 if (release2 && buf2)
10722 PyMem_FREE(buf2);
10723 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724}
10725
10726/* --- Unicode Object Methods --------------------------------------------- */
10727
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010728PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010729 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730\n\
10731Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010732characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010733
10734static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010735unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010736{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010737 if (PyUnicode_READY(self) == -1)
10738 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010739 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740}
10741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010742PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010743 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744\n\
10745Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010746have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747
10748static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010749unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010751 if (PyUnicode_READY(self) == -1)
10752 return NULL;
10753 if (PyUnicode_GET_LENGTH(self) == 0)
10754 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010755 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756}
10757
Benjamin Petersond5890c82012-01-14 13:23:30 -050010758PyDoc_STRVAR(casefold__doc__,
10759 "S.casefold() -> str\n\
10760\n\
10761Return a version of S suitable for caseless comparisons.");
10762
10763static PyObject *
10764unicode_casefold(PyObject *self)
10765{
10766 if (PyUnicode_READY(self) == -1)
10767 return NULL;
10768 if (PyUnicode_IS_ASCII(self))
10769 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010770 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010771}
10772
10773
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010774/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010775
10776static int
10777convert_uc(PyObject *obj, void *addr)
10778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010780
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010781 if (!PyUnicode_Check(obj)) {
10782 PyErr_Format(PyExc_TypeError,
10783 "The fill character must be a unicode character, "
10784 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010785 return 0;
10786 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010787 if (PyUnicode_READY(obj) < 0)
10788 return 0;
10789 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010790 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010791 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010792 return 0;
10793 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010794 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010795 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010796}
10797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010798PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010799 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010801Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010802done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010803
10804static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010805unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010807 Py_ssize_t marg, left;
10808 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 Py_UCS4 fillchar = ' ';
10810
Victor Stinnere9a29352011-10-01 02:14:59 +020010811 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010812 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813
Benjamin Petersonbac79492012-01-14 13:34:47 -050010814 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815 return NULL;
10816
Victor Stinnerc4b49542011-12-11 22:44:26 +010010817 if (PyUnicode_GET_LENGTH(self) >= width)
10818 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819
Victor Stinnerc4b49542011-12-11 22:44:26 +010010820 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821 left = marg / 2 + (marg & width & 1);
10822
Victor Stinner9310abb2011-10-05 00:59:23 +020010823 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010824}
10825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010826/* This function assumes that str1 and str2 are readied by the caller. */
10827
Marc-André Lemburge5034372000-08-08 08:04:29 +000010828static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010829unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010830{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010831#define COMPARE(TYPE1, TYPE2) \
10832 do { \
10833 TYPE1* p1 = (TYPE1 *)data1; \
10834 TYPE2* p2 = (TYPE2 *)data2; \
10835 TYPE1* end = p1 + len; \
10836 Py_UCS4 c1, c2; \
10837 for (; p1 != end; p1++, p2++) { \
10838 c1 = *p1; \
10839 c2 = *p2; \
10840 if (c1 != c2) \
10841 return (c1 < c2) ? -1 : 1; \
10842 } \
10843 } \
10844 while (0)
10845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010846 int kind1, kind2;
10847 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010848 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010850 kind1 = PyUnicode_KIND(str1);
10851 kind2 = PyUnicode_KIND(str2);
10852 data1 = PyUnicode_DATA(str1);
10853 data2 = PyUnicode_DATA(str2);
10854 len1 = PyUnicode_GET_LENGTH(str1);
10855 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010856 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010857
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010858 switch(kind1) {
10859 case PyUnicode_1BYTE_KIND:
10860 {
10861 switch(kind2) {
10862 case PyUnicode_1BYTE_KIND:
10863 {
10864 int cmp = memcmp(data1, data2, len);
10865 /* normalize result of memcmp() into the range [-1; 1] */
10866 if (cmp < 0)
10867 return -1;
10868 if (cmp > 0)
10869 return 1;
10870 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010871 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010872 case PyUnicode_2BYTE_KIND:
10873 COMPARE(Py_UCS1, Py_UCS2);
10874 break;
10875 case PyUnicode_4BYTE_KIND:
10876 COMPARE(Py_UCS1, Py_UCS4);
10877 break;
10878 default:
10879 assert(0);
10880 }
10881 break;
10882 }
10883 case PyUnicode_2BYTE_KIND:
10884 {
10885 switch(kind2) {
10886 case PyUnicode_1BYTE_KIND:
10887 COMPARE(Py_UCS2, Py_UCS1);
10888 break;
10889 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010890 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010891 COMPARE(Py_UCS2, Py_UCS2);
10892 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010893 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010894 case PyUnicode_4BYTE_KIND:
10895 COMPARE(Py_UCS2, Py_UCS4);
10896 break;
10897 default:
10898 assert(0);
10899 }
10900 break;
10901 }
10902 case PyUnicode_4BYTE_KIND:
10903 {
10904 switch(kind2) {
10905 case PyUnicode_1BYTE_KIND:
10906 COMPARE(Py_UCS4, Py_UCS1);
10907 break;
10908 case PyUnicode_2BYTE_KIND:
10909 COMPARE(Py_UCS4, Py_UCS2);
10910 break;
10911 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010912 {
10913#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10914 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10915 /* normalize result of wmemcmp() into the range [-1; 1] */
10916 if (cmp < 0)
10917 return -1;
10918 if (cmp > 0)
10919 return 1;
10920#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010921 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010922#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010923 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010924 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010925 default:
10926 assert(0);
10927 }
10928 break;
10929 }
10930 default:
10931 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010932 }
10933
Victor Stinner770e19e2012-10-04 22:59:45 +020010934 if (len1 == len2)
10935 return 0;
10936 if (len1 < len2)
10937 return -1;
10938 else
10939 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010940
10941#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010942}
10943
Benjamin Peterson621b4302016-09-09 13:54:34 -070010944static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010945unicode_compare_eq(PyObject *str1, PyObject *str2)
10946{
10947 int kind;
10948 void *data1, *data2;
10949 Py_ssize_t len;
10950 int cmp;
10951
Victor Stinnere5567ad2012-10-23 02:48:49 +020010952 len = PyUnicode_GET_LENGTH(str1);
10953 if (PyUnicode_GET_LENGTH(str2) != len)
10954 return 0;
10955 kind = PyUnicode_KIND(str1);
10956 if (PyUnicode_KIND(str2) != kind)
10957 return 0;
10958 data1 = PyUnicode_DATA(str1);
10959 data2 = PyUnicode_DATA(str2);
10960
10961 cmp = memcmp(data1, data2, len * kind);
10962 return (cmp == 0);
10963}
10964
10965
Alexander Belopolsky40018472011-02-26 01:02:56 +000010966int
10967PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010968{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10970 if (PyUnicode_READY(left) == -1 ||
10971 PyUnicode_READY(right) == -1)
10972 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010973
10974 /* a string is equal to itself */
10975 if (left == right)
10976 return 0;
10977
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010978 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010979 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010980 PyErr_Format(PyExc_TypeError,
10981 "Can't compare %.100s and %.100s",
10982 left->ob_type->tp_name,
10983 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984 return -1;
10985}
10986
Martin v. Löwis5b222132007-06-10 09:51:05 +000010987int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010988_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10989{
10990 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10991 if (right_str == NULL)
10992 return -1;
10993 return PyUnicode_Compare(left, right_str);
10994}
10995
10996int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010997PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10998{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999 Py_ssize_t i;
11000 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 Py_UCS4 chr;
11002
Victor Stinner910337b2011-10-03 03:20:16 +020011003 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 if (PyUnicode_READY(uni) == -1)
11005 return -1;
11006 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011007 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011008 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011009 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011010 size_t len, len2 = strlen(str);
11011 int cmp;
11012
11013 len = Py_MIN(len1, len2);
11014 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011015 if (cmp != 0) {
11016 if (cmp < 0)
11017 return -1;
11018 else
11019 return 1;
11020 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011021 if (len1 > len2)
11022 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011023 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011024 return -1; /* str is longer */
11025 return 0;
11026 }
11027 else {
11028 void *data = PyUnicode_DATA(uni);
11029 /* Compare Unicode string and source character set string */
11030 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011031 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011032 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11033 /* This check keeps Python strings that end in '\0' from comparing equal
11034 to C strings identical up to that point. */
11035 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11036 return 1; /* uni is longer */
11037 if (str[i])
11038 return -1; /* str is longer */
11039 return 0;
11040 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011041}
11042
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011043
Benjamin Peterson29060642009-01-31 22:14:21 +000011044#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011045 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011046
Alexander Belopolsky40018472011-02-26 01:02:56 +000011047PyObject *
11048PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011049{
11050 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011051 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011052
Victor Stinnere5567ad2012-10-23 02:48:49 +020011053 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11054 Py_RETURN_NOTIMPLEMENTED;
11055
11056 if (PyUnicode_READY(left) == -1 ||
11057 PyUnicode_READY(right) == -1)
11058 return NULL;
11059
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011060 if (left == right) {
11061 switch (op) {
11062 case Py_EQ:
11063 case Py_LE:
11064 case Py_GE:
11065 /* a string is equal to itself */
11066 v = Py_True;
11067 break;
11068 case Py_NE:
11069 case Py_LT:
11070 case Py_GT:
11071 v = Py_False;
11072 break;
11073 default:
11074 PyErr_BadArgument();
11075 return NULL;
11076 }
11077 }
11078 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011079 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011080 result ^= (op == Py_NE);
11081 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011082 }
11083 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011084 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011085
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011086 /* Convert the return value to a Boolean */
11087 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011088 case Py_LE:
11089 v = TEST_COND(result <= 0);
11090 break;
11091 case Py_GE:
11092 v = TEST_COND(result >= 0);
11093 break;
11094 case Py_LT:
11095 v = TEST_COND(result == -1);
11096 break;
11097 case Py_GT:
11098 v = TEST_COND(result == 1);
11099 break;
11100 default:
11101 PyErr_BadArgument();
11102 return NULL;
11103 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011104 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011105 Py_INCREF(v);
11106 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011107}
11108
Alexander Belopolsky40018472011-02-26 01:02:56 +000011109int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011110_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11111{
11112 return unicode_eq(aa, bb);
11113}
11114
11115int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011116PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011117{
Victor Stinner77282cb2013-04-14 19:22:47 +020011118 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 void *buf1, *buf2;
11120 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011121 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011122
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011123 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011124 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011125 "'in <string>' requires string as left operand, not %.100s",
11126 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011127 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011128 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011129 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011130 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011131 if (ensure_unicode(str) < 0)
11132 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011135 kind2 = PyUnicode_KIND(substr);
11136 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011137 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011139 len2 = PyUnicode_GET_LENGTH(substr);
11140 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011141 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011142 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011143 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011144 if (len2 == 1) {
11145 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11146 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011147 return result;
11148 }
11149 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011150 buf2 = _PyUnicode_AsKind(substr, kind1);
11151 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011152 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011153 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011154
Victor Stinner77282cb2013-04-14 19:22:47 +020011155 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 case PyUnicode_1BYTE_KIND:
11157 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11158 break;
11159 case PyUnicode_2BYTE_KIND:
11160 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11161 break;
11162 case PyUnicode_4BYTE_KIND:
11163 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11164 break;
11165 default:
11166 result = -1;
11167 assert(0);
11168 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011169
Victor Stinner77282cb2013-04-14 19:22:47 +020011170 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 PyMem_Free(buf2);
11172
Guido van Rossum403d68b2000-03-13 15:55:09 +000011173 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011174}
11175
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176/* Concat to string or Unicode object giving a new Unicode object. */
11177
Alexander Belopolsky40018472011-02-26 01:02:56 +000011178PyObject *
11179PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011181 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011182 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011183 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011184
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011185 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11186 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187
11188 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011189 if (left == unicode_empty)
11190 return PyUnicode_FromObject(right);
11191 if (right == unicode_empty)
11192 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011194 left_len = PyUnicode_GET_LENGTH(left);
11195 right_len = PyUnicode_GET_LENGTH(right);
11196 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011197 PyErr_SetString(PyExc_OverflowError,
11198 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011199 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011200 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011201 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011202
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011203 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11204 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011205 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011208 result = PyUnicode_New(new_len, maxchar);
11209 if (result == NULL)
11210 return NULL;
11211 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11212 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11213 assert(_PyUnicode_CheckConsistency(result, 1));
11214 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215}
11216
Walter Dörwald1ab83302007-05-18 17:15:44 +000011217void
Victor Stinner23e56682011-10-03 03:54:37 +020011218PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011219{
Victor Stinner23e56682011-10-03 03:54:37 +020011220 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011221 Py_UCS4 maxchar, maxchar2;
11222 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011223
11224 if (p_left == NULL) {
11225 if (!PyErr_Occurred())
11226 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011227 return;
11228 }
Victor Stinner23e56682011-10-03 03:54:37 +020011229 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011230 if (right == NULL || left == NULL
11231 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011232 if (!PyErr_Occurred())
11233 PyErr_BadInternalCall();
11234 goto error;
11235 }
11236
Benjamin Petersonbac79492012-01-14 13:34:47 -050011237 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011238 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011239 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011240 goto error;
11241
Victor Stinner488fa492011-12-12 00:01:39 +010011242 /* Shortcuts */
11243 if (left == unicode_empty) {
11244 Py_DECREF(left);
11245 Py_INCREF(right);
11246 *p_left = right;
11247 return;
11248 }
11249 if (right == unicode_empty)
11250 return;
11251
11252 left_len = PyUnicode_GET_LENGTH(left);
11253 right_len = PyUnicode_GET_LENGTH(right);
11254 if (left_len > PY_SSIZE_T_MAX - right_len) {
11255 PyErr_SetString(PyExc_OverflowError,
11256 "strings are too large to concat");
11257 goto error;
11258 }
11259 new_len = left_len + right_len;
11260
11261 if (unicode_modifiable(left)
11262 && PyUnicode_CheckExact(right)
11263 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011264 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11265 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011266 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011267 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011268 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11269 {
11270 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011271 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011272 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011273
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011274 /* copy 'right' into the newly allocated area of 'left' */
11275 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011276 }
Victor Stinner488fa492011-12-12 00:01:39 +010011277 else {
11278 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11279 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011280 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011281
Victor Stinner488fa492011-12-12 00:01:39 +010011282 /* Concat the two Unicode strings */
11283 res = PyUnicode_New(new_len, maxchar);
11284 if (res == NULL)
11285 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011286 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11287 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011288 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011289 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011290 }
11291 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011292 return;
11293
11294error:
Victor Stinner488fa492011-12-12 00:01:39 +010011295 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011296}
11297
11298void
11299PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11300{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011301 PyUnicode_Append(pleft, right);
11302 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011303}
11304
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011305/*
11306Wraps stringlib_parse_args_finds() and additionally ensures that the
11307first argument is a unicode object.
11308*/
11309
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011310static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011311parse_args_finds_unicode(const char * function_name, PyObject *args,
11312 PyObject **substring,
11313 Py_ssize_t *start, Py_ssize_t *end)
11314{
11315 if(stringlib_parse_args_finds(function_name, args, substring,
11316 start, end)) {
11317 if (ensure_unicode(*substring) < 0)
11318 return 0;
11319 return 1;
11320 }
11321 return 0;
11322}
11323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011324PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011325 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011327Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011328string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011329interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
11331static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011332unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011334 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011335 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011336 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011338 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 void *buf1, *buf2;
11340 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011342 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 kind1 = PyUnicode_KIND(self);
11346 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011347 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011348 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 len1 = PyUnicode_GET_LENGTH(self);
11351 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011353 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011354 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011355
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011356 buf1 = PyUnicode_DATA(self);
11357 buf2 = PyUnicode_DATA(substring);
11358 if (kind2 != kind1) {
11359 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011360 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011361 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011362 }
11363 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 case PyUnicode_1BYTE_KIND:
11365 iresult = ucs1lib_count(
11366 ((Py_UCS1*)buf1) + start, end - start,
11367 buf2, len2, PY_SSIZE_T_MAX
11368 );
11369 break;
11370 case PyUnicode_2BYTE_KIND:
11371 iresult = ucs2lib_count(
11372 ((Py_UCS2*)buf1) + start, end - start,
11373 buf2, len2, PY_SSIZE_T_MAX
11374 );
11375 break;
11376 case PyUnicode_4BYTE_KIND:
11377 iresult = ucs4lib_count(
11378 ((Py_UCS4*)buf1) + start, end - start,
11379 buf2, len2, PY_SSIZE_T_MAX
11380 );
11381 break;
11382 default:
11383 assert(0); iresult = 0;
11384 }
11385
11386 result = PyLong_FromSsize_t(iresult);
11387
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011388 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 return result;
11392}
11393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011394PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011395 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011397Encode S using the codec registered for encoding. Default encoding\n\
11398is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011399handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011400a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11401'xmlcharrefreplace' as well as any other name registered with\n\
11402codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403
11404static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011405unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011407 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408 char *encoding = NULL;
11409 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011410
Benjamin Peterson308d6372009-09-18 21:42:35 +000011411 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11412 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011414 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011415}
11416
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011417PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011418 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419\n\
11420Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011421If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422
11423static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011424unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011426 Py_ssize_t i, j, line_pos, src_len, incr;
11427 Py_UCS4 ch;
11428 PyObject *u;
11429 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011430 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011432 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011433 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
Ezio Melotti745d54d2013-11-16 19:10:57 +020011435 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11436 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438
Antoine Pitrou22425222011-10-04 19:10:51 +020011439 if (PyUnicode_READY(self) == -1)
11440 return NULL;
11441
Thomas Wouters7e474022000-07-16 12:04:32 +000011442 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011443 src_len = PyUnicode_GET_LENGTH(self);
11444 i = j = line_pos = 0;
11445 kind = PyUnicode_KIND(self);
11446 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011447 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011448 for (; i < src_len; i++) {
11449 ch = PyUnicode_READ(kind, src_data, i);
11450 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011451 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011453 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011455 goto overflow;
11456 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011458 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011461 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011462 goto overflow;
11463 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011465 if (ch == '\n' || ch == '\r')
11466 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011468 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011469 if (!found)
11470 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011471
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011473 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 if (!u)
11475 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011476 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477
Antoine Pitroue71d5742011-10-04 15:55:09 +020011478 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Antoine Pitroue71d5742011-10-04 15:55:09 +020011480 for (; i < src_len; i++) {
11481 ch = PyUnicode_READ(kind, src_data, i);
11482 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011484 incr = tabsize - (line_pos % tabsize);
11485 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011486 FILL(kind, dest_data, ' ', j, incr);
11487 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011489 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011491 line_pos++;
11492 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011493 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011494 if (ch == '\n' || ch == '\r')
11495 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 }
11498 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011499 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011500
Antoine Pitroue71d5742011-10-04 15:55:09 +020011501 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011502 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504}
11505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011506PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508\n\
11509Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011510such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511arguments start and end are interpreted as in slice notation.\n\
11512\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011513Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514
11515static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011518 /* initialize variables to prevent gcc warning */
11519 PyObject *substring = NULL;
11520 Py_ssize_t start = 0;
11521 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011522 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011524 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011527 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011528 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011529
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011530 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 if (result == -2)
11533 return NULL;
11534
Christian Heimes217cfd12007-12-02 14:31:20 +000011535 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536}
11537
11538static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011539unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011541 void *data;
11542 enum PyUnicode_Kind kind;
11543 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011544
11545 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11546 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011548 }
11549 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11550 PyErr_SetString(PyExc_IndexError, "string index out of range");
11551 return NULL;
11552 }
11553 kind = PyUnicode_KIND(self);
11554 data = PyUnicode_DATA(self);
11555 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011556 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557}
11558
Guido van Rossumc2504932007-09-18 19:42:40 +000011559/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011560 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011561static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011562unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563{
Guido van Rossumc2504932007-09-18 19:42:40 +000011564 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011565 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011566
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011567#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011568 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011569#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 if (_PyUnicode_HASH(self) != -1)
11571 return _PyUnicode_HASH(self);
11572 if (PyUnicode_READY(self) == -1)
11573 return -1;
11574 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011575 /*
11576 We make the hash of the empty string be 0, rather than using
11577 (prefix ^ suffix), since this slightly obfuscates the hash secret
11578 */
11579 if (len == 0) {
11580 _PyUnicode_HASH(self) = 0;
11581 return 0;
11582 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011583 x = _Py_HashBytes(PyUnicode_DATA(self),
11584 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011586 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587}
11588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011589PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011592Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593
11594static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011597 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011598 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011599 PyObject *substring = NULL;
11600 Py_ssize_t start = 0;
11601 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011603 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011606 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011609 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011611 if (result == -2)
11612 return NULL;
11613
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614 if (result < 0) {
11615 PyErr_SetString(PyExc_ValueError, "substring not found");
11616 return NULL;
11617 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011618
Christian Heimes217cfd12007-12-02 14:31:20 +000011619 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620}
11621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011622PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011625Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011626at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627
11628static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011629unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 Py_ssize_t i, length;
11632 int kind;
11633 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634 int cased;
11635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 if (PyUnicode_READY(self) == -1)
11637 return NULL;
11638 length = PyUnicode_GET_LENGTH(self);
11639 kind = PyUnicode_KIND(self);
11640 data = PyUnicode_DATA(self);
11641
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 if (length == 1)
11644 return PyBool_FromLong(
11645 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011647 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011650
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 for (i = 0; i < length; i++) {
11653 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011654
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11656 return PyBool_FromLong(0);
11657 else if (!cased && Py_UNICODE_ISLOWER(ch))
11658 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011660 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661}
11662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011663PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011666Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668
11669static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011670unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 Py_ssize_t i, length;
11673 int kind;
11674 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675 int cased;
11676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 if (PyUnicode_READY(self) == -1)
11678 return NULL;
11679 length = PyUnicode_GET_LENGTH(self);
11680 kind = PyUnicode_KIND(self);
11681 data = PyUnicode_DATA(self);
11682
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 if (length == 1)
11685 return PyBool_FromLong(
11686 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011688 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011690 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011691
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 for (i = 0; i < length; i++) {
11694 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011695
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11697 return PyBool_FromLong(0);
11698 else if (!cased && Py_UNICODE_ISUPPER(ch))
11699 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011701 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702}
11703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011704PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011705 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011707Return True if S is a titlecased string and there is at least one\n\
11708character in S, i.e. upper- and titlecase characters may only\n\
11709follow uncased characters and lowercase characters only cased ones.\n\
11710Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711
11712static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011713unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 Py_ssize_t i, length;
11716 int kind;
11717 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 int cased, previous_is_cased;
11719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 if (PyUnicode_READY(self) == -1)
11721 return NULL;
11722 length = PyUnicode_GET_LENGTH(self);
11723 kind = PyUnicode_KIND(self);
11724 data = PyUnicode_DATA(self);
11725
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011727 if (length == 1) {
11728 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11729 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11730 (Py_UNICODE_ISUPPER(ch) != 0));
11731 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011733 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011735 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011736
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737 cased = 0;
11738 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 for (i = 0; i < length; i++) {
11740 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011741
Benjamin Peterson29060642009-01-31 22:14:21 +000011742 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11743 if (previous_is_cased)
11744 return PyBool_FromLong(0);
11745 previous_is_cased = 1;
11746 cased = 1;
11747 }
11748 else if (Py_UNICODE_ISLOWER(ch)) {
11749 if (!previous_is_cased)
11750 return PyBool_FromLong(0);
11751 previous_is_cased = 1;
11752 cased = 1;
11753 }
11754 else
11755 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011757 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758}
11759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011760PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011761 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011763Return True if all characters in S are whitespace\n\
11764and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765
11766static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011767unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 Py_ssize_t i, length;
11770 int kind;
11771 void *data;
11772
11773 if (PyUnicode_READY(self) == -1)
11774 return NULL;
11775 length = PyUnicode_GET_LENGTH(self);
11776 kind = PyUnicode_KIND(self);
11777 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 if (length == 1)
11781 return PyBool_FromLong(
11782 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011784 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011788 for (i = 0; i < length; i++) {
11789 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011790 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011791 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011793 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794}
11795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011796PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011797 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011798\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011799Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011800and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011801
11802static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011803unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 Py_ssize_t i, length;
11806 int kind;
11807 void *data;
11808
11809 if (PyUnicode_READY(self) == -1)
11810 return NULL;
11811 length = PyUnicode_GET_LENGTH(self);
11812 kind = PyUnicode_KIND(self);
11813 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011814
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011815 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 if (length == 1)
11817 return PyBool_FromLong(
11818 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011819
11820 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011822 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011823
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 for (i = 0; i < length; i++) {
11825 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011826 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011827 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011828 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011829}
11830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011831PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011832 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011833\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011834Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011835and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011836
11837static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011838unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011839{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 int kind;
11841 void *data;
11842 Py_ssize_t len, i;
11843
11844 if (PyUnicode_READY(self) == -1)
11845 return NULL;
11846
11847 kind = PyUnicode_KIND(self);
11848 data = PyUnicode_DATA(self);
11849 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011851 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 if (len == 1) {
11853 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11854 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11855 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011856
11857 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 for (i = 0; i < len; i++) {
11862 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011863 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011865 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011866 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011867}
11868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011869PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011870 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011872Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874
11875static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011876unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011878 Py_ssize_t i, length;
11879 int kind;
11880 void *data;
11881
11882 if (PyUnicode_READY(self) == -1)
11883 return NULL;
11884 length = PyUnicode_GET_LENGTH(self);
11885 kind = PyUnicode_KIND(self);
11886 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (length == 1)
11890 return PyBool_FromLong(
11891 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011893 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011894 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011895 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011897 for (i = 0; i < length; i++) {
11898 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011901 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902}
11903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011904PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011907Return True if all characters in S are digits\n\
11908and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909
11910static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011911unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913 Py_ssize_t i, length;
11914 int kind;
11915 void *data;
11916
11917 if (PyUnicode_READY(self) == -1)
11918 return NULL;
11919 length = PyUnicode_GET_LENGTH(self);
11920 kind = PyUnicode_KIND(self);
11921 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 if (length == 1) {
11925 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11926 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11927 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011929 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011931 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011933 for (i = 0; i < length; i++) {
11934 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011935 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011937 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938}
11939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011940PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011941 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011943Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011944False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
11946static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011947unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 Py_ssize_t i, length;
11950 int kind;
11951 void *data;
11952
11953 if (PyUnicode_READY(self) == -1)
11954 return NULL;
11955 length = PyUnicode_GET_LENGTH(self);
11956 kind = PyUnicode_KIND(self);
11957 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (length == 1)
11961 return PyBool_FromLong(
11962 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011964 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011965 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011966 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 for (i = 0; i < length; i++) {
11969 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011970 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011972 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011973}
11974
Martin v. Löwis47383402007-08-15 07:32:56 +000011975int
11976PyUnicode_IsIdentifier(PyObject *self)
11977{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011978 int kind;
11979 void *data;
11980 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011981 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 if (PyUnicode_READY(self) == -1) {
11984 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011985 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011986 }
11987
11988 /* Special case for empty strings */
11989 if (PyUnicode_GET_LENGTH(self) == 0)
11990 return 0;
11991 kind = PyUnicode_KIND(self);
11992 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011993
11994 /* PEP 3131 says that the first character must be in
11995 XID_Start and subsequent characters in XID_Continue,
11996 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011997 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011998 letters, digits, underscore). However, given the current
11999 definition of XID_Start and XID_Continue, it is sufficient
12000 to check just for these, except that _ must be allowed
12001 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012003 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012004 return 0;
12005
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012006 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012008 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012009 return 1;
12010}
12011
12012PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012013 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012014\n\
12015Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012016to the language definition.\n\
12017\n\
12018Use keyword.iskeyword() to test for reserved identifiers\n\
12019such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012020
12021static PyObject*
12022unicode_isidentifier(PyObject *self)
12023{
12024 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12025}
12026
Georg Brandl559e5d72008-06-11 18:37:52 +000012027PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012028 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012029\n\
12030Return True if all characters in S are considered\n\
12031printable in repr() or S is empty, False otherwise.");
12032
12033static PyObject*
12034unicode_isprintable(PyObject *self)
12035{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 Py_ssize_t i, length;
12037 int kind;
12038 void *data;
12039
12040 if (PyUnicode_READY(self) == -1)
12041 return NULL;
12042 length = PyUnicode_GET_LENGTH(self);
12043 kind = PyUnicode_KIND(self);
12044 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012045
12046 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 if (length == 1)
12048 return PyBool_FromLong(
12049 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 for (i = 0; i < length; i++) {
12052 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012053 Py_RETURN_FALSE;
12054 }
12055 }
12056 Py_RETURN_TRUE;
12057}
12058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012059PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012060 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061\n\
12062Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012063iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064
12065static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012066unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012068 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069}
12070
Martin v. Löwis18e16552006-02-15 17:27:45 +000012071static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012072unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 if (PyUnicode_READY(self) == -1)
12075 return -1;
12076 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077}
12078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012079PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012082Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012083done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084
12085static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012086unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012088 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 Py_UCS4 fillchar = ' ';
12090
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012091 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092 return NULL;
12093
Benjamin Petersonbac79492012-01-14 13:34:47 -050012094 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012095 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096
Victor Stinnerc4b49542011-12-11 22:44:26 +010012097 if (PyUnicode_GET_LENGTH(self) >= width)
12098 return unicode_result_unchanged(self);
12099
12100 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101}
12102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012103PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012104 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012106Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107
12108static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012109unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012111 if (PyUnicode_READY(self) == -1)
12112 return NULL;
12113 if (PyUnicode_IS_ASCII(self))
12114 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012115 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116}
12117
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012118#define LEFTSTRIP 0
12119#define RIGHTSTRIP 1
12120#define BOTHSTRIP 2
12121
12122/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012123static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012124
12125#define STRIPNAME(i) (stripformat[i]+3)
12126
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012127/* externally visible for str.strip(unicode) */
12128PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012129_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012130{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 void *data;
12132 int kind;
12133 Py_ssize_t i, j, len;
12134 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012135 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12138 return NULL;
12139
12140 kind = PyUnicode_KIND(self);
12141 data = PyUnicode_DATA(self);
12142 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012143 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12145 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012146 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012147
Benjamin Peterson14339b62009-01-31 16:36:08 +000012148 i = 0;
12149 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012150 while (i < len) {
12151 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12152 if (!BLOOM(sepmask, ch))
12153 break;
12154 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12155 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012156 i++;
12157 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012159
Benjamin Peterson14339b62009-01-31 16:36:08 +000012160 j = len;
12161 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012162 j--;
12163 while (j >= i) {
12164 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12165 if (!BLOOM(sepmask, ch))
12166 break;
12167 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12168 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012169 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012170 }
12171
Benjamin Peterson29060642009-01-31 22:14:21 +000012172 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012173 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012174
Victor Stinner7931d9a2011-11-04 00:22:48 +010012175 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176}
12177
12178PyObject*
12179PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12180{
12181 unsigned char *data;
12182 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012183 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012184
Victor Stinnerde636f32011-10-01 03:55:54 +020012185 if (PyUnicode_READY(self) == -1)
12186 return NULL;
12187
Victor Stinner684d5fd2012-05-03 02:32:34 +020012188 length = PyUnicode_GET_LENGTH(self);
12189 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012190
Victor Stinner684d5fd2012-05-03 02:32:34 +020012191 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012192 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193
Victor Stinnerde636f32011-10-01 03:55:54 +020012194 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012195 PyErr_SetString(PyExc_IndexError, "string index out of range");
12196 return NULL;
12197 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012198 if (start >= length || end < start)
12199 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012200
Victor Stinner684d5fd2012-05-03 02:32:34 +020012201 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012202 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012203 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012204 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012205 }
12206 else {
12207 kind = PyUnicode_KIND(self);
12208 data = PyUnicode_1BYTE_DATA(self);
12209 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012210 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012211 length);
12212 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214
12215static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012216do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218 Py_ssize_t len, i, j;
12219
12220 if (PyUnicode_READY(self) == -1)
12221 return NULL;
12222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012224
Victor Stinnercc7af722013-04-09 22:39:24 +020012225 if (PyUnicode_IS_ASCII(self)) {
12226 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12227
12228 i = 0;
12229 if (striptype != RIGHTSTRIP) {
12230 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012231 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012232 if (!_Py_ascii_whitespace[ch])
12233 break;
12234 i++;
12235 }
12236 }
12237
12238 j = len;
12239 if (striptype != LEFTSTRIP) {
12240 j--;
12241 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012242 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012243 if (!_Py_ascii_whitespace[ch])
12244 break;
12245 j--;
12246 }
12247 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012248 }
12249 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012250 else {
12251 int kind = PyUnicode_KIND(self);
12252 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012253
Victor Stinnercc7af722013-04-09 22:39:24 +020012254 i = 0;
12255 if (striptype != RIGHTSTRIP) {
12256 while (i < len) {
12257 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12258 if (!Py_UNICODE_ISSPACE(ch))
12259 break;
12260 i++;
12261 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012262 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012263
12264 j = len;
12265 if (striptype != LEFTSTRIP) {
12266 j--;
12267 while (j >= i) {
12268 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12269 if (!Py_UNICODE_ISSPACE(ch))
12270 break;
12271 j--;
12272 }
12273 j++;
12274 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012275 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012276
Victor Stinner7931d9a2011-11-04 00:22:48 +010012277 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278}
12279
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012280
12281static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012282do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012283{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012284 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012285
Serhiy Storchakac6792272013-10-19 21:03:34 +030012286 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012287 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012288
Benjamin Peterson14339b62009-01-31 16:36:08 +000012289 if (sep != NULL && sep != Py_None) {
12290 if (PyUnicode_Check(sep))
12291 return _PyUnicode_XStrip(self, striptype, sep);
12292 else {
12293 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012294 "%s arg must be None or str",
12295 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012296 return NULL;
12297 }
12298 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012299
Benjamin Peterson14339b62009-01-31 16:36:08 +000012300 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012301}
12302
12303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012304PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012305 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012306\n\
12307Return a copy of the string S with leading and trailing\n\
12308whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012309If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012310
12311static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012312unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012313{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012314 if (PyTuple_GET_SIZE(args) == 0)
12315 return do_strip(self, BOTHSTRIP); /* Common case */
12316 else
12317 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012318}
12319
12320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012321PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012322 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012323\n\
12324Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012325If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012326
12327static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012328unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012329{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012330 if (PyTuple_GET_SIZE(args) == 0)
12331 return do_strip(self, LEFTSTRIP); /* Common case */
12332 else
12333 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012334}
12335
12336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012337PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012338 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012339\n\
12340Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012341If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012342
12343static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012344unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012345{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012346 if (PyTuple_GET_SIZE(args) == 0)
12347 return do_strip(self, RIGHTSTRIP); /* Common case */
12348 else
12349 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012350}
12351
12352
Guido van Rossumd57fd912000-03-10 22:53:23 +000012353static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012354unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012355{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012356 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012358
Serhiy Storchaka05997252013-01-26 12:14:02 +020012359 if (len < 1)
12360 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012361
Victor Stinnerc4b49542011-12-11 22:44:26 +010012362 /* no repeat, return original string */
12363 if (len == 1)
12364 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012365
Benjamin Petersonbac79492012-01-14 13:34:47 -050012366 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 return NULL;
12368
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012369 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012370 PyErr_SetString(PyExc_OverflowError,
12371 "repeated string is too long");
12372 return NULL;
12373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012375
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012376 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377 if (!u)
12378 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012379 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381 if (PyUnicode_GET_LENGTH(str) == 1) {
12382 const int kind = PyUnicode_KIND(str);
12383 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012384 if (kind == PyUnicode_1BYTE_KIND) {
12385 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012386 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012387 }
12388 else if (kind == PyUnicode_2BYTE_KIND) {
12389 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012390 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012391 ucs2[n] = fill_char;
12392 } else {
12393 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12394 assert(kind == PyUnicode_4BYTE_KIND);
12395 for (n = 0; n < len; ++n)
12396 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012397 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 }
12399 else {
12400 /* number of characters copied this far */
12401 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012402 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012404 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012406 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012407 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012408 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012409 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012410 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012411 }
12412
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012413 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012414 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012415}
12416
Alexander Belopolsky40018472011-02-26 01:02:56 +000012417PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012418PyUnicode_Replace(PyObject *str,
12419 PyObject *substr,
12420 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012421 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012423 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12424 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012425 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012426 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427}
12428
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012429PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012430 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012431\n\
12432Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012433old replaced by new. If the optional argument count is\n\
12434given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012435
12436static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439 PyObject *str1;
12440 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012441 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012443 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012445 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012446 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012447 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448}
12449
Alexander Belopolsky40018472011-02-26 01:02:56 +000012450static PyObject *
12451unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012453 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012454 Py_ssize_t isize;
12455 Py_ssize_t osize, squote, dquote, i, o;
12456 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012457 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012461 return NULL;
12462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012463 isize = PyUnicode_GET_LENGTH(unicode);
12464 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 /* Compute length of output, quote characters, and
12467 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012468 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 max = 127;
12470 squote = dquote = 0;
12471 ikind = PyUnicode_KIND(unicode);
12472 for (i = 0; i < isize; i++) {
12473 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012474 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012475 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012476 case '\'': squote++; break;
12477 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012479 incr = 2;
12480 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 default:
12482 /* Fast-path ASCII */
12483 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012484 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012486 ;
12487 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012489 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012490 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012492 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012493 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012494 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012496 if (osize > PY_SSIZE_T_MAX - incr) {
12497 PyErr_SetString(PyExc_OverflowError,
12498 "string is too long to generate repr");
12499 return NULL;
12500 }
12501 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 }
12503
12504 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012505 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012507 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012508 if (dquote)
12509 /* Both squote and dquote present. Use squote,
12510 and escape them */
12511 osize += squote;
12512 else
12513 quote = '"';
12514 }
Victor Stinner55c08782013-04-14 18:45:39 +020012515 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012516
12517 repr = PyUnicode_New(osize, max);
12518 if (repr == NULL)
12519 return NULL;
12520 okind = PyUnicode_KIND(repr);
12521 odata = PyUnicode_DATA(repr);
12522
12523 PyUnicode_WRITE(okind, odata, 0, quote);
12524 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012525 if (unchanged) {
12526 _PyUnicode_FastCopyCharacters(repr, 1,
12527 unicode, 0,
12528 isize);
12529 }
12530 else {
12531 for (i = 0, o = 1; i < isize; i++) {
12532 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533
Victor Stinner55c08782013-04-14 18:45:39 +020012534 /* Escape quotes and backslashes */
12535 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012536 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012538 continue;
12539 }
12540
12541 /* Map special whitespace to '\t', \n', '\r' */
12542 if (ch == '\t') {
12543 PyUnicode_WRITE(okind, odata, o++, '\\');
12544 PyUnicode_WRITE(okind, odata, o++, 't');
12545 }
12546 else if (ch == '\n') {
12547 PyUnicode_WRITE(okind, odata, o++, '\\');
12548 PyUnicode_WRITE(okind, odata, o++, 'n');
12549 }
12550 else if (ch == '\r') {
12551 PyUnicode_WRITE(okind, odata, o++, '\\');
12552 PyUnicode_WRITE(okind, odata, o++, 'r');
12553 }
12554
12555 /* Map non-printable US ASCII to '\xhh' */
12556 else if (ch < ' ' || ch == 0x7F) {
12557 PyUnicode_WRITE(okind, odata, o++, '\\');
12558 PyUnicode_WRITE(okind, odata, o++, 'x');
12559 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12560 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12561 }
12562
12563 /* Copy ASCII characters as-is */
12564 else if (ch < 0x7F) {
12565 PyUnicode_WRITE(okind, odata, o++, ch);
12566 }
12567
12568 /* Non-ASCII characters */
12569 else {
12570 /* Map Unicode whitespace and control characters
12571 (categories Z* and C* except ASCII space)
12572 */
12573 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12574 PyUnicode_WRITE(okind, odata, o++, '\\');
12575 /* Map 8-bit characters to '\xhh' */
12576 if (ch <= 0xff) {
12577 PyUnicode_WRITE(okind, odata, o++, 'x');
12578 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12579 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12580 }
12581 /* Map 16-bit characters to '\uxxxx' */
12582 else if (ch <= 0xffff) {
12583 PyUnicode_WRITE(okind, odata, o++, 'u');
12584 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12585 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12586 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12587 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12588 }
12589 /* Map 21-bit characters to '\U00xxxxxx' */
12590 else {
12591 PyUnicode_WRITE(okind, odata, o++, 'U');
12592 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12593 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12594 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12595 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12596 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12597 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12598 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12599 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12600 }
12601 }
12602 /* Copy characters as-is */
12603 else {
12604 PyUnicode_WRITE(okind, odata, o++, ch);
12605 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012606 }
12607 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012610 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012611 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612}
12613
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012614PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012615 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616\n\
12617Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012618such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619arguments start and end are interpreted as in slice notation.\n\
12620\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012621Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622
12623static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012626 /* initialize variables to prevent gcc warning */
12627 PyObject *substring = NULL;
12628 Py_ssize_t start = 0;
12629 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012630 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012632 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012633 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012635 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012638 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 if (result == -2)
12641 return NULL;
12642
Christian Heimes217cfd12007-12-02 14:31:20 +000012643 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644}
12645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012646PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012647 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012649Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650
12651static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012654 /* initialize variables to prevent gcc warning */
12655 PyObject *substring = NULL;
12656 Py_ssize_t start = 0;
12657 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012658 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012660 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012661 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012663 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012665
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012666 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 if (result == -2)
12669 return NULL;
12670
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671 if (result < 0) {
12672 PyErr_SetString(PyExc_ValueError, "substring not found");
12673 return NULL;
12674 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675
Christian Heimes217cfd12007-12-02 14:31:20 +000012676 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677}
12678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012679PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012680 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012682Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012683done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684
12685static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012686unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012688 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 Py_UCS4 fillchar = ' ';
12690
Victor Stinnere9a29352011-10-01 02:14:59 +020012691 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012693
Benjamin Petersonbac79492012-01-14 13:34:47 -050012694 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695 return NULL;
12696
Victor Stinnerc4b49542011-12-11 22:44:26 +010012697 if (PyUnicode_GET_LENGTH(self) >= width)
12698 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699
Victor Stinnerc4b49542011-12-11 22:44:26 +010012700 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701}
12702
Alexander Belopolsky40018472011-02-26 01:02:56 +000012703PyObject *
12704PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012706 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012707 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012709 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710}
12711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012712PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012713 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714\n\
12715Return a list of the words in S, using sep as the\n\
12716delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012717splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012718whitespace string is a separator and empty strings are\n\
12719removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720
12721static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012722unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012724 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012726 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012728 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12729 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730 return NULL;
12731
12732 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012734
12735 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012736 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012737
12738 PyErr_Format(PyExc_TypeError,
12739 "must be str or None, not %.100s",
12740 Py_TYPE(substring)->tp_name);
12741 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742}
12743
Thomas Wouters477c8d52006-05-27 19:21:47 +000012744PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012745PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012747 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012748 int kind1, kind2;
12749 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012751
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012752 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012754
Victor Stinner14f8f022011-10-05 20:58:25 +020012755 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012757 len1 = PyUnicode_GET_LENGTH(str_obj);
12758 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012759 if (kind1 < kind2 || len1 < len2) {
12760 _Py_INCREF_UNICODE_EMPTY();
12761 if (!unicode_empty)
12762 out = NULL;
12763 else {
12764 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12765 Py_DECREF(unicode_empty);
12766 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012767 return out;
12768 }
12769 buf1 = PyUnicode_DATA(str_obj);
12770 buf2 = PyUnicode_DATA(sep_obj);
12771 if (kind2 != kind1) {
12772 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12773 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012774 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012775 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012776
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012777 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012778 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012779 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12780 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12781 else
12782 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 break;
12784 case PyUnicode_2BYTE_KIND:
12785 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12786 break;
12787 case PyUnicode_4BYTE_KIND:
12788 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12789 break;
12790 default:
12791 assert(0);
12792 out = 0;
12793 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012794
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012795 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012796 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797
12798 return out;
12799}
12800
12801
12802PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012803PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012804{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012805 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012806 int kind1, kind2;
12807 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012809
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012810 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012811 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012812
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012813 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012815 len1 = PyUnicode_GET_LENGTH(str_obj);
12816 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012817 if (kind1 < kind2 || len1 < len2) {
12818 _Py_INCREF_UNICODE_EMPTY();
12819 if (!unicode_empty)
12820 out = NULL;
12821 else {
12822 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12823 Py_DECREF(unicode_empty);
12824 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012825 return out;
12826 }
12827 buf1 = PyUnicode_DATA(str_obj);
12828 buf2 = PyUnicode_DATA(sep_obj);
12829 if (kind2 != kind1) {
12830 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12831 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012832 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012833 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012835 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012837 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12838 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12839 else
12840 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841 break;
12842 case PyUnicode_2BYTE_KIND:
12843 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12844 break;
12845 case PyUnicode_4BYTE_KIND:
12846 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12847 break;
12848 default:
12849 assert(0);
12850 out = 0;
12851 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012852
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012853 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012855
12856 return out;
12857}
12858
12859PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012860 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012861\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012862Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012863the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012864found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012865
12866static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012867unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012868{
Victor Stinner9310abb2011-10-05 00:59:23 +020012869 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012870}
12871
12872PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012873 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012874\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012875Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012876the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012877separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878
12879static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012880unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012881{
Victor Stinner9310abb2011-10-05 00:59:23 +020012882 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012883}
12884
Alexander Belopolsky40018472011-02-26 01:02:56 +000012885PyObject *
12886PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012887{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012888 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012889 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012890
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012891 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012892}
12893
12894PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012895 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012896\n\
12897Return a list of the words in S, using sep as the\n\
12898delimiter string, starting at the end of the string and\n\
12899working to the front. If maxsplit is given, at most maxsplit\n\
12900splits are done. If sep is not specified, any whitespace string\n\
12901is a separator.");
12902
12903static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012904unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012905{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012906 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012907 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012908 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012909
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012910 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12911 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012912 return NULL;
12913
12914 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012916
12917 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012918 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012919
12920 PyErr_Format(PyExc_TypeError,
12921 "must be str or None, not %.100s",
12922 Py_TYPE(substring)->tp_name);
12923 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012924}
12925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012926PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012927 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012928\n\
12929Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012930Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012931is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932
12933static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012934unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012936 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012937 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012939 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12940 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012941 return NULL;
12942
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012943 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012944}
12945
12946static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012947PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012948{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012949 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950}
12951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012952PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954\n\
12955Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012956and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012957
12958static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012959unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012960{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012961 if (PyUnicode_READY(self) == -1)
12962 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012963 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012964}
12965
Larry Hastings61272b72014-01-07 12:41:53 -080012966/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012967
Larry Hastings31826802013-10-19 00:09:25 -070012968@staticmethod
12969str.maketrans as unicode_maketrans
12970
12971 x: object
12972
12973 y: unicode=NULL
12974
12975 z: unicode=NULL
12976
12977 /
12978
12979Return a translation table usable for str.translate().
12980
12981If there is only one argument, it must be a dictionary mapping Unicode
12982ordinals (integers) or characters to Unicode ordinals, strings or None.
12983Character keys will be then converted to ordinals.
12984If there are two arguments, they must be strings of equal length, and
12985in the resulting dictionary, each character in x will be mapped to the
12986character at the same position in y. If there is a third argument, it
12987must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012988[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012989
Larry Hastings31826802013-10-19 00:09:25 -070012990static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012991unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012992/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012993{
Georg Brandlceee0772007-11-27 23:48:05 +000012994 PyObject *new = NULL, *key, *value;
12995 Py_ssize_t i = 0;
12996 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012997
Georg Brandlceee0772007-11-27 23:48:05 +000012998 new = PyDict_New();
12999 if (!new)
13000 return NULL;
13001 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 int x_kind, y_kind, z_kind;
13003 void *x_data, *y_data, *z_data;
13004
Georg Brandlceee0772007-11-27 23:48:05 +000013005 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013006 if (!PyUnicode_Check(x)) {
13007 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13008 "be a string if there is a second argument");
13009 goto err;
13010 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013012 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13013 "arguments must have equal length");
13014 goto err;
13015 }
13016 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 x_kind = PyUnicode_KIND(x);
13018 y_kind = PyUnicode_KIND(y);
13019 x_data = PyUnicode_DATA(x);
13020 y_data = PyUnicode_DATA(y);
13021 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13022 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013023 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013024 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013025 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013026 if (!value) {
13027 Py_DECREF(key);
13028 goto err;
13029 }
Georg Brandlceee0772007-11-27 23:48:05 +000013030 res = PyDict_SetItem(new, key, value);
13031 Py_DECREF(key);
13032 Py_DECREF(value);
13033 if (res < 0)
13034 goto err;
13035 }
13036 /* create entries for deleting chars in z */
13037 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013038 z_kind = PyUnicode_KIND(z);
13039 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013040 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013041 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013042 if (!key)
13043 goto err;
13044 res = PyDict_SetItem(new, key, Py_None);
13045 Py_DECREF(key);
13046 if (res < 0)
13047 goto err;
13048 }
13049 }
13050 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013051 int kind;
13052 void *data;
13053
Georg Brandlceee0772007-11-27 23:48:05 +000013054 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013055 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013056 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13057 "to maketrans it must be a dict");
13058 goto err;
13059 }
13060 /* copy entries into the new dict, converting string keys to int keys */
13061 while (PyDict_Next(x, &i, &key, &value)) {
13062 if (PyUnicode_Check(key)) {
13063 /* convert string keys to integer keys */
13064 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013065 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013066 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13067 "table must be of length 1");
13068 goto err;
13069 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013070 kind = PyUnicode_KIND(key);
13071 data = PyUnicode_DATA(key);
13072 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013073 if (!newkey)
13074 goto err;
13075 res = PyDict_SetItem(new, newkey, value);
13076 Py_DECREF(newkey);
13077 if (res < 0)
13078 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013079 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013080 /* just keep integer keys */
13081 if (PyDict_SetItem(new, key, value) < 0)
13082 goto err;
13083 } else {
13084 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13085 "be strings or integers");
13086 goto err;
13087 }
13088 }
13089 }
13090 return new;
13091 err:
13092 Py_DECREF(new);
13093 return NULL;
13094}
13095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013096PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013097 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013099Return a copy of the string S in which each character has been mapped\n\
13100through the given translation table. The table must implement\n\
13101lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13102mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13103this operation raises LookupError, the character is left untouched.\n\
13104Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105
13106static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013109 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110}
13111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013112PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013113 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013115Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116
13117static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013118unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013120 if (PyUnicode_READY(self) == -1)
13121 return NULL;
13122 if (PyUnicode_IS_ASCII(self))
13123 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013124 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125}
13126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013127PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013128 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013130Pad a numeric string S with zeros on the left, to fill a field\n\
13131of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132
13133static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013134unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013136 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013137 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013138 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013139 int kind;
13140 void *data;
13141 Py_UCS4 chr;
13142
Martin v. Löwis18e16552006-02-15 17:27:45 +000013143 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013144 return NULL;
13145
Benjamin Petersonbac79492012-01-14 13:34:47 -050013146 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013147 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013148
Victor Stinnerc4b49542011-12-11 22:44:26 +010013149 if (PyUnicode_GET_LENGTH(self) >= width)
13150 return unicode_result_unchanged(self);
13151
13152 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013153
13154 u = pad(self, fill, 0, '0');
13155
Walter Dörwald068325e2002-04-15 13:36:47 +000013156 if (u == NULL)
13157 return NULL;
13158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 kind = PyUnicode_KIND(u);
13160 data = PyUnicode_DATA(u);
13161 chr = PyUnicode_READ(kind, data, fill);
13162
13163 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013165 PyUnicode_WRITE(kind, data, 0, chr);
13166 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167 }
13168
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013169 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013170 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172
13173#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013174static PyObject *
13175unicode__decimal2ascii(PyObject *self)
13176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013177 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013178}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179#endif
13180
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013181PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013182 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013184Return True if S starts with the specified prefix, False otherwise.\n\
13185With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013186With optional end, stop comparing S at that position.\n\
13187prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188
13189static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013190unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013191 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013193 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013194 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013195 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013196 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013197 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198
Jesus Ceaac451502011-04-20 17:09:23 +020013199 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013201 if (PyTuple_Check(subobj)) {
13202 Py_ssize_t i;
13203 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013204 substring = PyTuple_GET_ITEM(subobj, i);
13205 if (!PyUnicode_Check(substring)) {
13206 PyErr_Format(PyExc_TypeError,
13207 "tuple for startswith must only contain str, "
13208 "not %.100s",
13209 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013210 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013211 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013212 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013213 if (result == -1)
13214 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013215 if (result) {
13216 Py_RETURN_TRUE;
13217 }
13218 }
13219 /* nothing matched */
13220 Py_RETURN_FALSE;
13221 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013222 if (!PyUnicode_Check(subobj)) {
13223 PyErr_Format(PyExc_TypeError,
13224 "startswith first arg must be str or "
13225 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013227 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013228 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013229 if (result == -1)
13230 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013231 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232}
13233
13234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013235PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013236 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013238Return True if S ends with the specified suffix, False otherwise.\n\
13239With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013240With optional end, stop comparing S at that position.\n\
13241suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242
13243static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013244unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013247 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013248 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013249 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013250 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013251 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252
Jesus Ceaac451502011-04-20 17:09:23 +020013253 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013255 if (PyTuple_Check(subobj)) {
13256 Py_ssize_t i;
13257 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013258 substring = PyTuple_GET_ITEM(subobj, i);
13259 if (!PyUnicode_Check(substring)) {
13260 PyErr_Format(PyExc_TypeError,
13261 "tuple for endswith must only contain str, "
13262 "not %.100s",
13263 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013265 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013266 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013267 if (result == -1)
13268 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013269 if (result) {
13270 Py_RETURN_TRUE;
13271 }
13272 }
13273 Py_RETURN_FALSE;
13274 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013275 if (!PyUnicode_Check(subobj)) {
13276 PyErr_Format(PyExc_TypeError,
13277 "endswith first arg must be str or "
13278 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013280 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013281 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013282 if (result == -1)
13283 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013284 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013285}
13286
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013287static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013288_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013289{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013290 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13291 writer->data = PyUnicode_DATA(writer->buffer);
13292
13293 if (!writer->readonly) {
13294 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013295 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013296 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013297 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013298 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13299 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13300 writer->kind = PyUnicode_WCHAR_KIND;
13301 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13302
Victor Stinner8f674cc2013-04-17 23:02:17 +020013303 /* Copy-on-write mode: set buffer size to 0 so
13304 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13305 * next write. */
13306 writer->size = 0;
13307 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013308}
13309
Victor Stinnerd3f08822012-05-29 12:57:52 +020013310void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013311_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013312{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013313 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013314
13315 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013316 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013317
13318 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13319 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13320 writer->kind = PyUnicode_WCHAR_KIND;
13321 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013322}
13323
Victor Stinnerd3f08822012-05-29 12:57:52 +020013324int
13325_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13326 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013327{
13328 Py_ssize_t newlen;
13329 PyObject *newbuffer;
13330
Victor Stinner2740e462016-09-06 16:58:36 -070013331 assert(maxchar <= MAX_UNICODE);
13332
Victor Stinnerca9381e2015-09-22 00:58:32 +020013333 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013334 assert((maxchar > writer->maxchar && length >= 0)
13335 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013336
Victor Stinner202fdca2012-05-07 12:47:02 +020013337 if (length > PY_SSIZE_T_MAX - writer->pos) {
13338 PyErr_NoMemory();
13339 return -1;
13340 }
13341 newlen = writer->pos + length;
13342
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013343 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013344
Victor Stinnerd3f08822012-05-29 12:57:52 +020013345 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013346 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013347 if (writer->overallocate
13348 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13349 /* overallocate to limit the number of realloc() */
13350 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013351 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013352 if (newlen < writer->min_length)
13353 newlen = writer->min_length;
13354
Victor Stinnerd3f08822012-05-29 12:57:52 +020013355 writer->buffer = PyUnicode_New(newlen, maxchar);
13356 if (writer->buffer == NULL)
13357 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013358 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013359 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013360 if (writer->overallocate
13361 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13362 /* overallocate to limit the number of realloc() */
13363 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013364 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013365 if (newlen < writer->min_length)
13366 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013367
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013368 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013369 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013370 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013371 newbuffer = PyUnicode_New(newlen, maxchar);
13372 if (newbuffer == NULL)
13373 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013374 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13375 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013376 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013377 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013378 }
13379 else {
13380 newbuffer = resize_compact(writer->buffer, newlen);
13381 if (newbuffer == NULL)
13382 return -1;
13383 }
13384 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013385 }
13386 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013387 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013388 newbuffer = PyUnicode_New(writer->size, maxchar);
13389 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013390 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013391 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13392 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013393 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013394 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013395 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013396 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013397
13398#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013399}
13400
Victor Stinnerca9381e2015-09-22 00:58:32 +020013401int
13402_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13403 enum PyUnicode_Kind kind)
13404{
13405 Py_UCS4 maxchar;
13406
13407 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13408 assert(writer->kind < kind);
13409
13410 switch (kind)
13411 {
13412 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13413 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13414 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13415 default:
13416 assert(0 && "invalid kind");
13417 return -1;
13418 }
13419
13420 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13421}
13422
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013423static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013424_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013425{
Victor Stinner2740e462016-09-06 16:58:36 -070013426 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013427 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13428 return -1;
13429 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13430 writer->pos++;
13431 return 0;
13432}
13433
13434int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013435_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13436{
13437 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13438}
13439
13440int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013441_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13442{
13443 Py_UCS4 maxchar;
13444 Py_ssize_t len;
13445
13446 if (PyUnicode_READY(str) == -1)
13447 return -1;
13448 len = PyUnicode_GET_LENGTH(str);
13449 if (len == 0)
13450 return 0;
13451 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13452 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013453 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013454 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013455 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013456 Py_INCREF(str);
13457 writer->buffer = str;
13458 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013459 writer->pos += len;
13460 return 0;
13461 }
13462 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13463 return -1;
13464 }
13465 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13466 str, 0, len);
13467 writer->pos += len;
13468 return 0;
13469}
13470
Victor Stinnere215d962012-10-06 23:03:36 +020013471int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013472_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13473 Py_ssize_t start, Py_ssize_t end)
13474{
13475 Py_UCS4 maxchar;
13476 Py_ssize_t len;
13477
13478 if (PyUnicode_READY(str) == -1)
13479 return -1;
13480
13481 assert(0 <= start);
13482 assert(end <= PyUnicode_GET_LENGTH(str));
13483 assert(start <= end);
13484
13485 if (end == 0)
13486 return 0;
13487
13488 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13489 return _PyUnicodeWriter_WriteStr(writer, str);
13490
13491 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13492 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13493 else
13494 maxchar = writer->maxchar;
13495 len = end - start;
13496
13497 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13498 return -1;
13499
13500 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13501 str, start, len);
13502 writer->pos += len;
13503 return 0;
13504}
13505
13506int
Victor Stinner4a587072013-11-19 12:54:53 +010013507_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13508 const char *ascii, Py_ssize_t len)
13509{
13510 if (len == -1)
13511 len = strlen(ascii);
13512
13513 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13514
13515 if (writer->buffer == NULL && !writer->overallocate) {
13516 PyObject *str;
13517
13518 str = _PyUnicode_FromASCII(ascii, len);
13519 if (str == NULL)
13520 return -1;
13521
13522 writer->readonly = 1;
13523 writer->buffer = str;
13524 _PyUnicodeWriter_Update(writer);
13525 writer->pos += len;
13526 return 0;
13527 }
13528
13529 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13530 return -1;
13531
13532 switch (writer->kind)
13533 {
13534 case PyUnicode_1BYTE_KIND:
13535 {
13536 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13537 Py_UCS1 *data = writer->data;
13538
Christian Heimesf051e432016-09-13 20:22:02 +020013539 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013540 break;
13541 }
13542 case PyUnicode_2BYTE_KIND:
13543 {
13544 _PyUnicode_CONVERT_BYTES(
13545 Py_UCS1, Py_UCS2,
13546 ascii, ascii + len,
13547 (Py_UCS2 *)writer->data + writer->pos);
13548 break;
13549 }
13550 case PyUnicode_4BYTE_KIND:
13551 {
13552 _PyUnicode_CONVERT_BYTES(
13553 Py_UCS1, Py_UCS4,
13554 ascii, ascii + len,
13555 (Py_UCS4 *)writer->data + writer->pos);
13556 break;
13557 }
13558 default:
13559 assert(0);
13560 }
13561
13562 writer->pos += len;
13563 return 0;
13564}
13565
13566int
13567_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13568 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013569{
13570 Py_UCS4 maxchar;
13571
13572 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13573 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13574 return -1;
13575 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13576 writer->pos += len;
13577 return 0;
13578}
13579
Victor Stinnerd3f08822012-05-29 12:57:52 +020013580PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013581_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013582{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013583 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013584 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013585 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013586 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013587 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013588 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013589 str = writer->buffer;
13590 writer->buffer = NULL;
13591 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13592 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013593 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013594 if (writer->pos == 0) {
13595 Py_CLEAR(writer->buffer);
13596
13597 /* Get the empty Unicode string singleton ('') */
13598 _Py_INCREF_UNICODE_EMPTY();
13599 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013600 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013601 else {
13602 str = writer->buffer;
13603 writer->buffer = NULL;
13604
13605 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13606 PyObject *str2;
13607 str2 = resize_compact(str, writer->pos);
13608 if (str2 == NULL)
13609 return NULL;
13610 str = str2;
13611 }
13612 }
13613
Victor Stinner15a0bd32013-07-08 22:29:55 +020013614 assert(_PyUnicode_CheckConsistency(str, 1));
13615 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013616}
13617
Victor Stinnerd3f08822012-05-29 12:57:52 +020013618void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013619_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013620{
13621 Py_CLEAR(writer->buffer);
13622}
13623
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013625
13626PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013628\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013629Return a formatted version of S, using substitutions from args and kwargs.\n\
13630The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013631
Eric Smith27bbca62010-11-04 17:06:58 +000013632PyDoc_STRVAR(format_map__doc__,
13633 "S.format_map(mapping) -> str\n\
13634\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013635Return a formatted version of S, using substitutions from mapping.\n\
13636The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013637
Eric Smith4a7d76d2008-05-30 18:10:19 +000013638static PyObject *
13639unicode__format__(PyObject* self, PyObject* args)
13640{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013641 PyObject *format_spec;
13642 _PyUnicodeWriter writer;
13643 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013644
13645 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13646 return NULL;
13647
Victor Stinnerd3f08822012-05-29 12:57:52 +020013648 if (PyUnicode_READY(self) == -1)
13649 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013650 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013651 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13652 self, format_spec, 0,
13653 PyUnicode_GET_LENGTH(format_spec));
13654 if (ret == -1) {
13655 _PyUnicodeWriter_Dealloc(&writer);
13656 return NULL;
13657 }
13658 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013659}
13660
Eric Smith8c663262007-08-25 02:26:07 +000013661PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013663\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013664Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013665
13666static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013667unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013668{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013669 Py_ssize_t size;
13670
13671 /* If it's a compact object, account for base structure +
13672 character data. */
13673 if (PyUnicode_IS_COMPACT_ASCII(v))
13674 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13675 else if (PyUnicode_IS_COMPACT(v))
13676 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013677 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013678 else {
13679 /* If it is a two-block object, account for base object, and
13680 for character block if present. */
13681 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013682 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013683 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013684 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013685 }
13686 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013687 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013688 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013689 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013690 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013691 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013692
13693 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013694}
13695
13696PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013697 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013698
13699static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013700unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013701{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013702 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013703 if (!copy)
13704 return NULL;
13705 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013706}
13707
Guido van Rossumd57fd912000-03-10 22:53:23 +000013708static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013709 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013710 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013711 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13712 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013713 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13714 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013715 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013716 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13717 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13718 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013719 {"expandtabs", (PyCFunction) unicode_expandtabs,
13720 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013721 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013722 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013723 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13724 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13725 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013726 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013727 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13728 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13729 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013730 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013731 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013732 {"splitlines", (PyCFunction) unicode_splitlines,
13733 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013734 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013735 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13736 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13737 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13738 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13739 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13740 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13741 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13742 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13743 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13744 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13745 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13746 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13747 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13748 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013749 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013750 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013751 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013752 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013753 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013754 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013755 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013756 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013757#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013758 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013759 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013760#endif
13761
Benjamin Peterson14339b62009-01-31 16:36:08 +000013762 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013763 {NULL, NULL}
13764};
13765
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013766static PyObject *
13767unicode_mod(PyObject *v, PyObject *w)
13768{
Brian Curtindfc80e32011-08-10 20:28:54 -050013769 if (!PyUnicode_Check(v))
13770 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013771 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013772}
13773
13774static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013775 0, /*nb_add*/
13776 0, /*nb_subtract*/
13777 0, /*nb_multiply*/
13778 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013779};
13780
Guido van Rossumd57fd912000-03-10 22:53:23 +000013781static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013782 (lenfunc) unicode_length, /* sq_length */
13783 PyUnicode_Concat, /* sq_concat */
13784 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13785 (ssizeargfunc) unicode_getitem, /* sq_item */
13786 0, /* sq_slice */
13787 0, /* sq_ass_item */
13788 0, /* sq_ass_slice */
13789 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013790};
13791
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013792static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013793unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013794{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013795 if (PyUnicode_READY(self) == -1)
13796 return NULL;
13797
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013798 if (PyIndex_Check(item)) {
13799 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013800 if (i == -1 && PyErr_Occurred())
13801 return NULL;
13802 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013803 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013804 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013805 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013806 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013807 PyObject *result;
13808 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013809 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013810 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013812 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013813 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013814 return NULL;
13815 }
13816
13817 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013818 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013819 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013820 slicelength == PyUnicode_GET_LENGTH(self)) {
13821 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013822 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013823 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013824 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013825 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013826 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013827 src_kind = PyUnicode_KIND(self);
13828 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013829 if (!PyUnicode_IS_ASCII(self)) {
13830 kind_limit = kind_maxchar_limit(src_kind);
13831 max_char = 0;
13832 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13833 ch = PyUnicode_READ(src_kind, src_data, cur);
13834 if (ch > max_char) {
13835 max_char = ch;
13836 if (max_char >= kind_limit)
13837 break;
13838 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013839 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013840 }
Victor Stinner55c99112011-10-13 01:17:06 +020013841 else
13842 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013843 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013844 if (result == NULL)
13845 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013846 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013847 dest_data = PyUnicode_DATA(result);
13848
13849 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013850 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13851 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013852 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013853 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013854 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013855 } else {
13856 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13857 return NULL;
13858 }
13859}
13860
13861static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013862 (lenfunc)unicode_length, /* mp_length */
13863 (binaryfunc)unicode_subscript, /* mp_subscript */
13864 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013865};
13866
Guido van Rossumd57fd912000-03-10 22:53:23 +000013867
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868/* Helpers for PyUnicode_Format() */
13869
Victor Stinnera47082312012-10-04 02:19:54 +020013870struct unicode_formatter_t {
13871 PyObject *args;
13872 int args_owned;
13873 Py_ssize_t arglen, argidx;
13874 PyObject *dict;
13875
13876 enum PyUnicode_Kind fmtkind;
13877 Py_ssize_t fmtcnt, fmtpos;
13878 void *fmtdata;
13879 PyObject *fmtstr;
13880
13881 _PyUnicodeWriter writer;
13882};
13883
13884struct unicode_format_arg_t {
13885 Py_UCS4 ch;
13886 int flags;
13887 Py_ssize_t width;
13888 int prec;
13889 int sign;
13890};
13891
Guido van Rossumd57fd912000-03-10 22:53:23 +000013892static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013893unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013894{
Victor Stinnera47082312012-10-04 02:19:54 +020013895 Py_ssize_t argidx = ctx->argidx;
13896
13897 if (argidx < ctx->arglen) {
13898 ctx->argidx++;
13899 if (ctx->arglen < 0)
13900 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013901 else
Victor Stinnera47082312012-10-04 02:19:54 +020013902 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013903 }
13904 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013905 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013906 return NULL;
13907}
13908
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013909/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013910
Victor Stinnera47082312012-10-04 02:19:54 +020013911/* Format a float into the writer if the writer is not NULL, or into *p_output
13912 otherwise.
13913
13914 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013915static int
Victor Stinnera47082312012-10-04 02:19:54 +020013916formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13917 PyObject **p_output,
13918 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013919{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013920 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013921 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013922 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013923 int prec;
13924 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013925
Guido van Rossumd57fd912000-03-10 22:53:23 +000013926 x = PyFloat_AsDouble(v);
13927 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013928 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013929
Victor Stinnera47082312012-10-04 02:19:54 +020013930 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013932 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013933
Victor Stinnera47082312012-10-04 02:19:54 +020013934 if (arg->flags & F_ALT)
13935 dtoa_flags = Py_DTSF_ALT;
13936 else
13937 dtoa_flags = 0;
13938 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013939 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013940 return -1;
13941 len = strlen(p);
13942 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013943 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013944 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013945 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013946 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013947 }
13948 else
13949 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013950 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013951 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013952}
13953
Victor Stinnerd0880d52012-04-27 23:40:13 +020013954/* formatlong() emulates the format codes d, u, o, x and X, and
13955 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13956 * Python's regular ints.
13957 * Return value: a new PyUnicodeObject*, or NULL if error.
13958 * The output string is of the form
13959 * "-"? ("0x" | "0X")? digit+
13960 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13961 * set in flags. The case of hex digits will be correct,
13962 * There will be at least prec digits, zero-filled on the left if
13963 * necessary to get that many.
13964 * val object to be converted
13965 * flags bitmask of format flags; only F_ALT is looked at
13966 * prec minimum number of digits; 0-fill on left if needed
13967 * type a character in [duoxX]; u acts the same as d
13968 *
13969 * CAUTION: o, x and X conversions on regular ints can never
13970 * produce a '-' sign, but can for Python's unbounded ints.
13971 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013972PyObject *
13973_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013974{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013975 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013976 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013977 Py_ssize_t i;
13978 int sign; /* 1 if '-', else 0 */
13979 int len; /* number of characters */
13980 Py_ssize_t llen;
13981 int numdigits; /* len == numnondigits + numdigits */
13982 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013983
Victor Stinnerd0880d52012-04-27 23:40:13 +020013984 /* Avoid exceeding SSIZE_T_MAX */
13985 if (prec > INT_MAX-3) {
13986 PyErr_SetString(PyExc_OverflowError,
13987 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013988 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013989 }
13990
13991 assert(PyLong_Check(val));
13992
13993 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013994 default:
13995 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013996 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013997 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013998 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013999 /* int and int subclasses should print numerically when a numeric */
14000 /* format code is used (see issue18780) */
14001 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014002 break;
14003 case 'o':
14004 numnondigits = 2;
14005 result = PyNumber_ToBase(val, 8);
14006 break;
14007 case 'x':
14008 case 'X':
14009 numnondigits = 2;
14010 result = PyNumber_ToBase(val, 16);
14011 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014012 }
14013 if (!result)
14014 return NULL;
14015
14016 assert(unicode_modifiable(result));
14017 assert(PyUnicode_IS_READY(result));
14018 assert(PyUnicode_IS_ASCII(result));
14019
14020 /* To modify the string in-place, there can only be one reference. */
14021 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014022 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014023 PyErr_BadInternalCall();
14024 return NULL;
14025 }
14026 buf = PyUnicode_DATA(result);
14027 llen = PyUnicode_GET_LENGTH(result);
14028 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014029 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014030 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014031 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014032 return NULL;
14033 }
14034 len = (int)llen;
14035 sign = buf[0] == '-';
14036 numnondigits += sign;
14037 numdigits = len - numnondigits;
14038 assert(numdigits > 0);
14039
14040 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014041 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014042 (type == 'o' || type == 'x' || type == 'X'))) {
14043 assert(buf[sign] == '0');
14044 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14045 buf[sign+1] == 'o');
14046 numnondigits -= 2;
14047 buf += 2;
14048 len -= 2;
14049 if (sign)
14050 buf[0] = '-';
14051 assert(len == numnondigits + numdigits);
14052 assert(numdigits > 0);
14053 }
14054
14055 /* Fill with leading zeroes to meet minimum width. */
14056 if (prec > numdigits) {
14057 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14058 numnondigits + prec);
14059 char *b1;
14060 if (!r1) {
14061 Py_DECREF(result);
14062 return NULL;
14063 }
14064 b1 = PyBytes_AS_STRING(r1);
14065 for (i = 0; i < numnondigits; ++i)
14066 *b1++ = *buf++;
14067 for (i = 0; i < prec - numdigits; i++)
14068 *b1++ = '0';
14069 for (i = 0; i < numdigits; i++)
14070 *b1++ = *buf++;
14071 *b1 = '\0';
14072 Py_DECREF(result);
14073 result = r1;
14074 buf = PyBytes_AS_STRING(result);
14075 len = numnondigits + prec;
14076 }
14077
14078 /* Fix up case for hex conversions. */
14079 if (type == 'X') {
14080 /* Need to convert all lower case letters to upper case.
14081 and need to convert 0x to 0X (and -0x to -0X). */
14082 for (i = 0; i < len; i++)
14083 if (buf[i] >= 'a' && buf[i] <= 'x')
14084 buf[i] -= 'a'-'A';
14085 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014086 if (!PyUnicode_Check(result)
14087 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014088 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014089 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014090 Py_DECREF(result);
14091 result = unicode;
14092 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014093 else if (len != PyUnicode_GET_LENGTH(result)) {
14094 if (PyUnicode_Resize(&result, len) < 0)
14095 Py_CLEAR(result);
14096 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014098}
14099
Ethan Furmandf3ed242014-01-05 06:50:30 -080014100/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014101 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014102 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014103 * -1 and raise an exception on error */
14104static int
Victor Stinnera47082312012-10-04 02:19:54 +020014105mainformatlong(PyObject *v,
14106 struct unicode_format_arg_t *arg,
14107 PyObject **p_output,
14108 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014109{
14110 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014111 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014112
14113 if (!PyNumber_Check(v))
14114 goto wrongtype;
14115
Ethan Furman9ab74802014-03-21 06:38:46 -070014116 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014117 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014118 if (type == 'o' || type == 'x' || type == 'X') {
14119 iobj = PyNumber_Index(v);
14120 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014121 if (PyErr_ExceptionMatches(PyExc_TypeError))
14122 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014123 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014124 }
14125 }
14126 else {
14127 iobj = PyNumber_Long(v);
14128 if (iobj == NULL ) {
14129 if (PyErr_ExceptionMatches(PyExc_TypeError))
14130 goto wrongtype;
14131 return -1;
14132 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014133 }
14134 assert(PyLong_Check(iobj));
14135 }
14136 else {
14137 iobj = v;
14138 Py_INCREF(iobj);
14139 }
14140
14141 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014142 && arg->width == -1 && arg->prec == -1
14143 && !(arg->flags & (F_SIGN | F_BLANK))
14144 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014145 {
14146 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014147 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014148 int base;
14149
Victor Stinnera47082312012-10-04 02:19:54 +020014150 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014151 {
14152 default:
14153 assert(0 && "'type' not in [diuoxX]");
14154 case 'd':
14155 case 'i':
14156 case 'u':
14157 base = 10;
14158 break;
14159 case 'o':
14160 base = 8;
14161 break;
14162 case 'x':
14163 case 'X':
14164 base = 16;
14165 break;
14166 }
14167
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014168 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14169 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014170 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014171 }
14172 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014173 return 1;
14174 }
14175
Ethan Furmanb95b5612015-01-23 20:05:18 -080014176 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014177 Py_DECREF(iobj);
14178 if (res == NULL)
14179 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014180 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014181 return 0;
14182
14183wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014184 switch(type)
14185 {
14186 case 'o':
14187 case 'x':
14188 case 'X':
14189 PyErr_Format(PyExc_TypeError,
14190 "%%%c format: an integer is required, "
14191 "not %.200s",
14192 type, Py_TYPE(v)->tp_name);
14193 break;
14194 default:
14195 PyErr_Format(PyExc_TypeError,
14196 "%%%c format: a number is required, "
14197 "not %.200s",
14198 type, Py_TYPE(v)->tp_name);
14199 break;
14200 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014201 return -1;
14202}
14203
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014204static Py_UCS4
14205formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014206{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014207 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014208 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014209 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014210 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014211 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014212 goto onError;
14213 }
14214 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014215 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014216 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014217 /* make sure number is a type of integer */
14218 if (!PyLong_Check(v)) {
14219 iobj = PyNumber_Index(v);
14220 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014221 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014222 }
14223 v = iobj;
14224 Py_DECREF(iobj);
14225 }
14226 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014227 x = PyLong_AsLong(v);
14228 if (x == -1 && PyErr_Occurred())
14229 goto onError;
14230
Victor Stinner8faf8212011-12-08 22:14:11 +010014231 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014232 PyErr_SetString(PyExc_OverflowError,
14233 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014234 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014235 }
14236
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014237 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014238 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014239
Benjamin Peterson29060642009-01-31 22:14:21 +000014240 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014241 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014242 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014243 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014244}
14245
Victor Stinnera47082312012-10-04 02:19:54 +020014246/* Parse options of an argument: flags, width, precision.
14247 Handle also "%(name)" syntax.
14248
14249 Return 0 if the argument has been formatted into arg->str.
14250 Return 1 if the argument has been written into ctx->writer,
14251 Raise an exception and return -1 on error. */
14252static int
14253unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14254 struct unicode_format_arg_t *arg)
14255{
14256#define FORMAT_READ(ctx) \
14257 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14258
14259 PyObject *v;
14260
Victor Stinnera47082312012-10-04 02:19:54 +020014261 if (arg->ch == '(') {
14262 /* Get argument value from a dictionary. Example: "%(name)s". */
14263 Py_ssize_t keystart;
14264 Py_ssize_t keylen;
14265 PyObject *key;
14266 int pcount = 1;
14267
14268 if (ctx->dict == NULL) {
14269 PyErr_SetString(PyExc_TypeError,
14270 "format requires a mapping");
14271 return -1;
14272 }
14273 ++ctx->fmtpos;
14274 --ctx->fmtcnt;
14275 keystart = ctx->fmtpos;
14276 /* Skip over balanced parentheses */
14277 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14278 arg->ch = FORMAT_READ(ctx);
14279 if (arg->ch == ')')
14280 --pcount;
14281 else if (arg->ch == '(')
14282 ++pcount;
14283 ctx->fmtpos++;
14284 }
14285 keylen = ctx->fmtpos - keystart - 1;
14286 if (ctx->fmtcnt < 0 || pcount > 0) {
14287 PyErr_SetString(PyExc_ValueError,
14288 "incomplete format key");
14289 return -1;
14290 }
14291 key = PyUnicode_Substring(ctx->fmtstr,
14292 keystart, keystart + keylen);
14293 if (key == NULL)
14294 return -1;
14295 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014296 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014297 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014298 }
14299 ctx->args = PyObject_GetItem(ctx->dict, key);
14300 Py_DECREF(key);
14301 if (ctx->args == NULL)
14302 return -1;
14303 ctx->args_owned = 1;
14304 ctx->arglen = -1;
14305 ctx->argidx = -2;
14306 }
14307
14308 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014309 while (--ctx->fmtcnt >= 0) {
14310 arg->ch = FORMAT_READ(ctx);
14311 ctx->fmtpos++;
14312 switch (arg->ch) {
14313 case '-': arg->flags |= F_LJUST; continue;
14314 case '+': arg->flags |= F_SIGN; continue;
14315 case ' ': arg->flags |= F_BLANK; continue;
14316 case '#': arg->flags |= F_ALT; continue;
14317 case '0': arg->flags |= F_ZERO; continue;
14318 }
14319 break;
14320 }
14321
14322 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014323 if (arg->ch == '*') {
14324 v = unicode_format_getnextarg(ctx);
14325 if (v == NULL)
14326 return -1;
14327 if (!PyLong_Check(v)) {
14328 PyErr_SetString(PyExc_TypeError,
14329 "* wants int");
14330 return -1;
14331 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014332 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014333 if (arg->width == -1 && PyErr_Occurred())
14334 return -1;
14335 if (arg->width < 0) {
14336 arg->flags |= F_LJUST;
14337 arg->width = -arg->width;
14338 }
14339 if (--ctx->fmtcnt >= 0) {
14340 arg->ch = FORMAT_READ(ctx);
14341 ctx->fmtpos++;
14342 }
14343 }
14344 else if (arg->ch >= '0' && arg->ch <= '9') {
14345 arg->width = arg->ch - '0';
14346 while (--ctx->fmtcnt >= 0) {
14347 arg->ch = FORMAT_READ(ctx);
14348 ctx->fmtpos++;
14349 if (arg->ch < '0' || arg->ch > '9')
14350 break;
14351 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14352 mixing signed and unsigned comparison. Since arg->ch is between
14353 '0' and '9', casting to int is safe. */
14354 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14355 PyErr_SetString(PyExc_ValueError,
14356 "width too big");
14357 return -1;
14358 }
14359 arg->width = arg->width*10 + (arg->ch - '0');
14360 }
14361 }
14362
14363 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014364 if (arg->ch == '.') {
14365 arg->prec = 0;
14366 if (--ctx->fmtcnt >= 0) {
14367 arg->ch = FORMAT_READ(ctx);
14368 ctx->fmtpos++;
14369 }
14370 if (arg->ch == '*') {
14371 v = unicode_format_getnextarg(ctx);
14372 if (v == NULL)
14373 return -1;
14374 if (!PyLong_Check(v)) {
14375 PyErr_SetString(PyExc_TypeError,
14376 "* wants int");
14377 return -1;
14378 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014379 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014380 if (arg->prec == -1 && PyErr_Occurred())
14381 return -1;
14382 if (arg->prec < 0)
14383 arg->prec = 0;
14384 if (--ctx->fmtcnt >= 0) {
14385 arg->ch = FORMAT_READ(ctx);
14386 ctx->fmtpos++;
14387 }
14388 }
14389 else if (arg->ch >= '0' && arg->ch <= '9') {
14390 arg->prec = arg->ch - '0';
14391 while (--ctx->fmtcnt >= 0) {
14392 arg->ch = FORMAT_READ(ctx);
14393 ctx->fmtpos++;
14394 if (arg->ch < '0' || arg->ch > '9')
14395 break;
14396 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14397 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014398 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014399 return -1;
14400 }
14401 arg->prec = arg->prec*10 + (arg->ch - '0');
14402 }
14403 }
14404 }
14405
14406 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14407 if (ctx->fmtcnt >= 0) {
14408 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14409 if (--ctx->fmtcnt >= 0) {
14410 arg->ch = FORMAT_READ(ctx);
14411 ctx->fmtpos++;
14412 }
14413 }
14414 }
14415 if (ctx->fmtcnt < 0) {
14416 PyErr_SetString(PyExc_ValueError,
14417 "incomplete format");
14418 return -1;
14419 }
14420 return 0;
14421
14422#undef FORMAT_READ
14423}
14424
14425/* Format one argument. Supported conversion specifiers:
14426
14427 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014428 - "i", "d", "u": int or float
14429 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014430 - "e", "E", "f", "F", "g", "G": float
14431 - "c": int or str (1 character)
14432
Victor Stinner8dbd4212012-12-04 09:30:24 +010014433 When possible, the output is written directly into the Unicode writer
14434 (ctx->writer). A string is created when padding is required.
14435
Victor Stinnera47082312012-10-04 02:19:54 +020014436 Return 0 if the argument has been formatted into *p_str,
14437 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014438 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014439static int
14440unicode_format_arg_format(struct unicode_formatter_t *ctx,
14441 struct unicode_format_arg_t *arg,
14442 PyObject **p_str)
14443{
14444 PyObject *v;
14445 _PyUnicodeWriter *writer = &ctx->writer;
14446
14447 if (ctx->fmtcnt == 0)
14448 ctx->writer.overallocate = 0;
14449
14450 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014451 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014452 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014453 return 1;
14454 }
14455
14456 v = unicode_format_getnextarg(ctx);
14457 if (v == NULL)
14458 return -1;
14459
Victor Stinnera47082312012-10-04 02:19:54 +020014460
14461 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014462 case 's':
14463 case 'r':
14464 case 'a':
14465 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14466 /* Fast path */
14467 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14468 return -1;
14469 return 1;
14470 }
14471
14472 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14473 *p_str = v;
14474 Py_INCREF(*p_str);
14475 }
14476 else {
14477 if (arg->ch == 's')
14478 *p_str = PyObject_Str(v);
14479 else if (arg->ch == 'r')
14480 *p_str = PyObject_Repr(v);
14481 else
14482 *p_str = PyObject_ASCII(v);
14483 }
14484 break;
14485
14486 case 'i':
14487 case 'd':
14488 case 'u':
14489 case 'o':
14490 case 'x':
14491 case 'X':
14492 {
14493 int ret = mainformatlong(v, arg, p_str, writer);
14494 if (ret != 0)
14495 return ret;
14496 arg->sign = 1;
14497 break;
14498 }
14499
14500 case 'e':
14501 case 'E':
14502 case 'f':
14503 case 'F':
14504 case 'g':
14505 case 'G':
14506 if (arg->width == -1 && arg->prec == -1
14507 && !(arg->flags & (F_SIGN | F_BLANK)))
14508 {
14509 /* Fast path */
14510 if (formatfloat(v, arg, NULL, writer) == -1)
14511 return -1;
14512 return 1;
14513 }
14514
14515 arg->sign = 1;
14516 if (formatfloat(v, arg, p_str, NULL) == -1)
14517 return -1;
14518 break;
14519
14520 case 'c':
14521 {
14522 Py_UCS4 ch = formatchar(v);
14523 if (ch == (Py_UCS4) -1)
14524 return -1;
14525 if (arg->width == -1 && arg->prec == -1) {
14526 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014527 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014528 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014529 return 1;
14530 }
14531 *p_str = PyUnicode_FromOrdinal(ch);
14532 break;
14533 }
14534
14535 default:
14536 PyErr_Format(PyExc_ValueError,
14537 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014538 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014539 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14540 (int)arg->ch,
14541 ctx->fmtpos - 1);
14542 return -1;
14543 }
14544 if (*p_str == NULL)
14545 return -1;
14546 assert (PyUnicode_Check(*p_str));
14547 return 0;
14548}
14549
14550static int
14551unicode_format_arg_output(struct unicode_formatter_t *ctx,
14552 struct unicode_format_arg_t *arg,
14553 PyObject *str)
14554{
14555 Py_ssize_t len;
14556 enum PyUnicode_Kind kind;
14557 void *pbuf;
14558 Py_ssize_t pindex;
14559 Py_UCS4 signchar;
14560 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014561 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014562 Py_ssize_t sublen;
14563 _PyUnicodeWriter *writer = &ctx->writer;
14564 Py_UCS4 fill;
14565
14566 fill = ' ';
14567 if (arg->sign && arg->flags & F_ZERO)
14568 fill = '0';
14569
14570 if (PyUnicode_READY(str) == -1)
14571 return -1;
14572
14573 len = PyUnicode_GET_LENGTH(str);
14574 if ((arg->width == -1 || arg->width <= len)
14575 && (arg->prec == -1 || arg->prec >= len)
14576 && !(arg->flags & (F_SIGN | F_BLANK)))
14577 {
14578 /* Fast path */
14579 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14580 return -1;
14581 return 0;
14582 }
14583
14584 /* Truncate the string for "s", "r" and "a" formats
14585 if the precision is set */
14586 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14587 if (arg->prec >= 0 && len > arg->prec)
14588 len = arg->prec;
14589 }
14590
14591 /* Adjust sign and width */
14592 kind = PyUnicode_KIND(str);
14593 pbuf = PyUnicode_DATA(str);
14594 pindex = 0;
14595 signchar = '\0';
14596 if (arg->sign) {
14597 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14598 if (ch == '-' || ch == '+') {
14599 signchar = ch;
14600 len--;
14601 pindex++;
14602 }
14603 else if (arg->flags & F_SIGN)
14604 signchar = '+';
14605 else if (arg->flags & F_BLANK)
14606 signchar = ' ';
14607 else
14608 arg->sign = 0;
14609 }
14610 if (arg->width < len)
14611 arg->width = len;
14612
14613 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014614 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014615 if (!(arg->flags & F_LJUST)) {
14616 if (arg->sign) {
14617 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014618 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014619 }
14620 else {
14621 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014622 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014623 }
14624 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014625 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14626 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014627 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014628 }
14629
Victor Stinnera47082312012-10-04 02:19:54 +020014630 buflen = arg->width;
14631 if (arg->sign && len == arg->width)
14632 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014633 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014634 return -1;
14635
14636 /* Write the sign if needed */
14637 if (arg->sign) {
14638 if (fill != ' ') {
14639 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14640 writer->pos += 1;
14641 }
14642 if (arg->width > len)
14643 arg->width--;
14644 }
14645
14646 /* Write the numeric prefix for "x", "X" and "o" formats
14647 if the alternate form is used.
14648 For example, write "0x" for the "%#x" format. */
14649 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14650 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14651 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14652 if (fill != ' ') {
14653 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14654 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14655 writer->pos += 2;
14656 pindex += 2;
14657 }
14658 arg->width -= 2;
14659 if (arg->width < 0)
14660 arg->width = 0;
14661 len -= 2;
14662 }
14663
14664 /* Pad left with the fill character if needed */
14665 if (arg->width > len && !(arg->flags & F_LJUST)) {
14666 sublen = arg->width - len;
14667 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14668 writer->pos += sublen;
14669 arg->width = len;
14670 }
14671
14672 /* If padding with spaces: write sign if needed and/or numeric prefix if
14673 the alternate form is used */
14674 if (fill == ' ') {
14675 if (arg->sign) {
14676 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14677 writer->pos += 1;
14678 }
14679 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14680 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14681 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14682 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14683 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14684 writer->pos += 2;
14685 pindex += 2;
14686 }
14687 }
14688
14689 /* Write characters */
14690 if (len) {
14691 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14692 str, pindex, len);
14693 writer->pos += len;
14694 }
14695
14696 /* Pad right with the fill character if needed */
14697 if (arg->width > len) {
14698 sublen = arg->width - len;
14699 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14700 writer->pos += sublen;
14701 }
14702 return 0;
14703}
14704
14705/* Helper of PyUnicode_Format(): format one arg.
14706 Return 0 on success, raise an exception and return -1 on error. */
14707static int
14708unicode_format_arg(struct unicode_formatter_t *ctx)
14709{
14710 struct unicode_format_arg_t arg;
14711 PyObject *str;
14712 int ret;
14713
Victor Stinner8dbd4212012-12-04 09:30:24 +010014714 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14715 arg.flags = 0;
14716 arg.width = -1;
14717 arg.prec = -1;
14718 arg.sign = 0;
14719 str = NULL;
14720
Victor Stinnera47082312012-10-04 02:19:54 +020014721 ret = unicode_format_arg_parse(ctx, &arg);
14722 if (ret == -1)
14723 return -1;
14724
14725 ret = unicode_format_arg_format(ctx, &arg, &str);
14726 if (ret == -1)
14727 return -1;
14728
14729 if (ret != 1) {
14730 ret = unicode_format_arg_output(ctx, &arg, str);
14731 Py_DECREF(str);
14732 if (ret == -1)
14733 return -1;
14734 }
14735
14736 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14737 PyErr_SetString(PyExc_TypeError,
14738 "not all arguments converted during string formatting");
14739 return -1;
14740 }
14741 return 0;
14742}
14743
Alexander Belopolsky40018472011-02-26 01:02:56 +000014744PyObject *
14745PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014746{
Victor Stinnera47082312012-10-04 02:19:54 +020014747 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014748
Guido van Rossumd57fd912000-03-10 22:53:23 +000014749 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014750 PyErr_BadInternalCall();
14751 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014752 }
Victor Stinnera47082312012-10-04 02:19:54 +020014753
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014754 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014755 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014756
14757 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014758 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14759 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14760 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14761 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014762
Victor Stinner8f674cc2013-04-17 23:02:17 +020014763 _PyUnicodeWriter_Init(&ctx.writer);
14764 ctx.writer.min_length = ctx.fmtcnt + 100;
14765 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014766
Guido van Rossumd57fd912000-03-10 22:53:23 +000014767 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014768 ctx.arglen = PyTuple_Size(args);
14769 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014770 }
14771 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014772 ctx.arglen = -1;
14773 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014774 }
Victor Stinnera47082312012-10-04 02:19:54 +020014775 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014776 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014777 ctx.dict = args;
14778 else
14779 ctx.dict = NULL;
14780 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014781
Victor Stinnera47082312012-10-04 02:19:54 +020014782 while (--ctx.fmtcnt >= 0) {
14783 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014784 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014785
14786 nonfmtpos = ctx.fmtpos++;
14787 while (ctx.fmtcnt >= 0 &&
14788 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14789 ctx.fmtpos++;
14790 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014791 }
Victor Stinnera47082312012-10-04 02:19:54 +020014792 if (ctx.fmtcnt < 0) {
14793 ctx.fmtpos--;
14794 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014795 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014796
Victor Stinnercfc4c132013-04-03 01:48:39 +020014797 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14798 nonfmtpos, ctx.fmtpos) < 0)
14799 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014800 }
14801 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014802 ctx.fmtpos++;
14803 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014804 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014805 }
14806 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014807
Victor Stinnera47082312012-10-04 02:19:54 +020014808 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014809 PyErr_SetString(PyExc_TypeError,
14810 "not all arguments converted during string formatting");
14811 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014812 }
14813
Victor Stinnera47082312012-10-04 02:19:54 +020014814 if (ctx.args_owned) {
14815 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014816 }
Victor Stinnera47082312012-10-04 02:19:54 +020014817 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014818
Benjamin Peterson29060642009-01-31 22:14:21 +000014819 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014820 _PyUnicodeWriter_Dealloc(&ctx.writer);
14821 if (ctx.args_owned) {
14822 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014823 }
14824 return NULL;
14825}
14826
Jeremy Hylton938ace62002-07-17 16:30:39 +000014827static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014828unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14829
Tim Peters6d6c1a32001-08-02 04:15:00 +000014830static PyObject *
14831unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14832{
Benjamin Peterson29060642009-01-31 22:14:21 +000014833 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014834 static char *kwlist[] = {"object", "encoding", "errors", 0};
14835 char *encoding = NULL;
14836 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014837
Benjamin Peterson14339b62009-01-31 16:36:08 +000014838 if (type != &PyUnicode_Type)
14839 return unicode_subtype_new(type, args, kwds);
14840 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014841 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014842 return NULL;
14843 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014844 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014845 if (encoding == NULL && errors == NULL)
14846 return PyObject_Str(x);
14847 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014848 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014849}
14850
Guido van Rossume023fe02001-08-30 03:12:59 +000014851static PyObject *
14852unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14853{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014854 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014855 Py_ssize_t length, char_size;
14856 int share_wstr, share_utf8;
14857 unsigned int kind;
14858 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014859
Benjamin Peterson14339b62009-01-31 16:36:08 +000014860 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014861
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014862 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014863 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014864 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014865 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014866 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014867 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014868 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014869 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014870
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014871 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014872 if (self == NULL) {
14873 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014874 return NULL;
14875 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014876 kind = PyUnicode_KIND(unicode);
14877 length = PyUnicode_GET_LENGTH(unicode);
14878
14879 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014880#ifdef Py_DEBUG
14881 _PyUnicode_HASH(self) = -1;
14882#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014883 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014884#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014885 _PyUnicode_STATE(self).interned = 0;
14886 _PyUnicode_STATE(self).kind = kind;
14887 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014888 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014889 _PyUnicode_STATE(self).ready = 1;
14890 _PyUnicode_WSTR(self) = NULL;
14891 _PyUnicode_UTF8_LENGTH(self) = 0;
14892 _PyUnicode_UTF8(self) = NULL;
14893 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014894 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014895
14896 share_utf8 = 0;
14897 share_wstr = 0;
14898 if (kind == PyUnicode_1BYTE_KIND) {
14899 char_size = 1;
14900 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14901 share_utf8 = 1;
14902 }
14903 else if (kind == PyUnicode_2BYTE_KIND) {
14904 char_size = 2;
14905 if (sizeof(wchar_t) == 2)
14906 share_wstr = 1;
14907 }
14908 else {
14909 assert(kind == PyUnicode_4BYTE_KIND);
14910 char_size = 4;
14911 if (sizeof(wchar_t) == 4)
14912 share_wstr = 1;
14913 }
14914
14915 /* Ensure we won't overflow the length. */
14916 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14917 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014918 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014919 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014920 data = PyObject_MALLOC((length + 1) * char_size);
14921 if (data == NULL) {
14922 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014923 goto onError;
14924 }
14925
Victor Stinnerc3c74152011-10-02 20:39:55 +020014926 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014927 if (share_utf8) {
14928 _PyUnicode_UTF8_LENGTH(self) = length;
14929 _PyUnicode_UTF8(self) = data;
14930 }
14931 if (share_wstr) {
14932 _PyUnicode_WSTR_LENGTH(self) = length;
14933 _PyUnicode_WSTR(self) = (wchar_t *)data;
14934 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014935
Christian Heimesf051e432016-09-13 20:22:02 +020014936 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014937 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014938 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014939#ifdef Py_DEBUG
14940 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14941#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014942 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014943 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014944
14945onError:
14946 Py_DECREF(unicode);
14947 Py_DECREF(self);
14948 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014949}
14950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014951PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014952"str(object='') -> str\n\
14953str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014954\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014955Create a new string object from the given object. If encoding or\n\
14956errors is specified, then the object must expose a data buffer\n\
14957that will be decoded using the given encoding and error handler.\n\
14958Otherwise, returns the result of object.__str__() (if defined)\n\
14959or repr(object).\n\
14960encoding defaults to sys.getdefaultencoding().\n\
14961errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014962
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014963static PyObject *unicode_iter(PyObject *seq);
14964
Guido van Rossumd57fd912000-03-10 22:53:23 +000014965PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014966 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014967 "str", /* tp_name */
14968 sizeof(PyUnicodeObject), /* tp_size */
14969 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014970 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014971 (destructor)unicode_dealloc, /* tp_dealloc */
14972 0, /* tp_print */
14973 0, /* tp_getattr */
14974 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014975 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014976 unicode_repr, /* tp_repr */
14977 &unicode_as_number, /* tp_as_number */
14978 &unicode_as_sequence, /* tp_as_sequence */
14979 &unicode_as_mapping, /* tp_as_mapping */
14980 (hashfunc) unicode_hash, /* tp_hash*/
14981 0, /* tp_call*/
14982 (reprfunc) unicode_str, /* tp_str */
14983 PyObject_GenericGetAttr, /* tp_getattro */
14984 0, /* tp_setattro */
14985 0, /* tp_as_buffer */
14986 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014987 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014988 unicode_doc, /* tp_doc */
14989 0, /* tp_traverse */
14990 0, /* tp_clear */
14991 PyUnicode_RichCompare, /* tp_richcompare */
14992 0, /* tp_weaklistoffset */
14993 unicode_iter, /* tp_iter */
14994 0, /* tp_iternext */
14995 unicode_methods, /* tp_methods */
14996 0, /* tp_members */
14997 0, /* tp_getset */
14998 &PyBaseObject_Type, /* tp_base */
14999 0, /* tp_dict */
15000 0, /* tp_descr_get */
15001 0, /* tp_descr_set */
15002 0, /* tp_dictoffset */
15003 0, /* tp_init */
15004 0, /* tp_alloc */
15005 unicode_new, /* tp_new */
15006 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015007};
15008
15009/* Initialize the Unicode implementation */
15010
Victor Stinner3a50e702011-10-18 21:21:00 +020015011int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015012{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015013 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015014 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015015 0x000A, /* LINE FEED */
15016 0x000D, /* CARRIAGE RETURN */
15017 0x001C, /* FILE SEPARATOR */
15018 0x001D, /* GROUP SEPARATOR */
15019 0x001E, /* RECORD SEPARATOR */
15020 0x0085, /* NEXT LINE */
15021 0x2028, /* LINE SEPARATOR */
15022 0x2029, /* PARAGRAPH SEPARATOR */
15023 };
15024
Fred Drakee4315f52000-05-09 19:53:39 +000015025 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015026 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015027 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015028 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015029 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015030
Guido van Rossumcacfc072002-05-24 19:01:59 +000015031 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015032 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015033
15034 /* initialize the linebreak bloom filter */
15035 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015036 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015037 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015038
Christian Heimes26532f72013-07-20 14:57:16 +020015039 if (PyType_Ready(&EncodingMapType) < 0)
15040 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015041
Benjamin Petersonc4311282012-10-30 23:21:10 -040015042 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15043 Py_FatalError("Can't initialize field name iterator type");
15044
15045 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15046 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015047
Victor Stinner3a50e702011-10-18 21:21:00 +020015048 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015049}
15050
15051/* Finalize the Unicode implementation */
15052
Christian Heimesa156e092008-02-16 07:38:31 +000015053int
15054PyUnicode_ClearFreeList(void)
15055{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015056 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015057}
15058
Guido van Rossumd57fd912000-03-10 22:53:23 +000015059void
Thomas Wouters78890102000-07-22 19:25:51 +000015060_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015061{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015062 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015063
Serhiy Storchaka05997252013-01-26 12:14:02 +020015064 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015065
Serhiy Storchaka05997252013-01-26 12:14:02 +020015066 for (i = 0; i < 256; i++)
15067 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015068 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015069 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015070}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015071
Walter Dörwald16807132007-05-25 13:52:07 +000015072void
15073PyUnicode_InternInPlace(PyObject **p)
15074{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015075 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015077#ifdef Py_DEBUG
15078 assert(s != NULL);
15079 assert(_PyUnicode_CHECK(s));
15080#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015081 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015082 return;
15083#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015084 /* If it's a subclass, we don't really know what putting
15085 it in the interned dict might do. */
15086 if (!PyUnicode_CheckExact(s))
15087 return;
15088 if (PyUnicode_CHECK_INTERNED(s))
15089 return;
15090 if (interned == NULL) {
15091 interned = PyDict_New();
15092 if (interned == NULL) {
15093 PyErr_Clear(); /* Don't leave an exception */
15094 return;
15095 }
15096 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015097 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015098 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015099 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015100 if (t == NULL) {
15101 PyErr_Clear();
15102 return;
15103 }
15104 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015105 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015106 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015107 return;
15108 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015109 /* The two references in interned are not counted by refcnt.
15110 The deallocator will take care of this */
15111 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015112 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015113}
15114
15115void
15116PyUnicode_InternImmortal(PyObject **p)
15117{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015118 PyUnicode_InternInPlace(p);
15119 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015120 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015121 Py_INCREF(*p);
15122 }
Walter Dörwald16807132007-05-25 13:52:07 +000015123}
15124
15125PyObject *
15126PyUnicode_InternFromString(const char *cp)
15127{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 PyObject *s = PyUnicode_FromString(cp);
15129 if (s == NULL)
15130 return NULL;
15131 PyUnicode_InternInPlace(&s);
15132 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015133}
15134
Alexander Belopolsky40018472011-02-26 01:02:56 +000015135void
15136_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015137{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015138 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015139 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015140 Py_ssize_t i, n;
15141 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015142
Benjamin Peterson14339b62009-01-31 16:36:08 +000015143 if (interned == NULL || !PyDict_Check(interned))
15144 return;
15145 keys = PyDict_Keys(interned);
15146 if (keys == NULL || !PyList_Check(keys)) {
15147 PyErr_Clear();
15148 return;
15149 }
Walter Dörwald16807132007-05-25 13:52:07 +000015150
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15152 detector, interned unicode strings are not forcibly deallocated;
15153 rather, we give them their stolen references back, and then clear
15154 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015155
Benjamin Peterson14339b62009-01-31 16:36:08 +000015156 n = PyList_GET_SIZE(keys);
15157 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015158 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015159 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015160 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015161 if (PyUnicode_READY(s) == -1) {
15162 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015163 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015164 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015165 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 case SSTATE_NOT_INTERNED:
15167 /* XXX Shouldn't happen */
15168 break;
15169 case SSTATE_INTERNED_IMMORTAL:
15170 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015171 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015172 break;
15173 case SSTATE_INTERNED_MORTAL:
15174 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015175 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015176 break;
15177 default:
15178 Py_FatalError("Inconsistent interned string state.");
15179 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015180 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015181 }
15182 fprintf(stderr, "total size of all interned strings: "
15183 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15184 "mortal/immortal\n", mortal_size, immortal_size);
15185 Py_DECREF(keys);
15186 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015187 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015188}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015189
15190
15191/********************* Unicode Iterator **************************/
15192
15193typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015194 PyObject_HEAD
15195 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015196 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015197} unicodeiterobject;
15198
15199static void
15200unicodeiter_dealloc(unicodeiterobject *it)
15201{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 _PyObject_GC_UNTRACK(it);
15203 Py_XDECREF(it->it_seq);
15204 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015205}
15206
15207static int
15208unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15209{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015210 Py_VISIT(it->it_seq);
15211 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015212}
15213
15214static PyObject *
15215unicodeiter_next(unicodeiterobject *it)
15216{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015217 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015218
Benjamin Peterson14339b62009-01-31 16:36:08 +000015219 assert(it != NULL);
15220 seq = it->it_seq;
15221 if (seq == NULL)
15222 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015223 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015225 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15226 int kind = PyUnicode_KIND(seq);
15227 void *data = PyUnicode_DATA(seq);
15228 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15229 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015230 if (item != NULL)
15231 ++it->it_index;
15232 return item;
15233 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015234
Benjamin Peterson14339b62009-01-31 16:36:08 +000015235 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015236 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015237 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015238}
15239
15240static PyObject *
15241unicodeiter_len(unicodeiterobject *it)
15242{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015243 Py_ssize_t len = 0;
15244 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015245 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015247}
15248
15249PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15250
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015251static PyObject *
15252unicodeiter_reduce(unicodeiterobject *it)
15253{
15254 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015255 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015256 it->it_seq, it->it_index);
15257 } else {
15258 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15259 if (u == NULL)
15260 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015261 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015262 }
15263}
15264
15265PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15266
15267static PyObject *
15268unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15269{
15270 Py_ssize_t index = PyLong_AsSsize_t(state);
15271 if (index == -1 && PyErr_Occurred())
15272 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015273 if (it->it_seq != NULL) {
15274 if (index < 0)
15275 index = 0;
15276 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15277 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15278 it->it_index = index;
15279 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015280 Py_RETURN_NONE;
15281}
15282
15283PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15284
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015285static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015287 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015288 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15289 reduce_doc},
15290 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15291 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015292 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015293};
15294
15295PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015296 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15297 "str_iterator", /* tp_name */
15298 sizeof(unicodeiterobject), /* tp_basicsize */
15299 0, /* tp_itemsize */
15300 /* methods */
15301 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15302 0, /* tp_print */
15303 0, /* tp_getattr */
15304 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015305 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 0, /* tp_repr */
15307 0, /* tp_as_number */
15308 0, /* tp_as_sequence */
15309 0, /* tp_as_mapping */
15310 0, /* tp_hash */
15311 0, /* tp_call */
15312 0, /* tp_str */
15313 PyObject_GenericGetAttr, /* tp_getattro */
15314 0, /* tp_setattro */
15315 0, /* tp_as_buffer */
15316 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15317 0, /* tp_doc */
15318 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15319 0, /* tp_clear */
15320 0, /* tp_richcompare */
15321 0, /* tp_weaklistoffset */
15322 PyObject_SelfIter, /* tp_iter */
15323 (iternextfunc)unicodeiter_next, /* tp_iternext */
15324 unicodeiter_methods, /* tp_methods */
15325 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015326};
15327
15328static PyObject *
15329unicode_iter(PyObject *seq)
15330{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015332
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 if (!PyUnicode_Check(seq)) {
15334 PyErr_BadInternalCall();
15335 return NULL;
15336 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015337 if (PyUnicode_READY(seq) == -1)
15338 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15340 if (it == NULL)
15341 return NULL;
15342 it->it_index = 0;
15343 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015344 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 _PyObject_GC_TRACK(it);
15346 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015347}
15348
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015349
15350size_t
15351Py_UNICODE_strlen(const Py_UNICODE *u)
15352{
15353 int res = 0;
15354 while(*u++)
15355 res++;
15356 return res;
15357}
15358
15359Py_UNICODE*
15360Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15361{
15362 Py_UNICODE *u = s1;
15363 while ((*u++ = *s2++));
15364 return s1;
15365}
15366
15367Py_UNICODE*
15368Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15369{
15370 Py_UNICODE *u = s1;
15371 while ((*u++ = *s2++))
15372 if (n-- == 0)
15373 break;
15374 return s1;
15375}
15376
15377Py_UNICODE*
15378Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15379{
15380 Py_UNICODE *u1 = s1;
15381 u1 += Py_UNICODE_strlen(u1);
15382 Py_UNICODE_strcpy(u1, s2);
15383 return s1;
15384}
15385
15386int
15387Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15388{
15389 while (*s1 && *s2 && *s1 == *s2)
15390 s1++, s2++;
15391 if (*s1 && *s2)
15392 return (*s1 < *s2) ? -1 : +1;
15393 if (*s1)
15394 return 1;
15395 if (*s2)
15396 return -1;
15397 return 0;
15398}
15399
15400int
15401Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15402{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015403 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015404 for (; n != 0; n--) {
15405 u1 = *s1;
15406 u2 = *s2;
15407 if (u1 != u2)
15408 return (u1 < u2) ? -1 : +1;
15409 if (u1 == '\0')
15410 return 0;
15411 s1++;
15412 s2++;
15413 }
15414 return 0;
15415}
15416
15417Py_UNICODE*
15418Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15419{
15420 const Py_UNICODE *p;
15421 for (p = s; *p; p++)
15422 if (*p == c)
15423 return (Py_UNICODE*)p;
15424 return NULL;
15425}
15426
15427Py_UNICODE*
15428Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15429{
15430 const Py_UNICODE *p;
15431 p = s + Py_UNICODE_strlen(s);
15432 while (p != s) {
15433 p--;
15434 if (*p == c)
15435 return (Py_UNICODE*)p;
15436 }
15437 return NULL;
15438}
Victor Stinner331ea922010-08-10 16:37:20 +000015439
Victor Stinner71133ff2010-09-01 23:43:53 +000015440Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015441PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015442{
Victor Stinner577db2c2011-10-11 22:12:48 +020015443 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015444 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015446 if (!PyUnicode_Check(unicode)) {
15447 PyErr_BadArgument();
15448 return NULL;
15449 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015450 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015451 if (u == NULL)
15452 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015453 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015454 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015455 PyErr_NoMemory();
15456 return NULL;
15457 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015458 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015459 size *= sizeof(Py_UNICODE);
15460 copy = PyMem_Malloc(size);
15461 if (copy == NULL) {
15462 PyErr_NoMemory();
15463 return NULL;
15464 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015465 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015466 return copy;
15467}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015468
Georg Brandl66c221e2010-10-14 07:04:07 +000015469/* A _string module, to export formatter_parser and formatter_field_name_split
15470 to the string.Formatter class implemented in Python. */
15471
15472static PyMethodDef _string_methods[] = {
15473 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15474 METH_O, PyDoc_STR("split the argument as a field name")},
15475 {"formatter_parser", (PyCFunction) formatter_parser,
15476 METH_O, PyDoc_STR("parse the argument as a format string")},
15477 {NULL, NULL}
15478};
15479
15480static struct PyModuleDef _string_module = {
15481 PyModuleDef_HEAD_INIT,
15482 "_string",
15483 PyDoc_STR("string helper module"),
15484 0,
15485 _string_methods,
15486 NULL,
15487 NULL,
15488 NULL,
15489 NULL
15490};
15491
15492PyMODINIT_FUNC
15493PyInit__string(void)
15494{
15495 return PyModule_Create(&_string_module);
15496}
15497
15498
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015499#ifdef __cplusplus
15500}
15501#endif