blob: a6e02f478b1f764cdcdc29ad83a5e6a8ddc8bdf8 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043#include "internal/pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000044#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050045#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070046#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000047
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000048#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000049#include <windows.h>
50#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000051
Larry Hastings61272b72014-01-07 12:41:53 -080052/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090053class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080054[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090055/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
56
57/*[python input]
58class Py_UCS4_converter(CConverter):
59 type = 'Py_UCS4'
60 converter = 'convert_uc'
61
62 def converter_init(self):
63 if self.default is not unspecified:
64 self.c_default = ascii(self.default)
65 if len(self.c_default) > 4 or self.c_default[0] != "'":
66 self.c_default = hex(ord(self.default))
67
68[python start generated code]*/
69/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080070
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000071/* --- Globals ------------------------------------------------------------
72
Serhiy Storchaka05997252013-01-26 12:14:02 +020073NOTE: In the interpreter's initialization phase, some globals are currently
74 initialized dynamically as needed. In the process Unicode objects may
75 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000076
77*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000078
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079
80#ifdef __cplusplus
81extern "C" {
82#endif
83
Victor Stinner8faf8212011-12-08 22:14:11 +010084/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
85#define MAX_UNICODE 0x10ffff
86
Victor Stinner910337b2011-10-03 03:20:16 +020087#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020088# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020089#else
90# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
91#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020092
Victor Stinnere90fe6a2011-10-01 16:48:13 +020093#define _PyUnicode_UTF8(op) \
94 (((PyCompactUnicodeObject*)(op))->utf8)
95#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020096 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020097 assert(PyUnicode_IS_READY(op)), \
98 PyUnicode_IS_COMPACT_ASCII(op) ? \
99 ((char*)((PyASCIIObject*)(op) + 1)) : \
100 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200101#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 (((PyCompactUnicodeObject*)(op))->utf8_length)
103#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200104 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200105 assert(PyUnicode_IS_READY(op)), \
106 PyUnicode_IS_COMPACT_ASCII(op) ? \
107 ((PyASCIIObject*)(op))->length : \
108 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_WSTR(op) \
110 (((PyASCIIObject*)(op))->wstr)
111#define _PyUnicode_WSTR_LENGTH(op) \
112 (((PyCompactUnicodeObject*)(op))->wstr_length)
113#define _PyUnicode_LENGTH(op) \
114 (((PyASCIIObject *)(op))->length)
115#define _PyUnicode_STATE(op) \
116 (((PyASCIIObject *)(op))->state)
117#define _PyUnicode_HASH(op) \
118 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200125#define _PyUnicode_DATA_ANY(op) \
126 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200127
Victor Stinner910337b2011-10-03 03:20:16 +0200128#undef PyUnicode_READY
129#define PyUnicode_READY(op) \
130 (assert(_PyUnicode_CHECK(op)), \
131 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200132 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100133 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200134
Victor Stinnerc379ead2011-10-03 12:52:27 +0200135#define _PyUnicode_SHARE_UTF8(op) \
136 (assert(_PyUnicode_CHECK(op)), \
137 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
138 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
139#define _PyUnicode_SHARE_WSTR(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
142
Victor Stinner829c0ad2011-10-03 01:08:02 +0200143/* true if the Unicode object has an allocated UTF-8 memory block
144 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200145#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200146 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200147 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200148 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
149
Victor Stinner03490912011-10-03 23:45:12 +0200150/* true if the Unicode object has an allocated wstr memory block
151 (not shared with other data) */
152#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200153 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200154 (!PyUnicode_IS_READY(op) || \
155 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
156
Victor Stinner910337b2011-10-03 03:20:16 +0200157/* Generic helper macro to convert characters of different types.
158 from_type and to_type have to be valid type names, begin and end
159 are pointers to the source characters which should be of type
160 "from_type *". to is a pointer of type "to_type *" and points to the
161 buffer where the result characters are written to. */
162#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
163 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100164 to_type *_to = (to_type *)(to); \
165 const from_type *_iter = (from_type *)(begin); \
166 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200167 Py_ssize_t n = (_end) - (_iter); \
168 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200169 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_unrolled_end)) { \
171 _to[0] = (to_type) _iter[0]; \
172 _to[1] = (to_type) _iter[1]; \
173 _to[2] = (to_type) _iter[2]; \
174 _to[3] = (to_type) _iter[3]; \
175 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200176 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200177 while (_iter < (_end)) \
178 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200179 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200180
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200181#ifdef MS_WINDOWS
182 /* On Windows, overallocate by 50% is the best factor */
183# define OVERALLOCATE_FACTOR 2
184#else
185 /* On Linux, overallocate by 25% is the best factor */
186# define OVERALLOCATE_FACTOR 4
187#endif
188
Walter Dörwald16807132007-05-25 13:52:07 +0000189/* This dictionary holds all interned unicode strings. Note that references
190 to strings in this dictionary are *not* counted in the string's ob_refcnt.
191 When the interned string reaches a refcnt of 0 the string deallocation
192 function will delete the reference from this dictionary.
193
194 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000195 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000196*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000198
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200201
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200203 do { \
204 if (unicode_empty != NULL) \
205 Py_INCREF(unicode_empty); \
206 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207 unicode_empty = PyUnicode_New(0, 0); \
208 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200209 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200210 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
211 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200213 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000214
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215#define _Py_RETURN_UNICODE_EMPTY() \
216 do { \
217 _Py_INCREF_UNICODE_EMPTY(); \
218 return unicode_empty; \
219 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000220
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200221/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700222static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200223_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
224
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200225/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200226static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200227
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000228/* Single character Unicode strings in the Latin-1 range are being
229 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200230static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000231
Christian Heimes190d79e2008-01-30 11:58:22 +0000232/* Fast detection of the most frequent whitespace characters */
233const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000235/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000236/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000237/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000238/* case 0x000C: * FORM FEED */
239/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000240 0, 1, 1, 1, 1, 1, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000242/* case 0x001C: * FILE SEPARATOR */
243/* case 0x001D: * GROUP SEPARATOR */
244/* case 0x001E: * RECORD SEPARATOR */
245/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000246 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000247/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000248 1, 0, 0, 0, 0, 0, 0, 0,
249 0, 0, 0, 0, 0, 0, 0, 0,
250 0, 0, 0, 0, 0, 0, 0, 0,
251 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000252
Benjamin Peterson14339b62009-01-31 16:36:08 +0000253 0, 0, 0, 0, 0, 0, 0, 0,
254 0, 0, 0, 0, 0, 0, 0, 0,
255 0, 0, 0, 0, 0, 0, 0, 0,
256 0, 0, 0, 0, 0, 0, 0, 0,
257 0, 0, 0, 0, 0, 0, 0, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000261};
262
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200263/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200264static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200265static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100266static int unicode_modifiable(PyObject *unicode);
267
Victor Stinnerfe226c02011-10-03 03:52:20 +0200268
Alexander Belopolsky40018472011-02-26 01:02:56 +0000269static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100270_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200271static PyObject *
272_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
273static PyObject *
274_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
275
276static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000277unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000278 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100279 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000280 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
281
Alexander Belopolsky40018472011-02-26 01:02:56 +0000282static void
283raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300284 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100285 PyObject *unicode,
286 Py_ssize_t startpos, Py_ssize_t endpos,
287 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000288
Christian Heimes190d79e2008-01-30 11:58:22 +0000289/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200290static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000292/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000293/* 0x000B, * LINE TABULATION */
294/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000295/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000296 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000298/* 0x001C, * FILE SEPARATOR */
299/* 0x001D, * GROUP SEPARATOR */
300/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 0, 0, 0, 0, 1, 1, 1, 0,
302 0, 0, 0, 0, 0, 0, 0, 0,
303 0, 0, 0, 0, 0, 0, 0, 0,
304 0, 0, 0, 0, 0, 0, 0, 0,
305 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000306
Benjamin Peterson14339b62009-01-31 16:36:08 +0000307 0, 0, 0, 0, 0, 0, 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0,
309 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0, 0, 0, 0, 0,
311 0, 0, 0, 0, 0, 0, 0, 0,
312 0, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0,
314 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000315};
316
INADA Naoki3ae20562017-01-16 20:41:20 +0900317static int convert_uc(PyObject *obj, void *addr);
318
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300319#include "clinic/unicodeobject.c.h"
320
Victor Stinner50149202015-09-22 00:26:54 +0200321typedef enum {
322 _Py_ERROR_UNKNOWN=0,
323 _Py_ERROR_STRICT,
324 _Py_ERROR_SURROGATEESCAPE,
325 _Py_ERROR_REPLACE,
326 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200327 _Py_ERROR_BACKSLASHREPLACE,
328 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200329 _Py_ERROR_XMLCHARREFREPLACE,
330 _Py_ERROR_OTHER
331} _Py_error_handler;
332
333static _Py_error_handler
334get_error_handler(const char *errors)
335{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200337 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200338 }
339 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200341 }
342 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200343 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200344 }
345 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200346 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200347 }
348 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200349 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200350 }
351 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200352 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200353 }
354 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200355 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200356 }
Victor Stinner50149202015-09-22 00:26:54 +0200357 return _Py_ERROR_OTHER;
358}
359
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300360/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
361 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000362Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000363PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000364{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000365#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000366 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000367#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000368 /* This is actually an illegal character, so it should
369 not be passed to unichr. */
370 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000371#endif
372}
373
Victor Stinner910337b2011-10-03 03:20:16 +0200374#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200375int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100376_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200377{
378 PyASCIIObject *ascii;
379 unsigned int kind;
380
381 assert(PyUnicode_Check(op));
382
383 ascii = (PyASCIIObject *)op;
384 kind = ascii->state.kind;
385
Victor Stinnera3b334d2011-10-03 13:53:37 +0200386 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200387 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 assert(ascii->state.ready == 1);
389 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200390 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200391 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200392 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200393
Victor Stinnera41463c2011-10-04 01:05:08 +0200394 if (ascii->state.compact == 1) {
395 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200396 assert(kind == PyUnicode_1BYTE_KIND
397 || kind == PyUnicode_2BYTE_KIND
398 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200399 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200400 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200401 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100402 }
403 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200404 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
405
406 data = unicode->data.any;
407 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100408 assert(ascii->length == 0);
409 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200410 assert(ascii->state.compact == 0);
411 assert(ascii->state.ascii == 0);
412 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100413 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200414 assert(ascii->wstr != NULL);
415 assert(data == NULL);
416 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 }
418 else {
419 assert(kind == PyUnicode_1BYTE_KIND
420 || kind == PyUnicode_2BYTE_KIND
421 || kind == PyUnicode_4BYTE_KIND);
422 assert(ascii->state.compact == 0);
423 assert(ascii->state.ready == 1);
424 assert(data != NULL);
425 if (ascii->state.ascii) {
426 assert (compact->utf8 == data);
427 assert (compact->utf8_length == ascii->length);
428 }
429 else
430 assert (compact->utf8 != data);
431 }
432 }
433 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200434 if (
435#if SIZEOF_WCHAR_T == 2
436 kind == PyUnicode_2BYTE_KIND
437#else
438 kind == PyUnicode_4BYTE_KIND
439#endif
440 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200441 {
442 assert(ascii->wstr == data);
443 assert(compact->wstr_length == ascii->length);
444 } else
445 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200446 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200447
448 if (compact->utf8 == NULL)
449 assert(compact->utf8_length == 0);
450 if (ascii->wstr == NULL)
451 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200452 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 /* check that the best kind is used */
454 if (check_content && kind != PyUnicode_WCHAR_KIND)
455 {
456 Py_ssize_t i;
457 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200458 void *data;
459 Py_UCS4 ch;
460
461 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200462 for (i=0; i < ascii->length; i++)
463 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200464 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200465 if (ch > maxchar)
466 maxchar = ch;
467 }
468 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100469 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200470 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100471 assert(maxchar <= 255);
472 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200473 else
474 assert(maxchar < 128);
475 }
Victor Stinner77faf692011-11-20 18:56:05 +0100476 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200477 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100478 assert(maxchar <= 0xFFFF);
479 }
480 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200481 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100482 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100483 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200484 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200485 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400486 return 1;
487}
Victor Stinner910337b2011-10-03 03:20:16 +0200488#endif
489
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100490static PyObject*
491unicode_result_wchar(PyObject *unicode)
492{
493#ifndef Py_DEBUG
494 Py_ssize_t len;
495
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 len = _PyUnicode_WSTR_LENGTH(unicode);
497 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100498 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200499 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100500 }
501
502 if (len == 1) {
503 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100504 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100505 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
506 Py_DECREF(unicode);
507 return latin1_char;
508 }
509 }
510
511 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200512 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100513 return NULL;
514 }
515#else
Victor Stinneraa771272012-10-04 02:32:58 +0200516 assert(Py_REFCNT(unicode) == 1);
517
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 /* don't make the result ready in debug mode to ensure that the caller
519 makes the string ready before using it */
520 assert(_PyUnicode_CheckConsistency(unicode, 1));
521#endif
522 return unicode;
523}
524
525static PyObject*
526unicode_result_ready(PyObject *unicode)
527{
528 Py_ssize_t length;
529
530 length = PyUnicode_GET_LENGTH(unicode);
531 if (length == 0) {
532 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100533 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200534 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100535 }
536 return unicode_empty;
537 }
538
539 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200540 void *data = PyUnicode_DATA(unicode);
541 int kind = PyUnicode_KIND(unicode);
542 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100543 if (ch < 256) {
544 PyObject *latin1_char = unicode_latin1[ch];
545 if (latin1_char != NULL) {
546 if (unicode != latin1_char) {
547 Py_INCREF(latin1_char);
548 Py_DECREF(unicode);
549 }
550 return latin1_char;
551 }
552 else {
553 assert(_PyUnicode_CheckConsistency(unicode, 1));
554 Py_INCREF(unicode);
555 unicode_latin1[ch] = unicode;
556 return unicode;
557 }
558 }
559 }
560
561 assert(_PyUnicode_CheckConsistency(unicode, 1));
562 return unicode;
563}
564
565static PyObject*
566unicode_result(PyObject *unicode)
567{
568 assert(_PyUnicode_CHECK(unicode));
569 if (PyUnicode_IS_READY(unicode))
570 return unicode_result_ready(unicode);
571 else
572 return unicode_result_wchar(unicode);
573}
574
Victor Stinnerc4b49542011-12-11 22:44:26 +0100575static PyObject*
576unicode_result_unchanged(PyObject *unicode)
577{
578 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500579 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100580 return NULL;
581 Py_INCREF(unicode);
582 return unicode;
583 }
584 else
585 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100586 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100587}
588
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200589/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
590 ASCII, Latin1, UTF-8, etc. */
591static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200592backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200593 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
594{
Victor Stinnerad771582015-10-09 12:38:53 +0200595 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200596 Py_UCS4 ch;
597 enum PyUnicode_Kind kind;
598 void *data;
599
600 assert(PyUnicode_IS_READY(unicode));
601 kind = PyUnicode_KIND(unicode);
602 data = PyUnicode_DATA(unicode);
603
604 size = 0;
605 /* determine replacement size */
606 for (i = collstart; i < collend; ++i) {
607 Py_ssize_t incr;
608
609 ch = PyUnicode_READ(kind, data, i);
610 if (ch < 0x100)
611 incr = 2+2;
612 else if (ch < 0x10000)
613 incr = 2+4;
614 else {
615 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200616 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200617 }
618 if (size > PY_SSIZE_T_MAX - incr) {
619 PyErr_SetString(PyExc_OverflowError,
620 "encoded result is too long for a Python string");
621 return NULL;
622 }
623 size += incr;
624 }
625
Victor Stinnerad771582015-10-09 12:38:53 +0200626 str = _PyBytesWriter_Prepare(writer, str, size);
627 if (str == NULL)
628 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200629
630 /* generate replacement */
631 for (i = collstart; i < collend; ++i) {
632 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200633 *str++ = '\\';
634 if (ch >= 0x00010000) {
635 *str++ = 'U';
636 *str++ = Py_hexdigits[(ch>>28)&0xf];
637 *str++ = Py_hexdigits[(ch>>24)&0xf];
638 *str++ = Py_hexdigits[(ch>>20)&0xf];
639 *str++ = Py_hexdigits[(ch>>16)&0xf];
640 *str++ = Py_hexdigits[(ch>>12)&0xf];
641 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200642 }
Victor Stinner797485e2015-10-09 03:17:30 +0200643 else if (ch >= 0x100) {
644 *str++ = 'u';
645 *str++ = Py_hexdigits[(ch>>12)&0xf];
646 *str++ = Py_hexdigits[(ch>>8)&0xf];
647 }
648 else
649 *str++ = 'x';
650 *str++ = Py_hexdigits[(ch>>4)&0xf];
651 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200652 }
653 return str;
654}
655
656/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
657 ASCII, Latin1, UTF-8, etc. */
658static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200659xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200660 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
661{
Victor Stinnerad771582015-10-09 12:38:53 +0200662 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200663 Py_UCS4 ch;
664 enum PyUnicode_Kind kind;
665 void *data;
666
667 assert(PyUnicode_IS_READY(unicode));
668 kind = PyUnicode_KIND(unicode);
669 data = PyUnicode_DATA(unicode);
670
671 size = 0;
672 /* determine replacement size */
673 for (i = collstart; i < collend; ++i) {
674 Py_ssize_t incr;
675
676 ch = PyUnicode_READ(kind, data, i);
677 if (ch < 10)
678 incr = 2+1+1;
679 else if (ch < 100)
680 incr = 2+2+1;
681 else if (ch < 1000)
682 incr = 2+3+1;
683 else if (ch < 10000)
684 incr = 2+4+1;
685 else if (ch < 100000)
686 incr = 2+5+1;
687 else if (ch < 1000000)
688 incr = 2+6+1;
689 else {
690 assert(ch <= MAX_UNICODE);
691 incr = 2+7+1;
692 }
693 if (size > PY_SSIZE_T_MAX - incr) {
694 PyErr_SetString(PyExc_OverflowError,
695 "encoded result is too long for a Python string");
696 return NULL;
697 }
698 size += incr;
699 }
700
Victor Stinnerad771582015-10-09 12:38:53 +0200701 str = _PyBytesWriter_Prepare(writer, str, size);
702 if (str == NULL)
703 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200704
705 /* generate replacement */
706 for (i = collstart; i < collend; ++i) {
707 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
708 }
709 return str;
710}
711
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712/* --- Bloom Filters ----------------------------------------------------- */
713
714/* stuff to implement simple "bloom filters" for Unicode characters.
715 to keep things simple, we use a single bitmask, using the least 5
716 bits from each unicode characters as the bit index. */
717
718/* the linebreak mask is set up by Unicode_Init below */
719
Antoine Pitrouf068f942010-01-13 14:19:12 +0000720#if LONG_BIT >= 128
721#define BLOOM_WIDTH 128
722#elif LONG_BIT >= 64
723#define BLOOM_WIDTH 64
724#elif LONG_BIT >= 32
725#define BLOOM_WIDTH 32
726#else
727#error "LONG_BIT is smaller than 32"
728#endif
729
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730#define BLOOM_MASK unsigned long
731
Serhiy Storchaka05997252013-01-26 12:14:02 +0200732static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733
Antoine Pitrouf068f942010-01-13 14:19:12 +0000734#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735
Benjamin Peterson29060642009-01-31 22:14:21 +0000736#define BLOOM_LINEBREAK(ch) \
737 ((ch) < 128U ? ascii_linebreak[(ch)] : \
738 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700740static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742{
Victor Stinnera85af502013-04-09 21:53:54 +0200743#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
744 do { \
745 TYPE *data = (TYPE *)PTR; \
746 TYPE *end = data + LEN; \
747 Py_UCS4 ch; \
748 for (; data != end; data++) { \
749 ch = *data; \
750 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
751 } \
752 break; \
753 } while (0)
754
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755 /* calculate simple bloom-style bitmask for a given unicode string */
756
Antoine Pitrouf068f942010-01-13 14:19:12 +0000757 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
759 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200760 switch (kind) {
761 case PyUnicode_1BYTE_KIND:
762 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
763 break;
764 case PyUnicode_2BYTE_KIND:
765 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
766 break;
767 case PyUnicode_4BYTE_KIND:
768 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
769 break;
770 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700771 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200772 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200774
775#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776}
777
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300778static int
779ensure_unicode(PyObject *obj)
780{
781 if (!PyUnicode_Check(obj)) {
782 PyErr_Format(PyExc_TypeError,
783 "must be str, not %.100s",
784 Py_TYPE(obj)->tp_name);
785 return -1;
786 }
787 return PyUnicode_READY(obj);
788}
789
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200790/* Compilation of templated routines */
791
792#include "stringlib/asciilib.h"
793#include "stringlib/fastsearch.h"
794#include "stringlib/partition.h"
795#include "stringlib/split.h"
796#include "stringlib/count.h"
797#include "stringlib/find.h"
798#include "stringlib/find_max_char.h"
799#include "stringlib/localeutil.h"
800#include "stringlib/undef.h"
801
802#include "stringlib/ucs1lib.h"
803#include "stringlib/fastsearch.h"
804#include "stringlib/partition.h"
805#include "stringlib/split.h"
806#include "stringlib/count.h"
807#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300808#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200809#include "stringlib/find_max_char.h"
810#include "stringlib/localeutil.h"
811#include "stringlib/undef.h"
812
813#include "stringlib/ucs2lib.h"
814#include "stringlib/fastsearch.h"
815#include "stringlib/partition.h"
816#include "stringlib/split.h"
817#include "stringlib/count.h"
818#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300819#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200820#include "stringlib/find_max_char.h"
821#include "stringlib/localeutil.h"
822#include "stringlib/undef.h"
823
824#include "stringlib/ucs4lib.h"
825#include "stringlib/fastsearch.h"
826#include "stringlib/partition.h"
827#include "stringlib/split.h"
828#include "stringlib/count.h"
829#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300830#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200831#include "stringlib/find_max_char.h"
832#include "stringlib/localeutil.h"
833#include "stringlib/undef.h"
834
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200835#include "stringlib/unicodedefs.h"
836#include "stringlib/fastsearch.h"
837#include "stringlib/count.h"
838#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100839#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200840
Guido van Rossumd57fd912000-03-10 22:53:23 +0000841/* --- Unicode Object ----------------------------------------------------- */
842
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700843static inline Py_ssize_t
844findchar(const void *s, int kind,
845 Py_ssize_t size, Py_UCS4 ch,
846 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200847{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 switch (kind) {
849 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if ((Py_UCS1) ch != ch)
851 return -1;
852 if (direction > 0)
853 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
854 else
855 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200856 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200857 if ((Py_UCS2) ch != ch)
858 return -1;
859 if (direction > 0)
860 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
861 else
862 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200863 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200864 if (direction > 0)
865 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
866 else
867 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200868 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700869 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871}
872
Victor Stinnerafffce42012-10-03 23:03:17 +0200873#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000874/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200875 earlier.
876
877 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
878 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
879 invalid character in Unicode 6.0. */
880static void
881unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
882{
883 int kind = PyUnicode_KIND(unicode);
884 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
885 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
886 if (length <= old_length)
887 return;
888 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
889}
890#endif
891
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892static PyObject*
893resize_compact(PyObject *unicode, Py_ssize_t length)
894{
895 Py_ssize_t char_size;
896 Py_ssize_t struct_size;
897 Py_ssize_t new_size;
898 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100899 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200900#ifdef Py_DEBUG
901 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
902#endif
903
Victor Stinner79891572012-05-03 13:43:07 +0200904 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200905 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100906 assert(PyUnicode_IS_COMPACT(unicode));
907
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200908 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100909 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200910 struct_size = sizeof(PyASCIIObject);
911 else
912 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200913 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200914
Victor Stinnerfe226c02011-10-03 03:52:20 +0200915 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
916 PyErr_NoMemory();
917 return NULL;
918 }
919 new_size = (struct_size + (length + 1) * char_size);
920
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200921 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
922 PyObject_DEL(_PyUnicode_UTF8(unicode));
923 _PyUnicode_UTF8(unicode) = NULL;
924 _PyUnicode_UTF8_LENGTH(unicode) = 0;
925 }
Victor Stinner84def372011-12-11 20:04:56 +0100926 _Py_DEC_REFTOTAL;
927 _Py_ForgetReference(unicode);
928
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300929 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100930 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100931 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 PyErr_NoMemory();
933 return NULL;
934 }
Victor Stinner84def372011-12-11 20:04:56 +0100935 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200936 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100937
Victor Stinnerfe226c02011-10-03 03:52:20 +0200938 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200939 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100941 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200942 _PyUnicode_WSTR_LENGTH(unicode) = length;
943 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100944 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
945 PyObject_DEL(_PyUnicode_WSTR(unicode));
946 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100947 if (!PyUnicode_IS_ASCII(unicode))
948 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100949 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200950#ifdef Py_DEBUG
951 unicode_fill_invalid(unicode, old_length);
952#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
954 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200955 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 return unicode;
957}
958
Alexander Belopolsky40018472011-02-26 01:02:56 +0000959static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200960resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000961{
Victor Stinner95663112011-10-04 01:03:50 +0200962 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100963 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200964 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000966
Victor Stinnerfe226c02011-10-03 03:52:20 +0200967 if (PyUnicode_IS_READY(unicode)) {
968 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200969 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200970 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200971#ifdef Py_DEBUG
972 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
973#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200974
975 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200976 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200977 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
978 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979
980 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 new_size = (length + 1) * char_size;
985
Victor Stinner7a9105a2011-12-12 00:13:42 +0100986 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
987 {
988 PyObject_DEL(_PyUnicode_UTF8(unicode));
989 _PyUnicode_UTF8(unicode) = NULL;
990 _PyUnicode_UTF8_LENGTH(unicode) = 0;
991 }
992
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 data = (PyObject *)PyObject_REALLOC(data, new_size);
994 if (data == NULL) {
995 PyErr_NoMemory();
996 return -1;
997 }
998 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200999 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001001 _PyUnicode_WSTR_LENGTH(unicode) = length;
1002 }
1003 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001004 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001005 _PyUnicode_UTF8_LENGTH(unicode) = length;
1006 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001007 _PyUnicode_LENGTH(unicode) = length;
1008 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001009#ifdef Py_DEBUG
1010 unicode_fill_invalid(unicode, old_length);
1011#endif
Victor Stinner95663112011-10-04 01:03:50 +02001012 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001013 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001014 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001015 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001016 }
Victor Stinner95663112011-10-04 01:03:50 +02001017 assert(_PyUnicode_WSTR(unicode) != NULL);
1018
1019 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001020 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001021 PyErr_NoMemory();
1022 return -1;
1023 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001024 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001025 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001026 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001027 if (!wstr) {
1028 PyErr_NoMemory();
1029 return -1;
1030 }
1031 _PyUnicode_WSTR(unicode) = wstr;
1032 _PyUnicode_WSTR(unicode)[length] = 0;
1033 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001034 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001035 return 0;
1036}
1037
Victor Stinnerfe226c02011-10-03 03:52:20 +02001038static PyObject*
1039resize_copy(PyObject *unicode, Py_ssize_t length)
1040{
1041 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001042 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001045 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046
1047 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1048 if (copy == NULL)
1049 return NULL;
1050
1051 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001052 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001054 }
1055 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001056 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001057
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001058 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001059 if (w == NULL)
1060 return NULL;
1061 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1062 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001063 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001064 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001065 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001066 }
1067}
1068
Guido van Rossumd57fd912000-03-10 22:53:23 +00001069/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001070 Ux0000 terminated; some code (e.g. new_identifier)
1071 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072
1073 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001074 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075
1076*/
1077
Alexander Belopolsky40018472011-02-26 01:02:56 +00001078static PyUnicodeObject *
1079_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001080{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001081 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001083
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 if (length == 0 && unicode_empty != NULL) {
1086 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001087 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001088 }
1089
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001090 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001091 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001092 return (PyUnicodeObject *)PyErr_NoMemory();
1093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 if (length < 0) {
1095 PyErr_SetString(PyExc_SystemError,
1096 "Negative size passed to _PyUnicode_New");
1097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001098 }
1099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1101 if (unicode == NULL)
1102 return NULL;
1103 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001104
1105 _PyUnicode_WSTR_LENGTH(unicode) = length;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
1108 _PyUnicode_STATE(unicode).kind = 0;
1109 _PyUnicode_STATE(unicode).compact = 0;
1110 _PyUnicode_STATE(unicode).ready = 0;
1111 _PyUnicode_STATE(unicode).ascii = 0;
1112 _PyUnicode_DATA_ANY(unicode) = NULL;
1113 _PyUnicode_LENGTH(unicode) = 0;
1114 _PyUnicode_UTF8(unicode) = NULL;
1115 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1118 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001119 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001120 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001121 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123
Jeremy Hyltond8082792003-09-16 19:41:39 +00001124 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001125 * the caller fails before initializing str -- unicode_resize()
1126 * reads str[0], and the Keep-Alive optimization can keep memory
1127 * allocated for str alive across a call to unicode_dealloc(unicode).
1128 * We don't want unicode_resize to read uninitialized memory in
1129 * that case.
1130 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001131 _PyUnicode_WSTR(unicode)[0] = 0;
1132 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001133
Victor Stinner7931d9a2011-11-04 00:22:48 +01001134 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001135 return unicode;
1136}
1137
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138static const char*
1139unicode_kind_name(PyObject *unicode)
1140{
Victor Stinner42dfd712011-10-03 14:41:45 +02001141 /* don't check consistency: unicode_kind_name() is called from
1142 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001143 if (!PyUnicode_IS_COMPACT(unicode))
1144 {
1145 if (!PyUnicode_IS_READY(unicode))
1146 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001147 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001148 {
1149 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001150 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 return "legacy ascii";
1152 else
1153 return "legacy latin1";
1154 case PyUnicode_2BYTE_KIND:
1155 return "legacy UCS2";
1156 case PyUnicode_4BYTE_KIND:
1157 return "legacy UCS4";
1158 default:
1159 return "<legacy invalid kind>";
1160 }
1161 }
1162 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001163 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001164 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001165 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001166 return "ascii";
1167 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001168 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001169 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001170 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001171 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001172 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 default:
1174 return "<invalid compact kind>";
1175 }
1176}
1177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179/* Functions wrapping macros for use in debugger */
1180char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001181 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001182}
1183
1184void *_PyUnicode_compact_data(void *unicode) {
1185 return _PyUnicode_COMPACT_DATA(unicode);
1186}
1187void *_PyUnicode_data(void *unicode){
1188 printf("obj %p\n", unicode);
1189 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1190 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1191 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1192 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1193 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1194 return PyUnicode_DATA(unicode);
1195}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001196
1197void
1198_PyUnicode_Dump(PyObject *op)
1199{
1200 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001201 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1202 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1203 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001206 {
1207 if (ascii->state.ascii)
1208 data = (ascii + 1);
1209 else
1210 data = (compact + 1);
1211 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001212 else
1213 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001214 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1215 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001216
Victor Stinnera849a4b2011-10-03 12:12:11 +02001217 if (ascii->wstr == data)
1218 printf("shared ");
1219 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001220
Victor Stinnera3b334d2011-10-03 13:53:37 +02001221 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001222 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001223 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1224 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001225 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1226 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001227 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001228 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001229}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230#endif
1231
1232PyObject *
1233PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1234{
1235 PyObject *obj;
1236 PyCompactUnicodeObject *unicode;
1237 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001238 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001239 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 Py_ssize_t char_size;
1241 Py_ssize_t struct_size;
1242
1243 /* Optimization for empty strings */
1244 if (size == 0 && unicode_empty != NULL) {
1245 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001246 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 }
1248
Victor Stinner9e9d6892011-10-04 01:02:02 +02001249 is_ascii = 0;
1250 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 struct_size = sizeof(PyCompactUnicodeObject);
1252 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001253 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 char_size = 1;
1255 is_ascii = 1;
1256 struct_size = sizeof(PyASCIIObject);
1257 }
1258 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001259 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 char_size = 1;
1261 }
1262 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001263 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 char_size = 2;
1265 if (sizeof(wchar_t) == 2)
1266 is_sharing = 1;
1267 }
1268 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001269 if (maxchar > MAX_UNICODE) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "invalid maximum character passed to PyUnicode_New");
1272 return NULL;
1273 }
Victor Stinner8f825062012-04-27 13:55:39 +02001274 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 char_size = 4;
1276 if (sizeof(wchar_t) == 4)
1277 is_sharing = 1;
1278 }
1279
1280 /* Ensure we won't overflow the size. */
1281 if (size < 0) {
1282 PyErr_SetString(PyExc_SystemError,
1283 "Negative size passed to PyUnicode_New");
1284 return NULL;
1285 }
1286 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1287 return PyErr_NoMemory();
1288
1289 /* Duplicated allocation code from _PyObject_New() instead of a call to
1290 * PyObject_New() so we are able to allocate space for the object and
1291 * it's data buffer.
1292 */
1293 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1294 if (obj == NULL)
1295 return PyErr_NoMemory();
1296 obj = PyObject_INIT(obj, &PyUnicode_Type);
1297 if (obj == NULL)
1298 return NULL;
1299
1300 unicode = (PyCompactUnicodeObject *)obj;
1301 if (is_ascii)
1302 data = ((PyASCIIObject*)obj) + 1;
1303 else
1304 data = unicode + 1;
1305 _PyUnicode_LENGTH(unicode) = size;
1306 _PyUnicode_HASH(unicode) = -1;
1307 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001308 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001309 _PyUnicode_STATE(unicode).compact = 1;
1310 _PyUnicode_STATE(unicode).ready = 1;
1311 _PyUnicode_STATE(unicode).ascii = is_ascii;
1312 if (is_ascii) {
1313 ((char*)data)[size] = 0;
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 }
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((char*)data)[size] = 0;
1318 _PyUnicode_WSTR(unicode) = NULL;
1319 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001321 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 else {
1324 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001325 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001326 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001328 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001329 ((Py_UCS4*)data)[size] = 0;
1330 if (is_sharing) {
1331 _PyUnicode_WSTR_LENGTH(unicode) = size;
1332 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1333 }
1334 else {
1335 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1336 _PyUnicode_WSTR(unicode) = NULL;
1337 }
1338 }
Victor Stinner8f825062012-04-27 13:55:39 +02001339#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001340 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001341#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001342 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 return obj;
1344}
1345
1346#if SIZEOF_WCHAR_T == 2
1347/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1348 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001349 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350
1351 This function assumes that unicode can hold one more code point than wstr
1352 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001353static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001355 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356{
1357 const wchar_t *iter;
1358 Py_UCS4 *ucs4_out;
1359
Victor Stinner910337b2011-10-03 03:20:16 +02001360 assert(unicode != NULL);
1361 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1363 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1364
1365 for (iter = begin; iter < end; ) {
1366 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1367 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001368 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1369 && (iter+1) < end
1370 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 {
Victor Stinner551ac952011-11-29 22:58:13 +01001372 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 iter += 2;
1374 }
1375 else {
1376 *ucs4_out++ = *iter;
1377 iter++;
1378 }
1379 }
1380 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1381 _PyUnicode_GET_LENGTH(unicode)));
1382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383}
1384#endif
1385
Victor Stinnercd9950f2011-10-02 00:34:53 +02001386static int
Victor Stinner488fa492011-12-12 00:01:39 +01001387unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001388{
Victor Stinner488fa492011-12-12 00:01:39 +01001389 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001390 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001391 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001392 return -1;
1393 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001394 return 0;
1395}
1396
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397static int
1398_copy_characters(PyObject *to, Py_ssize_t to_start,
1399 PyObject *from, Py_ssize_t from_start,
1400 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001402 unsigned int from_kind, to_kind;
1403 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404
Victor Stinneree4544c2012-05-09 22:24:08 +02001405 assert(0 <= how_many);
1406 assert(0 <= from_start);
1407 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001408 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001409 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001410 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerd3f08822012-05-29 12:57:52 +02001412 assert(PyUnicode_Check(to));
1413 assert(PyUnicode_IS_READY(to));
1414 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1415
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001416 if (how_many == 0)
1417 return 0;
1418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001420 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001422 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423
Victor Stinnerf1852262012-06-16 16:38:26 +02001424#ifdef Py_DEBUG
1425 if (!check_maxchar
1426 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1427 {
1428 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1429 Py_UCS4 ch;
1430 Py_ssize_t i;
1431 for (i=0; i < how_many; i++) {
1432 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1433 assert(ch <= to_maxchar);
1434 }
1435 }
1436#endif
1437
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001438 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001439 if (check_maxchar
1440 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1441 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001442 /* Writing Latin-1 characters into an ASCII string requires to
1443 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001444 Py_UCS4 max_char;
1445 max_char = ucs1lib_find_max_char(from_data,
1446 (Py_UCS1*)from_data + how_many);
1447 if (max_char >= 128)
1448 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001449 }
Christian Heimesf051e432016-09-13 20:22:02 +02001450 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001451 (char*)from_data + from_kind * from_start,
1452 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001454 else if (from_kind == PyUnicode_1BYTE_KIND
1455 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001456 {
1457 _PyUnicode_CONVERT_BYTES(
1458 Py_UCS1, Py_UCS2,
1459 PyUnicode_1BYTE_DATA(from) + from_start,
1460 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1461 PyUnicode_2BYTE_DATA(to) + to_start
1462 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001463 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001464 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001465 && to_kind == PyUnicode_4BYTE_KIND)
1466 {
1467 _PyUnicode_CONVERT_BYTES(
1468 Py_UCS1, Py_UCS4,
1469 PyUnicode_1BYTE_DATA(from) + from_start,
1470 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1471 PyUnicode_4BYTE_DATA(to) + to_start
1472 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001473 }
1474 else if (from_kind == PyUnicode_2BYTE_KIND
1475 && to_kind == PyUnicode_4BYTE_KIND)
1476 {
1477 _PyUnicode_CONVERT_BYTES(
1478 Py_UCS2, Py_UCS4,
1479 PyUnicode_2BYTE_DATA(from) + from_start,
1480 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1481 PyUnicode_4BYTE_DATA(to) + to_start
1482 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001483 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001484 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001485 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1486
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001487 if (!check_maxchar) {
1488 if (from_kind == PyUnicode_2BYTE_KIND
1489 && to_kind == PyUnicode_1BYTE_KIND)
1490 {
1491 _PyUnicode_CONVERT_BYTES(
1492 Py_UCS2, Py_UCS1,
1493 PyUnicode_2BYTE_DATA(from) + from_start,
1494 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1495 PyUnicode_1BYTE_DATA(to) + to_start
1496 );
1497 }
1498 else if (from_kind == PyUnicode_4BYTE_KIND
1499 && to_kind == PyUnicode_1BYTE_KIND)
1500 {
1501 _PyUnicode_CONVERT_BYTES(
1502 Py_UCS4, Py_UCS1,
1503 PyUnicode_4BYTE_DATA(from) + from_start,
1504 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1505 PyUnicode_1BYTE_DATA(to) + to_start
1506 );
1507 }
1508 else if (from_kind == PyUnicode_4BYTE_KIND
1509 && to_kind == PyUnicode_2BYTE_KIND)
1510 {
1511 _PyUnicode_CONVERT_BYTES(
1512 Py_UCS4, Py_UCS2,
1513 PyUnicode_4BYTE_DATA(from) + from_start,
1514 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1515 PyUnicode_2BYTE_DATA(to) + to_start
1516 );
1517 }
1518 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001519 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001520 }
1521 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001522 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001523 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001525 Py_ssize_t i;
1526
Victor Stinnera0702ab2011-09-29 14:14:38 +02001527 for (i=0; i < how_many; i++) {
1528 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001529 if (ch > to_maxchar)
1530 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001531 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1532 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001533 }
1534 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001535 return 0;
1536}
1537
Victor Stinnerd3f08822012-05-29 12:57:52 +02001538void
1539_PyUnicode_FastCopyCharacters(
1540 PyObject *to, Py_ssize_t to_start,
1541 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001542{
1543 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1544}
1545
1546Py_ssize_t
1547PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1548 PyObject *from, Py_ssize_t from_start,
1549 Py_ssize_t how_many)
1550{
1551 int err;
1552
1553 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1554 PyErr_BadInternalCall();
1555 return -1;
1556 }
1557
Benjamin Petersonbac79492012-01-14 13:34:47 -05001558 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001560 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001561 return -1;
1562
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001563 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001564 PyErr_SetString(PyExc_IndexError, "string index out of range");
1565 return -1;
1566 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001567 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568 PyErr_SetString(PyExc_IndexError, "string index out of range");
1569 return -1;
1570 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001571 if (how_many < 0) {
1572 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1573 return -1;
1574 }
1575 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1577 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001578 "Cannot write %zi characters at %zi "
1579 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001580 how_many, to_start, PyUnicode_GET_LENGTH(to));
1581 return -1;
1582 }
1583
1584 if (how_many == 0)
1585 return 0;
1586
Victor Stinner488fa492011-12-12 00:01:39 +01001587 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001588 return -1;
1589
1590 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1591 if (err) {
1592 PyErr_Format(PyExc_SystemError,
1593 "Cannot copy %s characters "
1594 "into a string of %s characters",
1595 unicode_kind_name(from),
1596 unicode_kind_name(to));
1597 return -1;
1598 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001599 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600}
1601
Victor Stinner17222162011-09-28 22:15:37 +02001602/* Find the maximum code point and count the number of surrogate pairs so a
1603 correct string length can be computed before converting a string to UCS4.
1604 This function counts single surrogates as a character and not as a pair.
1605
1606 Return 0 on success, or -1 on error. */
1607static int
1608find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1609 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610{
1611 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001612 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613
Victor Stinnerc53be962011-10-02 21:33:54 +02001614 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 *num_surrogates = 0;
1616 *maxchar = 0;
1617
1618 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001620 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1621 && (iter+1) < end
1622 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1623 {
1624 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1625 ++(*num_surrogates);
1626 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001629#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001630 {
1631 ch = *iter;
1632 iter++;
1633 }
1634 if (ch > *maxchar) {
1635 *maxchar = ch;
1636 if (*maxchar > MAX_UNICODE) {
1637 PyErr_Format(PyExc_ValueError,
1638 "character U+%x is not in range [U+0000; U+10ffff]",
1639 ch);
1640 return -1;
1641 }
1642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 }
1644 return 0;
1645}
1646
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001647int
1648_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649{
1650 wchar_t *end;
1651 Py_UCS4 maxchar = 0;
1652 Py_ssize_t num_surrogates;
1653#if SIZEOF_WCHAR_T == 2
1654 Py_ssize_t length_wo_surrogates;
1655#endif
1656
Georg Brandl7597add2011-10-05 16:36:47 +02001657 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001658 strings were created using _PyObject_New() and where no canonical
1659 representation (the str field) has been set yet aka strings
1660 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001661 assert(_PyUnicode_CHECK(unicode));
1662 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001663 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001665 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001666 /* Actually, it should neither be interned nor be anything else: */
1667 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001670 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001671 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001673
1674 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001675 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1676 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 PyErr_NoMemory();
1678 return -1;
1679 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001680 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001681 _PyUnicode_WSTR(unicode), end,
1682 PyUnicode_1BYTE_DATA(unicode));
1683 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1684 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1685 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1686 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001687 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001688 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001689 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 }
1691 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001692 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 _PyUnicode_UTF8(unicode) = NULL;
1694 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001695 }
1696 PyObject_FREE(_PyUnicode_WSTR(unicode));
1697 _PyUnicode_WSTR(unicode) = NULL;
1698 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1699 }
1700 /* In this case we might have to convert down from 4-byte native
1701 wchar_t to 2-byte unicode. */
1702 else if (maxchar < 65536) {
1703 assert(num_surrogates == 0 &&
1704 "FindMaxCharAndNumSurrogatePairs() messed up");
1705
Victor Stinner506f5922011-09-28 22:34:18 +02001706#if SIZEOF_WCHAR_T == 2
1707 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001709 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1710 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1711 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001712 _PyUnicode_UTF8(unicode) = NULL;
1713 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001714#else
1715 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001716 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001717 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001718 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyErr_NoMemory();
1720 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 }
Victor Stinner506f5922011-09-28 22:34:18 +02001722 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1723 _PyUnicode_WSTR(unicode), end,
1724 PyUnicode_2BYTE_DATA(unicode));
1725 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1726 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1727 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001728 _PyUnicode_UTF8(unicode) = NULL;
1729 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001730 PyObject_FREE(_PyUnicode_WSTR(unicode));
1731 _PyUnicode_WSTR(unicode) = NULL;
1732 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1733#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 }
1735 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1736 else {
1737#if SIZEOF_WCHAR_T == 2
1738 /* in case the native representation is 2-bytes, we need to allocate a
1739 new normalized 4-byte version. */
1740 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001741 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1742 PyErr_NoMemory();
1743 return -1;
1744 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001745 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1746 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyErr_NoMemory();
1748 return -1;
1749 }
1750 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001752 _PyUnicode_UTF8(unicode) = NULL;
1753 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001754 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001756 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 PyObject_FREE(_PyUnicode_WSTR(unicode));
1758 _PyUnicode_WSTR(unicode) = NULL;
1759 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1760#else
1761 assert(num_surrogates == 0);
1762
Victor Stinnerc3c74152011-10-02 20:39:55 +02001763 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001765 _PyUnicode_UTF8(unicode) = NULL;
1766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1768#endif
1769 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1770 }
1771 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001772 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 return 0;
1774}
1775
Alexander Belopolsky40018472011-02-26 01:02:56 +00001776static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001777unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001778{
Walter Dörwald16807132007-05-25 13:52:07 +00001779 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_NOT_INTERNED:
1781 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 case SSTATE_INTERNED_MORTAL:
1784 /* revive dead object temporarily for DelItem */
1785 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001786 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001787 Py_FatalError(
1788 "deletion of interned string failed");
1789 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001790
Benjamin Peterson29060642009-01-31 22:14:21 +00001791 case SSTATE_INTERNED_IMMORTAL:
1792 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001793 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001794
Benjamin Peterson29060642009-01-31 22:14:21 +00001795 default:
1796 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001797 }
1798
Victor Stinner03490912011-10-03 23:45:12 +02001799 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001801 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001802 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001803 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1804 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001806 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807}
1808
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001809#ifdef Py_DEBUG
1810static int
1811unicode_is_singleton(PyObject *unicode)
1812{
1813 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1814 if (unicode == unicode_empty)
1815 return 1;
1816 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1817 {
1818 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1819 if (ch < 256 && unicode_latin1[ch] == unicode)
1820 return 1;
1821 }
1822 return 0;
1823}
1824#endif
1825
Alexander Belopolsky40018472011-02-26 01:02:56 +00001826static int
Victor Stinner488fa492011-12-12 00:01:39 +01001827unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828{
Victor Stinner488fa492011-12-12 00:01:39 +01001829 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 if (Py_REFCNT(unicode) != 1)
1831 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001832 if (_PyUnicode_HASH(unicode) != -1)
1833 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001834 if (PyUnicode_CHECK_INTERNED(unicode))
1835 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001836 if (!PyUnicode_CheckExact(unicode))
1837 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001838#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001839 /* singleton refcount is greater than 1 */
1840 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001841#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 return 1;
1843}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001844
Victor Stinnerfe226c02011-10-03 03:52:20 +02001845static int
1846unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1847{
1848 PyObject *unicode;
1849 Py_ssize_t old_length;
1850
1851 assert(p_unicode != NULL);
1852 unicode = *p_unicode;
1853
1854 assert(unicode != NULL);
1855 assert(PyUnicode_Check(unicode));
1856 assert(0 <= length);
1857
Victor Stinner910337b2011-10-03 03:20:16 +02001858 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 old_length = PyUnicode_WSTR_LENGTH(unicode);
1860 else
1861 old_length = PyUnicode_GET_LENGTH(unicode);
1862 if (old_length == length)
1863 return 0;
1864
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001865 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001866 _Py_INCREF_UNICODE_EMPTY();
1867 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001868 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001869 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001870 return 0;
1871 }
1872
Victor Stinner488fa492011-12-12 00:01:39 +01001873 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 PyObject *copy = resize_copy(unicode, length);
1875 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001877 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001878 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001879 }
1880
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001882 PyObject *new_unicode = resize_compact(unicode, length);
1883 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001885 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001886 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001887 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001888 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001889}
1890
Alexander Belopolsky40018472011-02-26 01:02:56 +00001891int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001892PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001894 PyObject *unicode;
1895 if (p_unicode == NULL) {
1896 PyErr_BadInternalCall();
1897 return -1;
1898 }
1899 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001900 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001901 {
1902 PyErr_BadInternalCall();
1903 return -1;
1904 }
1905 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001906}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001907
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001908/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001909
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001910 WARNING: The function doesn't copy the terminating null character and
1911 doesn't check the maximum character (may write a latin1 character in an
1912 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001913static void
1914unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1915 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001916{
1917 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1918 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001919 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001920
1921 switch (kind) {
1922 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001923 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001924#ifdef Py_DEBUG
1925 if (PyUnicode_IS_ASCII(unicode)) {
1926 Py_UCS4 maxchar = ucs1lib_find_max_char(
1927 (const Py_UCS1*)str,
1928 (const Py_UCS1*)str + len);
1929 assert(maxchar < 128);
1930 }
1931#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001932 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001933 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001934 }
1935 case PyUnicode_2BYTE_KIND: {
1936 Py_UCS2 *start = (Py_UCS2 *)data + index;
1937 Py_UCS2 *ucs2 = start;
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs2 = (Py_UCS2)*str;
1942
1943 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001944 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001945 }
1946 default: {
1947 Py_UCS4 *start = (Py_UCS4 *)data + index;
1948 Py_UCS4 *ucs4 = start;
1949 assert(kind == PyUnicode_4BYTE_KIND);
1950 assert(index <= PyUnicode_GET_LENGTH(unicode));
1951
Victor Stinner184252a2012-06-16 02:57:41 +02001952 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001953 *ucs4 = (Py_UCS4)*str;
1954
1955 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001956 }
1957 }
1958}
1959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960static PyObject*
1961get_latin1_char(unsigned char ch)
1962{
Victor Stinnera464fc12011-10-02 20:39:30 +02001963 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001964 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001965 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 if (!unicode)
1967 return NULL;
1968 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001969 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001970 unicode_latin1[ch] = unicode;
1971 }
1972 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001973 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974}
1975
Victor Stinner985a82a2014-01-03 12:53:47 +01001976static PyObject*
1977unicode_char(Py_UCS4 ch)
1978{
1979 PyObject *unicode;
1980
1981 assert(ch <= MAX_UNICODE);
1982
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001983 if (ch < 256)
1984 return get_latin1_char(ch);
1985
Victor Stinner985a82a2014-01-03 12:53:47 +01001986 unicode = PyUnicode_New(1, ch);
1987 if (unicode == NULL)
1988 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001989
1990 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1991 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001992 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001993 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001994 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1995 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1996 }
1997 assert(_PyUnicode_CheckConsistency(unicode, 1));
1998 return unicode;
1999}
2000
Alexander Belopolsky40018472011-02-26 01:02:56 +00002001PyObject *
2002PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002003{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002004 if (u == NULL)
2005 return (PyObject*)_PyUnicode_New(size);
2006
2007 if (size < 0) {
2008 PyErr_BadInternalCall();
2009 return NULL;
2010 }
2011
2012 return PyUnicode_FromWideChar(u, size);
2013}
2014
2015PyObject *
2016PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2017{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002018 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 Py_UCS4 maxchar = 0;
2020 Py_ssize_t num_surrogates;
2021
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002022 if (u == NULL && size != 0) {
2023 PyErr_BadInternalCall();
2024 return NULL;
2025 }
2026
2027 if (size == -1) {
2028 size = wcslen(u);
2029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002030
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002031 /* If the Unicode data is known at construction time, we can apply
2032 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002035 if (size == 0)
2036 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 /* Single character Unicode objects in the Latin-1 range are
2039 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002040 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return get_latin1_char((unsigned char)*u);
2042
2043 /* If not empty and not single character, copy the Unicode data
2044 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002045 if (find_maxchar_surrogates(u, u + size,
2046 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048
Victor Stinner8faf8212011-12-08 22:14:11 +01002049 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 if (!unicode)
2051 return NULL;
2052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 switch (PyUnicode_KIND(unicode)) {
2054 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002055 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2057 break;
2058 case PyUnicode_2BYTE_KIND:
2059#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002060 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002062 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2064#endif
2065 break;
2066 case PyUnicode_4BYTE_KIND:
2067#if SIZEOF_WCHAR_T == 2
2068 /* This is the only case which has to process surrogates, thus
2069 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002070 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071#else
2072 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002073 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074#endif
2075 break;
2076 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002077 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002080 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081}
2082
Alexander Belopolsky40018472011-02-26 01:02:56 +00002083PyObject *
2084PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002085{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002086 if (size < 0) {
2087 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002088 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002089 return NULL;
2090 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002091 if (u != NULL)
2092 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2093 else
2094 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002095}
2096
Alexander Belopolsky40018472011-02-26 01:02:56 +00002097PyObject *
2098PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002099{
2100 size_t size = strlen(u);
2101 if (size > PY_SSIZE_T_MAX) {
2102 PyErr_SetString(PyExc_OverflowError, "input too long");
2103 return NULL;
2104 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002105 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002106}
2107
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002108PyObject *
2109_PyUnicode_FromId(_Py_Identifier *id)
2110{
2111 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002112 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2113 strlen(id->string),
2114 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002115 if (!id->object)
2116 return NULL;
2117 PyUnicode_InternInPlace(&id->object);
2118 assert(!id->next);
2119 id->next = static_strings;
2120 static_strings = id;
2121 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002122 return id->object;
2123}
2124
2125void
2126_PyUnicode_ClearStaticStrings()
2127{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002128 _Py_Identifier *tmp, *s = static_strings;
2129 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002130 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002131 tmp = s->next;
2132 s->next = NULL;
2133 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002134 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002135 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002136}
2137
Benjamin Peterson0df54292012-03-26 14:50:32 -04002138/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002139
Victor Stinnerd3f08822012-05-29 12:57:52 +02002140PyObject*
2141_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002142{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002143 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002144 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002145 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002146#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002147 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002148#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002149 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002150 }
Victor Stinner785938e2011-12-11 20:09:03 +01002151 unicode = PyUnicode_New(size, 127);
2152 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002153 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002154 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2155 assert(_PyUnicode_CheckConsistency(unicode, 1));
2156 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002157}
2158
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159static Py_UCS4
2160kind_maxchar_limit(unsigned int kind)
2161{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002162 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002163 case PyUnicode_1BYTE_KIND:
2164 return 0x80;
2165 case PyUnicode_2BYTE_KIND:
2166 return 0x100;
2167 case PyUnicode_4BYTE_KIND:
2168 return 0x10000;
2169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002170 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002171 }
2172}
2173
Victor Stinner702c7342011-10-05 13:50:52 +02002174static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002175_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002176{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002178 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002179
Serhiy Storchaka678db842013-01-26 12:16:36 +02002180 if (size == 0)
2181 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002182 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002183 if (size == 1)
2184 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002185
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002186 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002187 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 if (!res)
2189 return NULL;
2190 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002191 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002193}
2194
Victor Stinnere57b1c02011-09-28 22:20:48 +02002195static PyObject*
2196_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197{
2198 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002199 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002200
Serhiy Storchaka678db842013-01-26 12:16:36 +02002201 if (size == 0)
2202 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002203 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002204 if (size == 1)
2205 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002207 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002208 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 if (!res)
2210 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 else {
2214 _PyUnicode_CONVERT_BYTES(
2215 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2216 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002217 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return res;
2219}
2220
Victor Stinnere57b1c02011-09-28 22:20:48 +02002221static PyObject*
2222_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223{
2224 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002225 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002226
Serhiy Storchaka678db842013-01-26 12:16:36 +02002227 if (size == 0)
2228 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002229 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002230 if (size == 1)
2231 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002233 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002234 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 if (!res)
2236 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002237 if (max_char < 256)
2238 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2239 PyUnicode_1BYTE_DATA(res));
2240 else if (max_char < 0x10000)
2241 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2242 PyUnicode_2BYTE_DATA(res));
2243 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002245 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 return res;
2247}
2248
2249PyObject*
2250PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2251{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002252 if (size < 0) {
2253 PyErr_SetString(PyExc_ValueError, "size must be positive");
2254 return NULL;
2255 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002256 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002258 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002260 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002262 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002263 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002264 PyErr_SetString(PyExc_SystemError, "invalid kind");
2265 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267}
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269Py_UCS4
2270_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2271{
2272 enum PyUnicode_Kind kind;
2273 void *startptr, *endptr;
2274
2275 assert(PyUnicode_IS_READY(unicode));
2276 assert(0 <= start);
2277 assert(end <= PyUnicode_GET_LENGTH(unicode));
2278 assert(start <= end);
2279
2280 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2281 return PyUnicode_MAX_CHAR_VALUE(unicode);
2282
2283 if (start == end)
2284 return 127;
2285
Victor Stinner94d558b2012-04-27 22:26:58 +02002286 if (PyUnicode_IS_ASCII(unicode))
2287 return 127;
2288
Victor Stinnerece58de2012-04-23 23:36:38 +02002289 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002290 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002291 endptr = (char *)startptr + end * kind;
2292 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002293 switch(kind) {
2294 case PyUnicode_1BYTE_KIND:
2295 return ucs1lib_find_max_char(startptr, endptr);
2296 case PyUnicode_2BYTE_KIND:
2297 return ucs2lib_find_max_char(startptr, endptr);
2298 case PyUnicode_4BYTE_KIND:
2299 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002301 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002302 }
2303}
2304
Victor Stinner25a4b292011-10-06 12:31:55 +02002305/* Ensure that a string uses the most efficient storage, if it is not the
2306 case: create a new string with of the right kind. Write NULL into *p_unicode
2307 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002308static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002309unicode_adjust_maxchar(PyObject **p_unicode)
2310{
2311 PyObject *unicode, *copy;
2312 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002314 unsigned int kind;
2315
2316 assert(p_unicode != NULL);
2317 unicode = *p_unicode;
2318 assert(PyUnicode_IS_READY(unicode));
2319 if (PyUnicode_IS_ASCII(unicode))
2320 return;
2321
2322 len = PyUnicode_GET_LENGTH(unicode);
2323 kind = PyUnicode_KIND(unicode);
2324 if (kind == PyUnicode_1BYTE_KIND) {
2325 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002326 max_char = ucs1lib_find_max_char(u, u + len);
2327 if (max_char >= 128)
2328 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 }
2330 else if (kind == PyUnicode_2BYTE_KIND) {
2331 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002332 max_char = ucs2lib_find_max_char(u, u + len);
2333 if (max_char >= 256)
2334 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002335 }
2336 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002337 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002338 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002339 max_char = ucs4lib_find_max_char(u, u + len);
2340 if (max_char >= 0x10000)
2341 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002342 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002343 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002344 if (copy != NULL)
2345 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002346 Py_DECREF(unicode);
2347 *p_unicode = copy;
2348}
2349
Victor Stinner034f6cf2011-09-30 02:26:44 +02002350PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002351_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002352{
Victor Stinner87af4f22011-11-21 23:03:47 +01002353 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002355
Victor Stinner034f6cf2011-09-30 02:26:44 +02002356 if (!PyUnicode_Check(unicode)) {
2357 PyErr_BadInternalCall();
2358 return NULL;
2359 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002360 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002361 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002362
Victor Stinner87af4f22011-11-21 23:03:47 +01002363 length = PyUnicode_GET_LENGTH(unicode);
2364 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002365 if (!copy)
2366 return NULL;
2367 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2368
Christian Heimesf051e432016-09-13 20:22:02 +02002369 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002370 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002371 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002372 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002373}
2374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375
Victor Stinnerbc603d12011-10-02 01:00:40 +02002376/* Widen Unicode objects to larger buffers. Don't write terminating null
2377 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002378
2379void*
2380_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2381{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 Py_ssize_t len;
2383 void *result;
2384 unsigned int skind;
2385
Benjamin Petersonbac79492012-01-14 13:34:47 -05002386 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002387 return NULL;
2388
2389 len = PyUnicode_GET_LENGTH(s);
2390 skind = PyUnicode_KIND(s);
2391 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002392 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002393 return NULL;
2394 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002395 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002396 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002397 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002398 if (!result)
2399 return PyErr_NoMemory();
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS2,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002407 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002408 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 if (!result)
2410 return PyErr_NoMemory();
2411 if (skind == PyUnicode_2BYTE_KIND) {
2412 _PyUnicode_CONVERT_BYTES(
2413 Py_UCS2, Py_UCS4,
2414 PyUnicode_2BYTE_DATA(s),
2415 PyUnicode_2BYTE_DATA(s) + len,
2416 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002418 else {
2419 assert(skind == PyUnicode_1BYTE_KIND);
2420 _PyUnicode_CONVERT_BYTES(
2421 Py_UCS1, Py_UCS4,
2422 PyUnicode_1BYTE_DATA(s),
2423 PyUnicode_1BYTE_DATA(s) + len,
2424 result);
2425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002427 default:
2428 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 }
Victor Stinner01698042011-10-04 00:04:26 +02002430 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 return NULL;
2432}
2433
2434static Py_UCS4*
2435as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2436 int copy_null)
2437{
2438 int kind;
2439 void *data;
2440 Py_ssize_t len, targetlen;
2441 if (PyUnicode_READY(string) == -1)
2442 return NULL;
2443 kind = PyUnicode_KIND(string);
2444 data = PyUnicode_DATA(string);
2445 len = PyUnicode_GET_LENGTH(string);
2446 targetlen = len;
2447 if (copy_null)
2448 targetlen++;
2449 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002450 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 if (!target) {
2452 PyErr_NoMemory();
2453 return NULL;
2454 }
2455 }
2456 else {
2457 if (targetsize < targetlen) {
2458 PyErr_Format(PyExc_SystemError,
2459 "string is longer than the buffer");
2460 if (copy_null && 0 < targetsize)
2461 target[0] = 0;
2462 return NULL;
2463 }
2464 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002465 if (kind == PyUnicode_1BYTE_KIND) {
2466 Py_UCS1 *start = (Py_UCS1 *) data;
2467 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002469 else if (kind == PyUnicode_2BYTE_KIND) {
2470 Py_UCS2 *start = (Py_UCS2 *) data;
2471 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2472 }
2473 else {
2474 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002475 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 if (copy_null)
2478 target[len] = 0;
2479 return target;
2480}
2481
2482Py_UCS4*
2483PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2484 int copy_null)
2485{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002486 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 PyErr_BadInternalCall();
2488 return NULL;
2489 }
2490 return as_ucs4(string, target, targetsize, copy_null);
2491}
2492
2493Py_UCS4*
2494PyUnicode_AsUCS4Copy(PyObject *string)
2495{
2496 return as_ucs4(string, NULL, 0, 1);
2497}
2498
Victor Stinner15a11362012-10-06 23:48:20 +02002499/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002500 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2501 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2502#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002503
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002504static int
2505unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2506 Py_ssize_t width, Py_ssize_t precision)
2507{
2508 Py_ssize_t length, fill, arglen;
2509 Py_UCS4 maxchar;
2510
2511 if (PyUnicode_READY(str) == -1)
2512 return -1;
2513
2514 length = PyUnicode_GET_LENGTH(str);
2515 if ((precision == -1 || precision >= length)
2516 && width <= length)
2517 return _PyUnicodeWriter_WriteStr(writer, str);
2518
2519 if (precision != -1)
2520 length = Py_MIN(precision, length);
2521
2522 arglen = Py_MAX(length, width);
2523 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2524 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2525 else
2526 maxchar = writer->maxchar;
2527
2528 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2529 return -1;
2530
2531 if (width > length) {
2532 fill = width - length;
2533 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2534 return -1;
2535 writer->pos += fill;
2536 }
2537
2538 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2539 str, 0, length);
2540 writer->pos += length;
2541 return 0;
2542}
2543
2544static int
2545unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2546 Py_ssize_t width, Py_ssize_t precision)
2547{
2548 /* UTF-8 */
2549 Py_ssize_t length;
2550 PyObject *unicode;
2551 int res;
2552
2553 length = strlen(str);
2554 if (precision != -1)
2555 length = Py_MIN(length, precision);
2556 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2557 if (unicode == NULL)
2558 return -1;
2559
2560 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2561 Py_DECREF(unicode);
2562 return res;
2563}
2564
Victor Stinner96865452011-03-01 23:44:09 +00002565static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002566unicode_fromformat_arg(_PyUnicodeWriter *writer,
2567 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002568{
Victor Stinnere215d962012-10-06 23:03:36 +02002569 const char *p;
2570 Py_ssize_t len;
2571 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 Py_ssize_t width;
2573 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002574 int longflag;
2575 int longlongflag;
2576 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002577 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002578
2579 p = f;
2580 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002581 zeropad = 0;
2582 if (*f == '0') {
2583 zeropad = 1;
2584 f++;
2585 }
Victor Stinner96865452011-03-01 23:44:09 +00002586
2587 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002588 width = -1;
2589 if (Py_ISDIGIT((unsigned)*f)) {
2590 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002591 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002592 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002594 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002596 return NULL;
2597 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002599 f++;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 }
2602 precision = -1;
2603 if (*f == '.') {
2604 f++;
2605 if (Py_ISDIGIT((unsigned)*f)) {
2606 precision = (*f - '0');
2607 f++;
2608 while (Py_ISDIGIT((unsigned)*f)) {
2609 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2610 PyErr_SetString(PyExc_ValueError,
2611 "precision too big");
2612 return NULL;
2613 }
2614 precision = (precision * 10) + (*f - '0');
2615 f++;
2616 }
2617 }
Victor Stinner96865452011-03-01 23:44:09 +00002618 if (*f == '%') {
2619 /* "%.3%s" => f points to "3" */
2620 f--;
2621 }
2622 }
2623 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002624 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002625 f--;
2626 }
Victor Stinner96865452011-03-01 23:44:09 +00002627
2628 /* Handle %ld, %lu, %lld and %llu. */
2629 longflag = 0;
2630 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002631 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002632 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002633 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002634 longflag = 1;
2635 ++f;
2636 }
Victor Stinner96865452011-03-01 23:44:09 +00002637 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002639 longlongflag = 1;
2640 f += 2;
2641 }
Victor Stinner96865452011-03-01 23:44:09 +00002642 }
2643 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002644 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002645 size_tflag = 1;
2646 ++f;
2647 }
Victor Stinnere215d962012-10-06 23:03:36 +02002648
2649 if (f[1] == '\0')
2650 writer->overallocate = 0;
2651
2652 switch (*f) {
2653 case 'c':
2654 {
2655 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002656 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002657 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 "character argument not in range(0x110000)");
2659 return NULL;
2660 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002661 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002662 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002663 break;
2664 }
2665
2666 case 'i':
2667 case 'd':
2668 case 'u':
2669 case 'x':
2670 {
2671 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002672 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002673 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002674
2675 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002676 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002677 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002678 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002679 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002680 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002681 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002683 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002684 va_arg(*vargs, size_t));
2685 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, unsigned int));
2688 }
2689 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002691 }
2692 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002694 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002695 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002696 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002697 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002698 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002700 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002701 va_arg(*vargs, Py_ssize_t));
2702 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, int));
2705 }
2706 assert(len >= 0);
2707
Victor Stinnere215d962012-10-06 23:03:36 +02002708 if (precision < len)
2709 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002710
2711 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2713 return NULL;
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (width > precision) {
2716 Py_UCS4 fillchar;
2717 fill = width - precision;
2718 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002719 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2720 return NULL;
2721 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002722 }
Victor Stinner15a11362012-10-06 23:48:20 +02002723 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002724 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2726 return NULL;
2727 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002728 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002729
Victor Stinner4a587072013-11-19 12:54:53 +01002730 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2731 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002732 break;
2733 }
2734
2735 case 'p':
2736 {
2737 char number[MAX_LONG_LONG_CHARS];
2738
2739 len = sprintf(number, "%p", va_arg(*vargs, void*));
2740 assert(len >= 0);
2741
2742 /* %p is ill-defined: ensure leading 0x. */
2743 if (number[1] == 'X')
2744 number[1] = 'x';
2745 else if (number[1] != 'x') {
2746 memmove(number + 2, number,
2747 strlen(number) + 1);
2748 number[0] = '0';
2749 number[1] = 'x';
2750 len += 2;
2751 }
2752
Victor Stinner4a587072013-11-19 12:54:53 +01002753 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002754 return NULL;
2755 break;
2756 }
2757
2758 case 's':
2759 {
2760 /* UTF-8 */
2761 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002762 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002763 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002764 break;
2765 }
2766
2767 case 'U':
2768 {
2769 PyObject *obj = va_arg(*vargs, PyObject *);
2770 assert(obj && _PyUnicode_CHECK(obj));
2771
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002772 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002773 return NULL;
2774 break;
2775 }
2776
2777 case 'V':
2778 {
2779 PyObject *obj = va_arg(*vargs, PyObject *);
2780 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002781 if (obj) {
2782 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002783 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002784 return NULL;
2785 }
2786 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002787 assert(str != NULL);
2788 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002789 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002790 }
2791 break;
2792 }
2793
2794 case 'S':
2795 {
2796 PyObject *obj = va_arg(*vargs, PyObject *);
2797 PyObject *str;
2798 assert(obj);
2799 str = PyObject_Str(obj);
2800 if (!str)
2801 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002802 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002803 Py_DECREF(str);
2804 return NULL;
2805 }
2806 Py_DECREF(str);
2807 break;
2808 }
2809
2810 case 'R':
2811 {
2812 PyObject *obj = va_arg(*vargs, PyObject *);
2813 PyObject *repr;
2814 assert(obj);
2815 repr = PyObject_Repr(obj);
2816 if (!repr)
2817 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002818 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002819 Py_DECREF(repr);
2820 return NULL;
2821 }
2822 Py_DECREF(repr);
2823 break;
2824 }
2825
2826 case 'A':
2827 {
2828 PyObject *obj = va_arg(*vargs, PyObject *);
2829 PyObject *ascii;
2830 assert(obj);
2831 ascii = PyObject_ASCII(obj);
2832 if (!ascii)
2833 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002834 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002835 Py_DECREF(ascii);
2836 return NULL;
2837 }
2838 Py_DECREF(ascii);
2839 break;
2840 }
2841
2842 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002843 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002844 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002845 break;
2846
2847 default:
2848 /* if we stumble upon an unknown formatting code, copy the rest
2849 of the format string to the output string. (we cannot just
2850 skip the code, since there's no way to know what's in the
2851 argument list) */
2852 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002853 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002854 return NULL;
2855 f = p+len;
2856 return f;
2857 }
2858
2859 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002860 return f;
2861}
2862
Walter Dörwaldd2034312007-05-18 16:29:38 +00002863PyObject *
2864PyUnicode_FromFormatV(const char *format, va_list vargs)
2865{
Victor Stinnere215d962012-10-06 23:03:36 +02002866 va_list vargs2;
2867 const char *f;
2868 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002869
Victor Stinner8f674cc2013-04-17 23:02:17 +02002870 _PyUnicodeWriter_Init(&writer);
2871 writer.min_length = strlen(format) + 100;
2872 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002873
Benjamin Peterson0c212142016-09-20 20:39:33 -07002874 // Copy varags to be able to pass a reference to a subfunction.
2875 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002876
2877 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002878 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002879 f = unicode_fromformat_arg(&writer, f, &vargs2);
2880 if (f == NULL)
2881 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002884 const char *p;
2885 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002886
Victor Stinnere215d962012-10-06 23:03:36 +02002887 p = f;
2888 do
2889 {
2890 if ((unsigned char)*p > 127) {
2891 PyErr_Format(PyExc_ValueError,
2892 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2893 "string, got a non-ASCII byte: 0x%02x",
2894 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002895 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002896 }
2897 p++;
2898 }
2899 while (*p != '\0' && *p != '%');
2900 len = p - f;
2901
2902 if (*p == '\0')
2903 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002904
2905 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002906 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002907
2908 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002909 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002910 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002911 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002912 return _PyUnicodeWriter_Finish(&writer);
2913
2914 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002915 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002916 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002918}
2919
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920PyObject *
2921PyUnicode_FromFormat(const char *format, ...)
2922{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002923 PyObject* ret;
2924 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
2926#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002927 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 ret = PyUnicode_FromFormatV(format, vargs);
2932 va_end(vargs);
2933 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002934}
2935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002936#ifdef HAVE_WCHAR_H
2937
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002938/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939
Victor Stinnerd88d9832011-09-06 02:00:05 +02002940 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941 character) required to convert the unicode object. Ignore size argument.
2942
Victor Stinnerd88d9832011-09-06 02:00:05 +02002943 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002944 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002946Py_ssize_t
2947PyUnicode_AsWideChar(PyObject *unicode,
2948 wchar_t *w,
2949 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00002950{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002951 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002952 const wchar_t *wstr;
2953
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002954 if (unicode == NULL) {
2955 PyErr_BadInternalCall();
2956 return -1;
2957 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
Victor Stinner137c34c2010-09-29 10:25:54 +00002974wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002975PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 Py_ssize_t *size)
2977{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002978 const wchar_t *wstr;
2979 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 Py_ssize_t buflen;
2981
2982 if (unicode == NULL) {
2983 PyErr_BadInternalCall();
2984 return NULL;
2985 }
2986
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002987 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
2988 if (wstr == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002989 return NULL;
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03002990 }
2991 if (size == NULL && wcslen(wstr) != (size_t)buflen) {
2992 PyErr_SetString(PyExc_ValueError,
2993 "embedded null character");
2994 return NULL;
2995 }
2996
2997 buffer = PyMem_NEW(wchar_t, buflen + 1);
Victor Stinner137c34c2010-09-29 10:25:54 +00002998 if (buffer == NULL) {
2999 PyErr_NoMemory();
3000 return NULL;
3001 }
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003002 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00003003 if (size != NULL)
3004 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003005 return buffer;
3006}
3007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003008#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003012{
Victor Stinner8faf8212011-12-08 22:14:11 +01003013 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 PyErr_SetString(PyExc_ValueError,
3015 "chr() arg not in range(0x110000)");
3016 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003017 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003018
Victor Stinner985a82a2014-01-03 12:53:47 +01003019 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020}
3021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003023PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003025 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003027 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003028 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003029 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003030 Py_INCREF(obj);
3031 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 }
3033 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 /* For a Unicode subtype that's not a Unicode object,
3035 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003036 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003038 PyErr_Format(PyExc_TypeError,
3039 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003040 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003041 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003042}
3043
Alexander Belopolsky40018472011-02-26 01:02:56 +00003044PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003045PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003046 const char *encoding,
3047 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003049 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003051
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 PyErr_BadInternalCall();
3054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003055 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 /* Decoding bytes objects is the most common case and should be fast */
3058 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003059 if (PyBytes_GET_SIZE(obj) == 0)
3060 _Py_RETURN_UNICODE_EMPTY();
3061 v = PyUnicode_Decode(
3062 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3063 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 return v;
3065 }
3066
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003067 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 PyErr_SetString(PyExc_TypeError,
3069 "decoding str is not supported");
3070 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003071 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003072
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003073 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3074 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3075 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003076 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003077 Py_TYPE(obj)->tp_name);
3078 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003079 }
Tim Petersced69f82003-09-16 20:30:58 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003082 PyBuffer_Release(&buffer);
3083 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003085
Serhiy Storchaka05997252013-01-26 12:14:02 +02003086 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003088 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089}
3090
Victor Stinnerebe17e02016-10-12 13:57:45 +02003091/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3092 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3093 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003094int
3095_Py_normalize_encoding(const char *encoding,
3096 char *lower,
3097 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003099 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003100 char *l;
3101 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003102 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003103
Victor Stinner942889a2016-09-05 15:40:10 -07003104 assert(encoding != NULL);
3105
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003106 e = encoding;
3107 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003109 punct = 0;
3110 while (1) {
3111 char c = *e;
3112 if (c == 0) {
3113 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 }
Victor Stinner942889a2016-09-05 15:40:10 -07003115
3116 if (Py_ISALNUM(c) || c == '.') {
3117 if (punct && l != lower) {
3118 if (l == l_end) {
3119 return 0;
3120 }
3121 *l++ = '_';
3122 }
3123 punct = 0;
3124
3125 if (l == l_end) {
3126 return 0;
3127 }
3128 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003129 }
3130 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003131 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003132 }
Victor Stinner942889a2016-09-05 15:40:10 -07003133
3134 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003137 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003138}
3139
Alexander Belopolsky40018472011-02-26 01:02:56 +00003140PyObject *
3141PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003142 Py_ssize_t size,
3143 const char *encoding,
3144 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003145{
3146 PyObject *buffer = NULL, *unicode;
3147 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003148 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3149
3150 if (encoding == NULL) {
3151 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3152 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003153
Fred Drakee4315f52000-05-09 19:53:39 +00003154 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003155 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3156 char *lower = buflower;
3157
3158 /* Fast paths */
3159 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3160 lower += 3;
3161 if (*lower == '_') {
3162 /* Match "utf8" and "utf_8" */
3163 lower++;
3164 }
3165
3166 if (lower[0] == '8' && lower[1] == 0) {
3167 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3168 }
3169 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3170 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3171 }
3172 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3173 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3174 }
3175 }
3176 else {
3177 if (strcmp(lower, "ascii") == 0
3178 || strcmp(lower, "us_ascii") == 0) {
3179 return PyUnicode_DecodeASCII(s, size, errors);
3180 }
Steve Dowercc16be82016-09-08 10:35:16 -07003181 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003182 else if (strcmp(lower, "mbcs") == 0) {
3183 return PyUnicode_DecodeMBCS(s, size, errors);
3184 }
3185 #endif
3186 else if (strcmp(lower, "latin1") == 0
3187 || strcmp(lower, "latin_1") == 0
3188 || strcmp(lower, "iso_8859_1") == 0
3189 || strcmp(lower, "iso8859_1") == 0) {
3190 return PyUnicode_DecodeLatin1(s, size, errors);
3191 }
3192 }
Victor Stinner37296e82010-06-10 13:36:23 +00003193 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003194
3195 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003196 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003197 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003198 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003199 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200 if (buffer == NULL)
3201 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003202 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003203 if (unicode == NULL)
3204 goto onError;
3205 if (!PyUnicode_Check(unicode)) {
3206 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003207 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3208 "use codecs.decode() to decode to arbitrary types",
3209 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003210 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 Py_DECREF(unicode);
3212 goto onError;
3213 }
3214 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003215 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003216
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 Py_XDECREF(buffer);
3219 return NULL;
3220}
3221
Alexander Belopolsky40018472011-02-26 01:02:56 +00003222PyObject *
3223PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003224 const char *encoding,
3225 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003226{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003227 if (!PyUnicode_Check(unicode)) {
3228 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003229 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003230 }
3231
Serhiy Storchaka00939072016-10-27 21:05:49 +03003232 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3233 "PyUnicode_AsDecodedObject() is deprecated; "
3234 "use PyCodec_Decode() to decode from str", 1) < 0)
3235 return NULL;
3236
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003237 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003238 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003239
3240 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003241 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242}
3243
Alexander Belopolsky40018472011-02-26 01:02:56 +00003244PyObject *
3245PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003246 const char *encoding,
3247 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003248{
3249 PyObject *v;
3250
3251 if (!PyUnicode_Check(unicode)) {
3252 PyErr_BadArgument();
3253 goto onError;
3254 }
3255
Serhiy Storchaka00939072016-10-27 21:05:49 +03003256 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3257 "PyUnicode_AsDecodedUnicode() is deprecated; "
3258 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3259 return NULL;
3260
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003261 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003262 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003263
3264 /* Decode via the codec registry */
3265 v = PyCodec_Decode(unicode, encoding, errors);
3266 if (v == NULL)
3267 goto onError;
3268 if (!PyUnicode_Check(v)) {
3269 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003270 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3271 "use codecs.decode() to decode to arbitrary types",
3272 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003273 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003274 Py_DECREF(v);
3275 goto onError;
3276 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003277 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278
Benjamin Peterson29060642009-01-31 22:14:21 +00003279 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003280 return NULL;
3281}
3282
Alexander Belopolsky40018472011-02-26 01:02:56 +00003283PyObject *
3284PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003285 Py_ssize_t size,
3286 const char *encoding,
3287 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288{
3289 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003290
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003291 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3295 Py_DECREF(unicode);
3296 return v;
3297}
3298
Alexander Belopolsky40018472011-02-26 01:02:56 +00003299PyObject *
3300PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003301 const char *encoding,
3302 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003303{
3304 PyObject *v;
3305
3306 if (!PyUnicode_Check(unicode)) {
3307 PyErr_BadArgument();
3308 goto onError;
3309 }
3310
Serhiy Storchaka00939072016-10-27 21:05:49 +03003311 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3312 "PyUnicode_AsEncodedObject() is deprecated; "
3313 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3314 "or PyCodec_Encode() for generic encoding", 1) < 0)
3315 return NULL;
3316
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003318 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003319
3320 /* Encode via the codec registry */
3321 v = PyCodec_Encode(unicode, encoding, errors);
3322 if (v == NULL)
3323 goto onError;
3324 return v;
3325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327 return NULL;
3328}
3329
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003330static size_t
3331wcstombs_errorpos(const wchar_t *wstr)
3332{
3333 size_t len;
3334#if SIZEOF_WCHAR_T == 2
3335 wchar_t buf[3];
3336#else
3337 wchar_t buf[2];
3338#endif
3339 char outbuf[MB_LEN_MAX];
3340 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003341
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003342#if SIZEOF_WCHAR_T == 2
3343 buf[2] = 0;
3344#else
3345 buf[1] = 0;
3346#endif
3347 start = wstr;
3348 while (*wstr != L'\0')
3349 {
3350 previous = wstr;
3351#if SIZEOF_WCHAR_T == 2
3352 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3353 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3354 {
3355 buf[0] = wstr[0];
3356 buf[1] = wstr[1];
3357 wstr += 2;
3358 }
3359 else {
3360 buf[0] = *wstr;
3361 buf[1] = 0;
3362 wstr++;
3363 }
3364#else
3365 buf[0] = *wstr;
3366 wstr++;
3367#endif
3368 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003369 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 }
3372
3373 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return 0;
3375}
3376
Victor Stinner1b579672011-12-17 05:47:23 +01003377static int
3378locale_error_handler(const char *errors, int *surrogateescape)
3379{
Victor Stinner50149202015-09-22 00:26:54 +02003380 _Py_error_handler error_handler = get_error_handler(errors);
3381 switch (error_handler)
3382 {
3383 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003384 *surrogateescape = 0;
3385 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003386 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003387 *surrogateescape = 1;
3388 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003389 default:
3390 PyErr_Format(PyExc_ValueError,
3391 "only 'strict' and 'surrogateescape' error handlers "
3392 "are supported, not '%s'",
3393 errors);
3394 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003395 }
Victor Stinner1b579672011-12-17 05:47:23 +01003396}
3397
Victor Stinner2cba6b82018-01-10 22:46:15 +01003398static PyObject *
3399unicode_encode_locale(PyObject *unicode, const char *errors, int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003400{
3401 Py_ssize_t wlen, wlen2;
3402 wchar_t *wstr;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003403 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003404 PyObject *bytes, *reason, *exc;
3405 size_t error_pos, errlen;
Victor Stinner1b579672011-12-17 05:47:23 +01003406 int surrogateescape;
3407
3408 if (locale_error_handler(errors, &surrogateescape) < 0)
3409 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410
3411 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3412 if (wstr == NULL)
3413 return NULL;
3414
3415 wlen2 = wcslen(wstr);
3416 if (wlen2 != wlen) {
3417 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003418 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003419 return NULL;
3420 }
3421
3422 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003423 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424 char *str;
3425
Victor Stinner2cba6b82018-01-10 22:46:15 +01003426 if (current_locale) {
3427 str = _Py_EncodeCurrentLocale(wstr, &error_pos);
3428 }
3429 else {
3430 str = Py_EncodeLocale(wstr, &error_pos);
3431 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003432 if (str == NULL) {
3433 if (error_pos == (size_t)-1) {
3434 PyErr_NoMemory();
3435 PyMem_Free(wstr);
3436 return NULL;
3437 }
3438 else {
3439 goto encode_error;
3440 }
3441 }
3442 PyMem_Free(wstr);
3443
3444 bytes = PyBytes_FromString(str);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003445 if (current_locale) {
3446 PyMem_RawFree(str);
3447 }
3448 else {
3449 PyMem_Free(str);
3450 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003451 }
3452 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003453 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003454 size_t len, len2;
3455
3456 len = wcstombs(NULL, wstr, 0);
3457 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003458 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003459 goto encode_error;
3460 }
3461
3462 bytes = PyBytes_FromStringAndSize(NULL, len);
3463 if (bytes == NULL) {
3464 PyMem_Free(wstr);
3465 return NULL;
3466 }
3467
3468 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3469 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003470 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003471 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003472 goto encode_error;
3473 }
3474 PyMem_Free(wstr);
3475 }
3476 return bytes;
3477
3478encode_error:
3479 errmsg = strerror(errno);
3480 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003481
3482 if (error_pos == (size_t)-1)
3483 error_pos = wcstombs_errorpos(wstr);
3484
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003485 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003486
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003487 wstr = Py_DecodeLocale(errmsg, &errlen);
3488 if (wstr != NULL) {
3489 reason = PyUnicode_FromWideChar(wstr, errlen);
3490 PyMem_RawFree(wstr);
3491 } else {
3492 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003493 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003494
Victor Stinner2f197072011-12-17 07:08:30 +01003495 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003496 reason = PyUnicode_FromString(
3497 "wcstombs() encountered an unencodable "
3498 "wide character");
3499 if (reason == NULL)
3500 return NULL;
3501
3502 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3503 "locale", unicode,
3504 (Py_ssize_t)error_pos,
3505 (Py_ssize_t)(error_pos+1),
3506 reason);
3507 Py_DECREF(reason);
3508 if (exc != NULL) {
3509 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003510 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003511 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003512 return NULL;
3513}
3514
Victor Stinnerad158722010-10-27 00:25:46 +00003515PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003516PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3517{
3518 return unicode_encode_locale(unicode, errors, 0);
3519}
3520
3521PyObject *
3522_PyUnicode_EncodeCurrentLocale(PyObject *unicode, const char *errors)
3523{
3524 return unicode_encode_locale(unicode, errors, 1);
3525}
3526
3527PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003528PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003529{
Steve Dowercc16be82016-09-08 10:35:16 -07003530#if defined(__APPLE__)
3531 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003532#else
Victor Stinner793b5312011-04-27 00:24:21 +02003533 PyInterpreterState *interp = PyThreadState_GET()->interp;
3534 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3535 cannot use it to encode and decode filenames before it is loaded. Load
3536 the Python codec requires to encode at least its own filename. Use the C
3537 version of the locale codec until the codec registry is initialized and
3538 the Python codec is loaded.
3539
3540 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3541 cannot only rely on it: check also interp->fscodec_initialized for
3542 subinterpreters. */
3543 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003544 return PyUnicode_AsEncodedString(unicode,
3545 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003546 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003547 }
3548 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003549 return unicode_encode_locale(unicode,
3550 Py_FileSystemDefaultEncodeErrors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003551 }
Victor Stinnerad158722010-10-27 00:25:46 +00003552#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003553}
3554
Alexander Belopolsky40018472011-02-26 01:02:56 +00003555PyObject *
3556PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003557 const char *encoding,
3558 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003559{
3560 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003561 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003562
Guido van Rossumd57fd912000-03-10 22:53:23 +00003563 if (!PyUnicode_Check(unicode)) {
3564 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003565 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003566 }
Fred Drakee4315f52000-05-09 19:53:39 +00003567
Victor Stinner942889a2016-09-05 15:40:10 -07003568 if (encoding == NULL) {
3569 return _PyUnicode_AsUTF8String(unicode, errors);
3570 }
3571
Fred Drakee4315f52000-05-09 19:53:39 +00003572 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003573 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3574 char *lower = buflower;
3575
3576 /* Fast paths */
3577 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3578 lower += 3;
3579 if (*lower == '_') {
3580 /* Match "utf8" and "utf_8" */
3581 lower++;
3582 }
3583
3584 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003585 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003586 }
3587 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3588 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3589 }
3590 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3591 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3592 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003593 }
Victor Stinner942889a2016-09-05 15:40:10 -07003594 else {
3595 if (strcmp(lower, "ascii") == 0
3596 || strcmp(lower, "us_ascii") == 0) {
3597 return _PyUnicode_AsASCIIString(unicode, errors);
3598 }
Steve Dowercc16be82016-09-08 10:35:16 -07003599#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003600 else if (strcmp(lower, "mbcs") == 0) {
3601 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3602 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003603#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003604 else if (strcmp(lower, "latin1") == 0 ||
3605 strcmp(lower, "latin_1") == 0 ||
3606 strcmp(lower, "iso_8859_1") == 0 ||
3607 strcmp(lower, "iso8859_1") == 0) {
3608 return _PyUnicode_AsLatin1String(unicode, errors);
3609 }
3610 }
Victor Stinner37296e82010-06-10 13:36:23 +00003611 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003612
3613 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003614 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003615 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003616 return NULL;
3617
3618 /* The normal path */
3619 if (PyBytes_Check(v))
3620 return v;
3621
3622 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003623 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003624 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003625 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003626
3627 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003628 "encoder %s returned bytearray instead of bytes; "
3629 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003630 encoding);
3631 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003632 Py_DECREF(v);
3633 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003634 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003635
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003636 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3637 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003638 Py_DECREF(v);
3639 return b;
3640 }
3641
3642 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003643 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3644 "use codecs.encode() to encode to arbitrary types",
3645 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003646 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003647 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003648 return NULL;
3649}
3650
Alexander Belopolsky40018472011-02-26 01:02:56 +00003651PyObject *
3652PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003653 const char *encoding,
3654 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003655{
3656 PyObject *v;
3657
3658 if (!PyUnicode_Check(unicode)) {
3659 PyErr_BadArgument();
3660 goto onError;
3661 }
3662
Serhiy Storchaka00939072016-10-27 21:05:49 +03003663 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3664 "PyUnicode_AsEncodedUnicode() is deprecated; "
3665 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3666 return NULL;
3667
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003668 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003670
3671 /* Encode via the codec registry */
3672 v = PyCodec_Encode(unicode, encoding, errors);
3673 if (v == NULL)
3674 goto onError;
3675 if (!PyUnicode_Check(v)) {
3676 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003677 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3678 "use codecs.encode() to encode to arbitrary types",
3679 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003680 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003681 Py_DECREF(v);
3682 goto onError;
3683 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003684 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003685
Benjamin Peterson29060642009-01-31 22:14:21 +00003686 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003687 return NULL;
3688}
3689
Victor Stinner2f197072011-12-17 07:08:30 +01003690static size_t
3691mbstowcs_errorpos(const char *str, size_t len)
3692{
3693#ifdef HAVE_MBRTOWC
3694 const char *start = str;
3695 mbstate_t mbs;
3696 size_t converted;
3697 wchar_t ch;
3698
3699 memset(&mbs, 0, sizeof mbs);
3700 while (len)
3701 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003702 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003703 if (converted == 0)
3704 /* Reached end of string */
3705 break;
3706 if (converted == (size_t)-1 || converted == (size_t)-2) {
3707 /* Conversion error or incomplete character */
3708 return str - start;
3709 }
3710 else {
3711 str += converted;
3712 len -= converted;
3713 }
3714 }
3715 /* failed to find the undecodable byte sequence */
3716 return 0;
3717#endif
3718 return 0;
3719}
3720
Victor Stinner2cba6b82018-01-10 22:46:15 +01003721static PyObject*
3722unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3723 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003724{
3725 wchar_t smallbuf[256];
3726 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3727 wchar_t *wstr;
3728 size_t wlen, wlen2;
3729 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003730 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003731 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003732 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003733 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003734
3735 if (locale_error_handler(errors, &surrogateescape) < 0)
3736 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003737
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003738 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3739 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003740 return NULL;
3741 }
3742
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003743 if (surrogateescape) {
3744 /* "surrogateescape" error handler */
Victor Stinner2cba6b82018-01-10 22:46:15 +01003745 if (current_locale) {
3746 wstr = _Py_DecodeCurrentLocale(str, &wlen);
3747 }
3748 else {
3749 wstr = Py_DecodeLocale(str, &wlen);
3750 }
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003751 if (wstr == NULL) {
3752 if (wlen == (size_t)-1)
3753 PyErr_NoMemory();
3754 else
3755 PyErr_SetFromErrno(PyExc_OSError);
3756 return NULL;
3757 }
3758
3759 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003760 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003761 }
3762 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003763 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003764#ifndef HAVE_BROKEN_MBSTOWCS
3765 wlen = mbstowcs(NULL, str, 0);
3766#else
3767 wlen = len;
3768#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003769 if (wlen == (size_t)-1)
3770 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003771 if (wlen+1 <= smallbuf_len) {
3772 wstr = smallbuf;
3773 }
3774 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003775 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003776 if (!wstr)
3777 return PyErr_NoMemory();
3778 }
3779
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003780 wlen2 = mbstowcs(wstr, str, wlen+1);
3781 if (wlen2 == (size_t)-1) {
3782 if (wstr != smallbuf)
3783 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003784 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003785 }
3786#ifdef HAVE_BROKEN_MBSTOWCS
3787 assert(wlen2 == wlen);
3788#endif
3789 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3790 if (wstr != smallbuf)
3791 PyMem_Free(wstr);
3792 }
3793 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003794
3795decode_error:
3796 errmsg = strerror(errno);
3797 assert(errmsg != NULL);
3798
3799 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003800 wstr = Py_DecodeLocale(errmsg, &errlen);
3801 if (wstr != NULL) {
3802 reason = PyUnicode_FromWideChar(wstr, errlen);
3803 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003804 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003805
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003806 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003807 reason = PyUnicode_FromString(
3808 "mbstowcs() encountered an invalid multibyte sequence");
3809 if (reason == NULL)
3810 return NULL;
3811
3812 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3813 "locale", str, len,
3814 (Py_ssize_t)error_pos,
3815 (Py_ssize_t)(error_pos+1),
3816 reason);
3817 Py_DECREF(reason);
3818 if (exc != NULL) {
3819 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003820 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003821 }
3822 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003823}
3824
3825PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003826PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3827 const char *errors)
3828{
3829 return unicode_decode_locale(str, len, errors, 0);
3830}
3831
3832PyObject*
3833_PyUnicode_DecodeCurrentLocaleAndSize(const char *str, Py_ssize_t len,
3834 const char *errors)
3835{
3836 return unicode_decode_locale(str, len, errors, 1);
3837}
3838
3839PyObject*
Victor Stinnercb3ae552018-01-11 10:37:59 +01003840_PyUnicode_DecodeCurrentLocale(const char *str, const char *errors)
3841{
3842 return unicode_decode_locale(str, (Py_ssize_t)strlen(str), errors, 1);
3843}
3844
3845PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003846PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003847{
3848 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003849 return unicode_decode_locale(str, size, errors, 0);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003850}
3851
3852
3853PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003854PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003855 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003856 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3857}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003858
Christian Heimes5894ba72007-11-04 11:43:14 +00003859PyObject*
3860PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3861{
Steve Dowercc16be82016-09-08 10:35:16 -07003862#if defined(__APPLE__)
3863 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003864#else
Victor Stinner793b5312011-04-27 00:24:21 +02003865 PyInterpreterState *interp = PyThreadState_GET()->interp;
3866 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3867 cannot use it to encode and decode filenames before it is loaded. Load
3868 the Python codec requires to encode at least its own filename. Use the C
3869 version of the locale codec until the codec registry is initialized and
3870 the Python codec is loaded.
3871
3872 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3873 cannot only rely on it: check also interp->fscodec_initialized for
3874 subinterpreters. */
3875 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003876 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003877 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003878 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003879 }
3880 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003881 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003882 }
Victor Stinnerad158722010-10-27 00:25:46 +00003883#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003884}
3885
Martin v. Löwis011e8422009-05-05 04:43:17 +00003886
3887int
3888PyUnicode_FSConverter(PyObject* arg, void* addr)
3889{
Brett Cannonec6ce872016-09-06 15:50:29 -07003890 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003891 PyObject *output = NULL;
3892 Py_ssize_t size;
3893 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003894 if (arg == NULL) {
3895 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003896 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003897 return 1;
3898 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003899 path = PyOS_FSPath(arg);
3900 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003901 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003902 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003903 if (PyBytes_Check(path)) {
3904 output = path;
3905 }
3906 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3907 output = PyUnicode_EncodeFSDefault(path);
3908 Py_DECREF(path);
3909 if (!output) {
3910 return 0;
3911 }
3912 assert(PyBytes_Check(output));
3913 }
3914
Victor Stinner0ea2a462010-04-30 00:22:08 +00003915 size = PyBytes_GET_SIZE(output);
3916 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003917 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003918 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003919 Py_DECREF(output);
3920 return 0;
3921 }
3922 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003923 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003924}
3925
3926
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003927int
3928PyUnicode_FSDecoder(PyObject* arg, void* addr)
3929{
Brett Cannona5711202016-09-06 19:36:01 -07003930 int is_buffer = 0;
3931 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003932 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003933 if (arg == NULL) {
3934 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003935 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003936 return 1;
3937 }
Brett Cannona5711202016-09-06 19:36:01 -07003938
3939 is_buffer = PyObject_CheckBuffer(arg);
3940 if (!is_buffer) {
3941 path = PyOS_FSPath(arg);
3942 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003943 return 0;
3944 }
Brett Cannona5711202016-09-06 19:36:01 -07003945 }
3946 else {
3947 path = arg;
3948 Py_INCREF(arg);
3949 }
3950
3951 if (PyUnicode_Check(path)) {
3952 if (PyUnicode_READY(path) == -1) {
3953 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003954 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003955 }
3956 output = path;
3957 }
3958 else if (PyBytes_Check(path) || is_buffer) {
3959 PyObject *path_bytes = NULL;
3960
3961 if (!PyBytes_Check(path) &&
3962 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3963 "path should be string, bytes, or os.PathLike, not %.200s",
3964 Py_TYPE(arg)->tp_name)) {
3965 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003966 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003967 }
3968 path_bytes = PyBytes_FromObject(path);
3969 Py_DECREF(path);
3970 if (!path_bytes) {
3971 return 0;
3972 }
3973 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3974 PyBytes_GET_SIZE(path_bytes));
3975 Py_DECREF(path_bytes);
3976 if (!output) {
3977 return 0;
3978 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003979 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003980 else {
3981 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003982 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003983 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003984 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003985 return 0;
3986 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003987 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003988 Py_DECREF(output);
3989 return 0;
3990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003991 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003992 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003993 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003994 Py_DECREF(output);
3995 return 0;
3996 }
3997 *(PyObject**)addr = output;
3998 return Py_CLEANUP_SUPPORTED;
3999}
4000
4001
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02004002const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004004{
Christian Heimesf3863112007-11-22 07:46:41 +00004005 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004006
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00004007 if (!PyUnicode_Check(unicode)) {
4008 PyErr_BadArgument();
4009 return NULL;
4010 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004011 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004012 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004013
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004014 if (PyUnicode_UTF8(unicode) == NULL) {
4015 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03004016 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004017 if (bytes == NULL)
4018 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004019 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
4020 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01004021 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022 Py_DECREF(bytes);
4023 return NULL;
4024 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004025 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02004026 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004027 PyBytes_AS_STRING(bytes),
4028 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029 Py_DECREF(bytes);
4030 }
4031
4032 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004033 *psize = PyUnicode_UTF8_LENGTH(unicode);
4034 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004035}
4036
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02004037const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4041}
4042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043Py_UNICODE *
4044PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4045{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 const unsigned char *one_byte;
4047#if SIZEOF_WCHAR_T == 4
4048 const Py_UCS2 *two_bytes;
4049#else
4050 const Py_UCS4 *four_bytes;
4051 const Py_UCS4 *ucs4_end;
4052 Py_ssize_t num_surrogates;
4053#endif
4054 wchar_t *w;
4055 wchar_t *wchar_end;
4056
4057 if (!PyUnicode_Check(unicode)) {
4058 PyErr_BadArgument();
4059 return NULL;
4060 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004061 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004062 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004063 assert(_PyUnicode_KIND(unicode) != 0);
4064 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004065
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004066 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004067#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004068 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4069 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004070 num_surrogates = 0;
4071
4072 for (; four_bytes < ucs4_end; ++four_bytes) {
4073 if (*four_bytes > 0xFFFF)
4074 ++num_surrogates;
4075 }
4076
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004077 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4078 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4079 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004080 PyErr_NoMemory();
4081 return NULL;
4082 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004083 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004084
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004085 w = _PyUnicode_WSTR(unicode);
4086 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4087 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004088 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4089 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004090 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004091 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004092 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4093 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004094 }
4095 else
4096 *w = *four_bytes;
4097
4098 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07004099 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004100 }
4101 }
4102 *w = 0;
4103#else
4104 /* sizeof(wchar_t) == 4 */
4105 Py_FatalError("Impossible unicode object state, wstr and str "
4106 "should share memory already.");
4107 return NULL;
4108#endif
4109 }
4110 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004111 if ((size_t)_PyUnicode_LENGTH(unicode) >
4112 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4113 PyErr_NoMemory();
4114 return NULL;
4115 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004116 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4117 (_PyUnicode_LENGTH(unicode) + 1));
4118 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004119 PyErr_NoMemory();
4120 return NULL;
4121 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004122 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4123 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4124 w = _PyUnicode_WSTR(unicode);
4125 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004126
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004127 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4128 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004129 for (; w < wchar_end; ++one_byte, ++w)
4130 *w = *one_byte;
4131 /* null-terminate the wstr */
4132 *w = 0;
4133 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004134 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004135#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004136 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004137 for (; w < wchar_end; ++two_bytes, ++w)
4138 *w = *two_bytes;
4139 /* null-terminate the wstr */
4140 *w = 0;
4141#else
4142 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004143 PyObject_FREE(_PyUnicode_WSTR(unicode));
4144 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004145 Py_FatalError("Impossible unicode object state, wstr "
4146 "and str should share memory already.");
4147 return NULL;
4148#endif
4149 }
4150 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07004151 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004152 }
4153 }
4154 }
4155 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004156 *size = PyUnicode_WSTR_LENGTH(unicode);
4157 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004158}
4159
Alexander Belopolsky40018472011-02-26 01:02:56 +00004160Py_UNICODE *
4161PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004163 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004164}
4165
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004166const Py_UNICODE *
4167_PyUnicode_AsUnicode(PyObject *unicode)
4168{
4169 Py_ssize_t size;
4170 const Py_UNICODE *wstr;
4171
4172 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4173 if (wstr && wcslen(wstr) != (size_t)size) {
4174 PyErr_SetString(PyExc_ValueError, "embedded null character");
4175 return NULL;
4176 }
4177 return wstr;
4178}
4179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004180
Alexander Belopolsky40018472011-02-26 01:02:56 +00004181Py_ssize_t
4182PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004183{
4184 if (!PyUnicode_Check(unicode)) {
4185 PyErr_BadArgument();
4186 goto onError;
4187 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004188 if (_PyUnicode_WSTR(unicode) == NULL) {
4189 if (PyUnicode_AsUnicode(unicode) == NULL)
4190 goto onError;
4191 }
4192 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004193
Benjamin Peterson29060642009-01-31 22:14:21 +00004194 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004195 return -1;
4196}
4197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004198Py_ssize_t
4199PyUnicode_GetLength(PyObject *unicode)
4200{
Victor Stinner07621332012-06-16 04:53:46 +02004201 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004202 PyErr_BadArgument();
4203 return -1;
4204 }
Victor Stinner07621332012-06-16 04:53:46 +02004205 if (PyUnicode_READY(unicode) == -1)
4206 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004207 return PyUnicode_GET_LENGTH(unicode);
4208}
4209
4210Py_UCS4
4211PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4212{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004213 void *data;
4214 int kind;
4215
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004216 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004217 PyErr_BadArgument();
4218 return (Py_UCS4)-1;
4219 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004220 if (PyUnicode_READY(unicode) == -1) {
4221 return (Py_UCS4)-1;
4222 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004223 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004224 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004225 return (Py_UCS4)-1;
4226 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004227 data = PyUnicode_DATA(unicode);
4228 kind = PyUnicode_KIND(unicode);
4229 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004230}
4231
4232int
4233PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4234{
4235 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004236 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004237 return -1;
4238 }
Victor Stinner488fa492011-12-12 00:01:39 +01004239 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004240 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004241 PyErr_SetString(PyExc_IndexError, "string index out of range");
4242 return -1;
4243 }
Victor Stinner488fa492011-12-12 00:01:39 +01004244 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004245 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004246 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4247 PyErr_SetString(PyExc_ValueError, "character out of range");
4248 return -1;
4249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004250 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4251 index, ch);
4252 return 0;
4253}
4254
Alexander Belopolsky40018472011-02-26 01:02:56 +00004255const char *
4256PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004257{
Victor Stinner42cb4622010-09-01 19:39:01 +00004258 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004259}
4260
Victor Stinner554f3f02010-06-16 23:33:54 +00004261/* create or adjust a UnicodeDecodeError */
4262static void
4263make_decode_exception(PyObject **exceptionObject,
4264 const char *encoding,
4265 const char *input, Py_ssize_t length,
4266 Py_ssize_t startpos, Py_ssize_t endpos,
4267 const char *reason)
4268{
4269 if (*exceptionObject == NULL) {
4270 *exceptionObject = PyUnicodeDecodeError_Create(
4271 encoding, input, length, startpos, endpos, reason);
4272 }
4273 else {
4274 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4275 goto onError;
4276 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4277 goto onError;
4278 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4279 goto onError;
4280 }
4281 return;
4282
4283onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004284 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004285}
4286
Steve Dowercc16be82016-09-08 10:35:16 -07004287#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004288/* error handling callback helper:
4289 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004290 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004291 and adjust various state variables.
4292 return 0 on success, -1 on error
4293*/
4294
Alexander Belopolsky40018472011-02-26 01:02:56 +00004295static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004296unicode_decode_call_errorhandler_wchar(
4297 const char *errors, PyObject **errorHandler,
4298 const char *encoding, const char *reason,
4299 const char **input, const char **inend, Py_ssize_t *startinpos,
4300 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4301 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004302{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004303 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004304
4305 PyObject *restuple = NULL;
4306 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004307 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004308 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004309 Py_ssize_t requiredsize;
4310 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004311 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004312 wchar_t *repwstr;
4313 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004314
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4316 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004317
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004318 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004319 *errorHandler = PyCodec_LookupError(errors);
4320 if (*errorHandler == NULL)
4321 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004322 }
4323
Victor Stinner554f3f02010-06-16 23:33:54 +00004324 make_decode_exception(exceptionObject,
4325 encoding,
4326 *input, *inend - *input,
4327 *startinpos, *endinpos,
4328 reason);
4329 if (*exceptionObject == NULL)
4330 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004331
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004332 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004333 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004335 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004336 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004337 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004338 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004339 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004340 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004341
4342 /* Copy back the bytes variables, which might have been modified by the
4343 callback */
4344 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4345 if (!inputobj)
4346 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004347 *input = PyBytes_AS_STRING(inputobj);
4348 insize = PyBytes_GET_SIZE(inputobj);
4349 *inend = *input + insize;
4350 /* we can DECREF safely, as the exception has another reference,
4351 so the object won't go away. */
4352 Py_DECREF(inputobj);
4353
4354 if (newpos<0)
4355 newpos = insize+newpos;
4356 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004357 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004358 goto onError;
4359 }
4360
4361 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4362 if (repwstr == NULL)
4363 goto onError;
4364 /* need more space? (at least enough for what we
4365 have+the replacement+the rest of the string (starting
4366 at the new input position), so we won't have to check space
4367 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004368 requiredsize = *outpos;
4369 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4370 goto overflow;
4371 requiredsize += repwlen;
4372 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4373 goto overflow;
4374 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004375 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004376 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004377 requiredsize = 2*outsize;
4378 if (unicode_resize(output, requiredsize) < 0)
4379 goto onError;
4380 }
4381 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4382 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004383 *endinpos = newpos;
4384 *inptr = *input + newpos;
4385
4386 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004387 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388 return 0;
4389
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004390 overflow:
4391 PyErr_SetString(PyExc_OverflowError,
4392 "decoded result is too long for a Python string");
4393
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004394 onError:
4395 Py_XDECREF(restuple);
4396 return -1;
4397}
Steve Dowercc16be82016-09-08 10:35:16 -07004398#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004399
4400static int
4401unicode_decode_call_errorhandler_writer(
4402 const char *errors, PyObject **errorHandler,
4403 const char *encoding, const char *reason,
4404 const char **input, const char **inend, Py_ssize_t *startinpos,
4405 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4406 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4407{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004408 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004409
4410 PyObject *restuple = NULL;
4411 PyObject *repunicode = NULL;
4412 Py_ssize_t insize;
4413 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004414 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004415 PyObject *inputobj = NULL;
4416
4417 if (*errorHandler == NULL) {
4418 *errorHandler = PyCodec_LookupError(errors);
4419 if (*errorHandler == NULL)
4420 goto onError;
4421 }
4422
4423 make_decode_exception(exceptionObject,
4424 encoding,
4425 *input, *inend - *input,
4426 *startinpos, *endinpos,
4427 reason);
4428 if (*exceptionObject == NULL)
4429 goto onError;
4430
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004431 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004432 if (restuple == NULL)
4433 goto onError;
4434 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004435 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436 goto onError;
4437 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004438 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004439 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004440
4441 /* Copy back the bytes variables, which might have been modified by the
4442 callback */
4443 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4444 if (!inputobj)
4445 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004446 *input = PyBytes_AS_STRING(inputobj);
4447 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004448 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004449 /* we can DECREF safely, as the exception has another reference,
4450 so the object won't go away. */
4451 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004452
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004453 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004454 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004455 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004456 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004458 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004459
Victor Stinner170ca6f2013-04-18 00:25:28 +02004460 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004461 if (replen > 1) {
4462 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004463 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004464 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4465 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4466 goto onError;
4467 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004468 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004469 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004471 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004472 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004473
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004474 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004475 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004476 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004477
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004479 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004480 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004481}
4482
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004483/* --- UTF-7 Codec -------------------------------------------------------- */
4484
Antoine Pitrou244651a2009-05-04 18:56:13 +00004485/* See RFC2152 for details. We encode conservatively and decode liberally. */
4486
4487/* Three simple macros defining base-64. */
4488
4489/* Is c a base-64 character? */
4490
4491#define IS_BASE64(c) \
4492 (((c) >= 'A' && (c) <= 'Z') || \
4493 ((c) >= 'a' && (c) <= 'z') || \
4494 ((c) >= '0' && (c) <= '9') || \
4495 (c) == '+' || (c) == '/')
4496
4497/* given that c is a base-64 character, what is its base-64 value? */
4498
4499#define FROM_BASE64(c) \
4500 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4501 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4502 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4503 (c) == '+' ? 62 : 63)
4504
4505/* What is the base-64 character of the bottom 6 bits of n? */
4506
4507#define TO_BASE64(n) \
4508 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4509
4510/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4511 * decoded as itself. We are permissive on decoding; the only ASCII
4512 * byte not decoding to itself is the + which begins a base64
4513 * string. */
4514
4515#define DECODE_DIRECT(c) \
4516 ((c) <= 127 && (c) != '+')
4517
4518/* The UTF-7 encoder treats ASCII characters differently according to
4519 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4520 * the above). See RFC2152. This array identifies these different
4521 * sets:
4522 * 0 : "Set D"
4523 * alphanumeric and '(),-./:?
4524 * 1 : "Set O"
4525 * !"#$%&*;<=>@[]^_`{|}
4526 * 2 : "whitespace"
4527 * ht nl cr sp
4528 * 3 : special (must be base64 encoded)
4529 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4530 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004531
Tim Petersced69f82003-09-16 20:30:58 +00004532static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533char utf7_category[128] = {
4534/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4535 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4536/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4537 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4538/* sp ! " # $ % & ' ( ) * + , - . / */
4539 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4540/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4542/* @ A B C D E F G H I J K L M N O */
4543 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4544/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4545 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4546/* ` a b c d e f g h i j k l m n o */
4547 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4548/* p q r s t u v w x y z { | } ~ del */
4549 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550};
4551
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552/* ENCODE_DIRECT: this character should be encoded as itself. The
4553 * answer depends on whether we are encoding set O as itself, and also
4554 * on whether we are encoding whitespace as itself. RFC2152 makes it
4555 * clear that the answers to these questions vary between
4556 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004557
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558#define ENCODE_DIRECT(c, directO, directWS) \
4559 ((c) < 128 && (c) > 0 && \
4560 ((utf7_category[(c)] == 0) || \
4561 (directWS && (utf7_category[(c)] == 2)) || \
4562 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004563
Alexander Belopolsky40018472011-02-26 01:02:56 +00004564PyObject *
4565PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004566 Py_ssize_t size,
4567 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004568{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004569 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4570}
4571
Antoine Pitrou244651a2009-05-04 18:56:13 +00004572/* The decoder. The only state we preserve is our read position,
4573 * i.e. how many characters we have consumed. So if we end in the
4574 * middle of a shift sequence we have to back off the read position
4575 * and the output to the beginning of the sequence, otherwise we lose
4576 * all the shift state (seen bits, number of bits seen, high
4577 * surrogate). */
4578
Alexander Belopolsky40018472011-02-26 01:02:56 +00004579PyObject *
4580PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004581 Py_ssize_t size,
4582 const char *errors,
4583 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004584{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004585 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004586 Py_ssize_t startinpos;
4587 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004589 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004590 const char *errmsg = "";
4591 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004592 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 unsigned int base64bits = 0;
4594 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004595 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004596 PyObject *errorHandler = NULL;
4597 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004599 if (size == 0) {
4600 if (consumed)
4601 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004602 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004603 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004605 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004606 _PyUnicodeWriter_Init(&writer);
4607 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004608
4609 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004610 e = s + size;
4611
4612 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004613 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004614 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004615 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004616
Antoine Pitrou244651a2009-05-04 18:56:13 +00004617 if (inShift) { /* in a base-64 section */
4618 if (IS_BASE64(ch)) { /* consume a base-64 character */
4619 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4620 base64bits += 6;
4621 s++;
4622 if (base64bits >= 16) {
4623 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004624 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004625 base64bits -= 16;
4626 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004627 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004628 if (surrogate) {
4629 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004630 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4631 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004632 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004633 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004634 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004635 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 }
4637 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004638 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004639 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004640 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 }
4642 }
Victor Stinner551ac952011-11-29 22:58:13 +01004643 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 /* first surrogate */
4645 surrogate = outCh;
4646 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004648 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004649 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004650 }
4651 }
4652 }
4653 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004654 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004655 if (base64bits > 0) { /* left-over bits */
4656 if (base64bits >= 6) {
4657 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004658 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004659 errmsg = "partial character in shift sequence";
4660 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004661 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004662 else {
4663 /* Some bits remain; they should be zero */
4664 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004665 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666 errmsg = "non-zero padding bits in shift sequence";
4667 goto utf7Error;
4668 }
4669 }
4670 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004671 if (surrogate && DECODE_DIRECT(ch)) {
4672 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4673 goto onError;
4674 }
4675 surrogate = 0;
4676 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004677 /* '-' is absorbed; other terminating
4678 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004679 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004680 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004681 }
4682 }
4683 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004684 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685 s++; /* consume '+' */
4686 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004687 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004688 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004689 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004690 }
4691 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004692 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004693 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004694 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004696 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004697 }
4698 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004699 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004700 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004701 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004702 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004703 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004704 else {
4705 startinpos = s-starts;
4706 s++;
4707 errmsg = "unexpected special character";
4708 goto utf7Error;
4709 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004710 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004711utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004712 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004713 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004714 errors, &errorHandler,
4715 "utf7", errmsg,
4716 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004717 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004718 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004719 }
4720
Antoine Pitrou244651a2009-05-04 18:56:13 +00004721 /* end of string */
4722
4723 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4724 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004725 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004726 if (surrogate ||
4727 (base64bits >= 6) ||
4728 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004729 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004730 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004731 errors, &errorHandler,
4732 "utf7", "unterminated shift sequence",
4733 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004734 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004735 goto onError;
4736 if (s < e)
4737 goto restart;
4738 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004739 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004740
4741 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004742 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004743 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004744 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004745 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004746 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004747 writer.kind, writer.data, shiftOutStart);
4748 Py_XDECREF(errorHandler);
4749 Py_XDECREF(exc);
4750 _PyUnicodeWriter_Dealloc(&writer);
4751 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004752 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004753 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004754 }
4755 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004756 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004757 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004758 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004759
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004760 Py_XDECREF(errorHandler);
4761 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004763
Benjamin Peterson29060642009-01-31 22:14:21 +00004764 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004765 Py_XDECREF(errorHandler);
4766 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004767 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 return NULL;
4769}
4770
4771
Alexander Belopolsky40018472011-02-26 01:02:56 +00004772PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004773_PyUnicode_EncodeUTF7(PyObject *str,
4774 int base64SetO,
4775 int base64WhiteSpace,
4776 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004777{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004778 int kind;
4779 void *data;
4780 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004781 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004782 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004783 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004784 unsigned int base64bits = 0;
4785 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004786 char * out;
4787 char * start;
4788
Benjamin Petersonbac79492012-01-14 13:34:47 -05004789 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004790 return NULL;
4791 kind = PyUnicode_KIND(str);
4792 data = PyUnicode_DATA(str);
4793 len = PyUnicode_GET_LENGTH(str);
4794
4795 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004796 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004797
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004798 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004799 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004800 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004801 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004802 if (v == NULL)
4803 return NULL;
4804
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004805 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004806 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004807 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004808
Antoine Pitrou244651a2009-05-04 18:56:13 +00004809 if (inShift) {
4810 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4811 /* shifting out */
4812 if (base64bits) { /* output remaining bits */
4813 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4814 base64buffer = 0;
4815 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004816 }
4817 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004818 /* Characters not in the BASE64 set implicitly unshift the sequence
4819 so no '-' is required, except if the character is itself a '-' */
4820 if (IS_BASE64(ch) || ch == '-') {
4821 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004822 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004823 *out++ = (char) ch;
4824 }
4825 else {
4826 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004827 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004828 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004829 else { /* not in a shift sequence */
4830 if (ch == '+') {
4831 *out++ = '+';
4832 *out++ = '-';
4833 }
4834 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4835 *out++ = (char) ch;
4836 }
4837 else {
4838 *out++ = '+';
4839 inShift = 1;
4840 goto encode_char;
4841 }
4842 }
4843 continue;
4844encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004845 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004846 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004847
Antoine Pitrou244651a2009-05-04 18:56:13 +00004848 /* code first surrogate */
4849 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004850 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004851 while (base64bits >= 6) {
4852 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4853 base64bits -= 6;
4854 }
4855 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004856 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004857 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004858 base64bits += 16;
4859 base64buffer = (base64buffer << 16) | ch;
4860 while (base64bits >= 6) {
4861 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4862 base64bits -= 6;
4863 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004864 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004865 if (base64bits)
4866 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4867 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004868 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004869 if (_PyBytes_Resize(&v, out - start) < 0)
4870 return NULL;
4871 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004872}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004873PyObject *
4874PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4875 Py_ssize_t size,
4876 int base64SetO,
4877 int base64WhiteSpace,
4878 const char *errors)
4879{
4880 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004881 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004882 if (tmp == NULL)
4883 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004884 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004885 base64WhiteSpace, errors);
4886 Py_DECREF(tmp);
4887 return result;
4888}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004889
Antoine Pitrou244651a2009-05-04 18:56:13 +00004890#undef IS_BASE64
4891#undef FROM_BASE64
4892#undef TO_BASE64
4893#undef DECODE_DIRECT
4894#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004895
Guido van Rossumd57fd912000-03-10 22:53:23 +00004896/* --- UTF-8 Codec -------------------------------------------------------- */
4897
Alexander Belopolsky40018472011-02-26 01:02:56 +00004898PyObject *
4899PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004900 Py_ssize_t size,
4901 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004902{
Walter Dörwald69652032004-09-07 20:24:22 +00004903 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4904}
4905
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004906#include "stringlib/asciilib.h"
4907#include "stringlib/codecs.h"
4908#include "stringlib/undef.h"
4909
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004910#include "stringlib/ucs1lib.h"
4911#include "stringlib/codecs.h"
4912#include "stringlib/undef.h"
4913
4914#include "stringlib/ucs2lib.h"
4915#include "stringlib/codecs.h"
4916#include "stringlib/undef.h"
4917
4918#include "stringlib/ucs4lib.h"
4919#include "stringlib/codecs.h"
4920#include "stringlib/undef.h"
4921
Antoine Pitrouab868312009-01-10 15:40:25 +00004922/* Mask to quickly check whether a C 'long' contains a
4923 non-ASCII, UTF8-encoded char. */
4924#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004925# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004926#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004927# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004928#else
4929# error C 'long' size should be either 4 or 8!
4930#endif
4931
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004932static Py_ssize_t
4933ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004934{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004935 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004936 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004937
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004938 /*
4939 * Issue #17237: m68k is a bit different from most architectures in
4940 * that objects do not use "natural alignment" - for example, int and
4941 * long are only aligned at 2-byte boundaries. Therefore the assert()
4942 * won't work; also, tests have shown that skipping the "optimised
4943 * version" will even speed up m68k.
4944 */
4945#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004947 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4948 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004949 /* Fast path, see in STRINGLIB(utf8_decode) for
4950 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004951 /* Help allocation */
4952 const char *_p = p;
4953 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004954 while (_p < aligned_end) {
4955 unsigned long value = *(const unsigned long *) _p;
4956 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004957 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004958 *((unsigned long *)q) = value;
4959 _p += SIZEOF_LONG;
4960 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004961 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 p = _p;
4963 while (p < end) {
4964 if ((unsigned char)*p & 0x80)
4965 break;
4966 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004967 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004968 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004969 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004971#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972 while (p < end) {
4973 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4974 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004975 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004976 /* Help allocation */
4977 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004978 while (_p < aligned_end) {
4979 unsigned long value = *(unsigned long *) _p;
4980 if (value & ASCII_CHAR_MASK)
4981 break;
4982 _p += SIZEOF_LONG;
4983 }
4984 p = _p;
4985 if (_p == end)
4986 break;
4987 }
4988 if ((unsigned char)*p & 0x80)
4989 break;
4990 ++p;
4991 }
4992 memcpy(dest, start, p - start);
4993 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004994}
Antoine Pitrouab868312009-01-10 15:40:25 +00004995
Victor Stinner785938e2011-12-11 20:09:03 +01004996PyObject *
4997PyUnicode_DecodeUTF8Stateful(const char *s,
4998 Py_ssize_t size,
4999 const char *errors,
5000 Py_ssize_t *consumed)
5001{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005002 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01005003 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005005
5006 Py_ssize_t startinpos;
5007 Py_ssize_t endinpos;
5008 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02005009 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005010 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02005011 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01005012
5013 if (size == 0) {
5014 if (consumed)
5015 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005016 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01005017 }
5018
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005019 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5020 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01005021 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005022 *consumed = 1;
5023 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01005024 }
5025
Victor Stinner8f674cc2013-04-17 23:02:17 +02005026 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005027 writer.min_length = size;
5028 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005029 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01005030
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005031 writer.pos = ascii_decode(s, end, writer.data);
5032 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005033 while (s < end) {
5034 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02005036
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005037 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005038 if (PyUnicode_IS_ASCII(writer.buffer))
5039 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005040 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005041 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005042 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005043 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005044 } else {
5045 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005046 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005047 }
5048
5049 switch (ch) {
5050 case 0:
5051 if (s == end || consumed)
5052 goto End;
5053 errmsg = "unexpected end of data";
5054 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005055 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005056 break;
5057 case 1:
5058 errmsg = "invalid start byte";
5059 startinpos = s - starts;
5060 endinpos = startinpos + 1;
5061 break;
5062 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005063 case 3:
5064 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065 errmsg = "invalid continuation byte";
5066 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005067 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005068 break;
5069 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005070 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005071 goto onError;
5072 continue;
5073 }
5074
Victor Stinner1d65d912015-10-05 13:43:50 +02005075 if (error_handler == _Py_ERROR_UNKNOWN)
5076 error_handler = get_error_handler(errors);
5077
5078 switch (error_handler) {
5079 case _Py_ERROR_IGNORE:
5080 s += (endinpos - startinpos);
5081 break;
5082
5083 case _Py_ERROR_REPLACE:
5084 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5085 goto onError;
5086 s += (endinpos - startinpos);
5087 break;
5088
5089 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005090 {
5091 Py_ssize_t i;
5092
Victor Stinner1d65d912015-10-05 13:43:50 +02005093 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5094 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005095 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005096 ch = (Py_UCS4)(unsigned char)(starts[i]);
5097 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5098 ch + 0xdc00);
5099 writer.pos++;
5100 }
5101 s += (endinpos - startinpos);
5102 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005103 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005104
5105 default:
5106 if (unicode_decode_call_errorhandler_writer(
5107 errors, &error_handler_obj,
5108 "utf-8", errmsg,
5109 &starts, &end, &startinpos, &endinpos, &exc, &s,
5110 &writer))
5111 goto onError;
5112 }
Victor Stinner785938e2011-12-11 20:09:03 +01005113 }
5114
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005115End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005116 if (consumed)
5117 *consumed = s - starts;
5118
Victor Stinner1d65d912015-10-05 13:43:50 +02005119 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005120 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005121 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005122
5123onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005124 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005125 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005126 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005127 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005128}
5129
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005130
Victor Stinner91106cd2017-12-13 12:29:09 +01005131/* UTF-8 decoder using the surrogateescape error handler .
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005132
Victor Stinner91106cd2017-12-13 12:29:09 +01005133 On success, return a pointer to a newly allocated wide character string (use
5134 PyMem_RawFree() to free the memory) and write the output length (in number
5135 of wchar_t units) into *p_wlen (if p_wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005136
Victor Stinner91106cd2017-12-13 12:29:09 +01005137 On memory allocation failure, return -1 and write (size_t)-1 into *p_wlen
5138 (if p_wlen is set). */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005139wchar_t*
Victor Stinner91106cd2017-12-13 12:29:09 +01005140_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size, size_t *p_wlen)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005141{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005142 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005143 wchar_t *unicode;
5144 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005145
5146 /* Note: size will always be longer than the resulting Unicode
5147 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01005148 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
5149 if (p_wlen) {
5150 *p_wlen = (size_t)-1;
5151 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005152 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005153 }
5154
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005155 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01005156 if (!unicode) {
5157 if (p_wlen) {
5158 *p_wlen = (size_t)-1;
5159 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005160 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005161 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005162
5163 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005164 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005165 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005166 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005167 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005168#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005169 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005170#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005171 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005172#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005173 if (ch > 0xFF) {
5174#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005175 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005176#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005177 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005178 /* compute and append the two surrogates: */
5179 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5180 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5181#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005182 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005183 else {
5184 if (!ch && s == e)
5185 break;
5186 /* surrogateescape */
5187 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5188 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005189 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005190 unicode[outpos] = L'\0';
Victor Stinner91106cd2017-12-13 12:29:09 +01005191 if (p_wlen) {
5192 *p_wlen = outpos;
5193 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005194 return unicode;
5195}
5196
Antoine Pitrouab868312009-01-10 15:40:25 +00005197
Victor Stinnere47e6982017-12-21 15:45:16 +01005198/* UTF-8 encoder using the surrogateescape error handler .
5199
5200 On success, return a pointer to a newly allocated character string (use
5201 PyMem_Free() to free the memory).
5202
5203 On encoding failure, return NULL and write the position of the invalid
5204 surrogate character into *error_pos (if error_pos is set).
5205
5206 On memory allocation failure, return NULL and write (size_t)-1 into
5207 *error_pos (if error_pos is set). */
5208char*
Victor Stinner9dd76202017-12-21 16:20:32 +01005209_Py_EncodeUTF8_surrogateescape(const wchar_t *text, size_t *error_pos,
5210 int raw_malloc)
Victor Stinnere47e6982017-12-21 15:45:16 +01005211{
5212 const Py_ssize_t max_char_size = 4;
5213 Py_ssize_t len = wcslen(text);
5214
5215 assert(len >= 0);
5216
5217 char *bytes;
5218 if (len <= PY_SSIZE_T_MAX / max_char_size - 1) {
Victor Stinner9dd76202017-12-21 16:20:32 +01005219 if (raw_malloc) {
5220 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5221 }
5222 else {
5223 bytes = PyMem_Malloc((len + 1) * max_char_size);
5224 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005225 }
5226 else {
5227 bytes = NULL;
5228 }
5229 if (bytes == NULL) {
5230 if (error_pos != NULL) {
5231 *error_pos = (size_t)-1;
5232 }
5233 return NULL;
5234 }
5235
5236 char *p = bytes;
5237 Py_ssize_t i;
5238 for (i = 0; i < len;) {
5239 Py_UCS4 ch = text[i++];
5240
5241 if (ch < 0x80) {
5242 /* Encode ASCII */
5243 *p++ = (char) ch;
5244
5245 }
5246 else if (ch < 0x0800) {
5247 /* Encode Latin-1 */
5248 *p++ = (char)(0xc0 | (ch >> 6));
5249 *p++ = (char)(0x80 | (ch & 0x3f));
5250 }
5251 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5252 /* surrogateescape error handler */
5253 if (!(0xDC80 <= ch && ch <= 0xDCFF)) {
5254 if (error_pos != NULL) {
5255 *error_pos = (size_t)i - 1;
5256 }
5257 goto error;
5258 }
5259 *p++ = (char)(ch & 0xff);
5260 }
5261 else if (ch < 0x10000) {
5262 *p++ = (char)(0xe0 | (ch >> 12));
5263 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5264 *p++ = (char)(0x80 | (ch & 0x3f));
5265 }
5266 else { /* ch >= 0x10000 */
5267 assert(ch <= MAX_UNICODE);
5268 /* Encode UCS4 Unicode ordinals */
5269 *p++ = (char)(0xf0 | (ch >> 18));
5270 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5271 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5272 *p++ = (char)(0x80 | (ch & 0x3f));
5273 }
5274 }
5275 *p++ = '\0';
5276
5277 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005278 char *bytes2;
5279 if (raw_malloc) {
5280 bytes2 = PyMem_RawRealloc(bytes, final_size);
5281 }
5282 else {
5283 bytes2 = PyMem_Realloc(bytes, final_size);
5284 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005285 if (bytes2 == NULL) {
5286 if (error_pos != NULL) {
5287 *error_pos = (size_t)-1;
5288 }
5289 goto error;
5290 }
5291 return bytes2;
5292
5293 error:
Victor Stinner9dd76202017-12-21 16:20:32 +01005294 if (raw_malloc) {
5295 PyMem_RawFree(bytes);
5296 }
5297 else {
5298 PyMem_Free(bytes);
5299 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005300 return NULL;
5301}
5302
5303
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005304/* Primary internal function which creates utf8 encoded bytes objects.
5305
5306 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005307 and allocate exactly as much space needed at the end. Else allocate the
5308 maximum possible needed (4 result bytes per Unicode character), and return
5309 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005310*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005311PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005312_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005313{
Victor Stinner6099a032011-12-18 14:22:26 +01005314 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005315 void *data;
5316 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005318 if (!PyUnicode_Check(unicode)) {
5319 PyErr_BadArgument();
5320 return NULL;
5321 }
5322
5323 if (PyUnicode_READY(unicode) == -1)
5324 return NULL;
5325
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005326 if (PyUnicode_UTF8(unicode))
5327 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5328 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005329
5330 kind = PyUnicode_KIND(unicode);
5331 data = PyUnicode_DATA(unicode);
5332 size = PyUnicode_GET_LENGTH(unicode);
5333
Benjamin Petersonead6b532011-12-20 17:23:42 -06005334 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005335 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005336 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005337 case PyUnicode_1BYTE_KIND:
5338 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5339 assert(!PyUnicode_IS_ASCII(unicode));
5340 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5341 case PyUnicode_2BYTE_KIND:
5342 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5343 case PyUnicode_4BYTE_KIND:
5344 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005345 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005346}
5347
Alexander Belopolsky40018472011-02-26 01:02:56 +00005348PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005349PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5350 Py_ssize_t size,
5351 const char *errors)
5352{
5353 PyObject *v, *unicode;
5354
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005355 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005356 if (unicode == NULL)
5357 return NULL;
5358 v = _PyUnicode_AsUTF8String(unicode, errors);
5359 Py_DECREF(unicode);
5360 return v;
5361}
5362
5363PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005364PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005366 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005367}
5368
Walter Dörwald41980ca2007-08-16 21:55:45 +00005369/* --- UTF-32 Codec ------------------------------------------------------- */
5370
5371PyObject *
5372PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 Py_ssize_t size,
5374 const char *errors,
5375 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005376{
5377 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5378}
5379
5380PyObject *
5381PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005382 Py_ssize_t size,
5383 const char *errors,
5384 int *byteorder,
5385 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005386{
5387 const char *starts = s;
5388 Py_ssize_t startinpos;
5389 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005390 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005391 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005392 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005393 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005394 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005395 PyObject *errorHandler = NULL;
5396 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005397
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398 q = (unsigned char *)s;
5399 e = q + size;
5400
5401 if (byteorder)
5402 bo = *byteorder;
5403
5404 /* Check for BOM marks (U+FEFF) in the input and adjust current
5405 byte order setting accordingly. In native mode, the leading BOM
5406 mark is skipped, in all other modes, it is copied to the output
5407 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005408 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005409 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005410 if (bom == 0x0000FEFF) {
5411 bo = -1;
5412 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005413 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005414 else if (bom == 0xFFFE0000) {
5415 bo = 1;
5416 q += 4;
5417 }
5418 if (byteorder)
5419 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005420 }
5421
Victor Stinnere64322e2012-10-30 23:12:47 +01005422 if (q == e) {
5423 if (consumed)
5424 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005425 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005426 }
5427
Victor Stinnere64322e2012-10-30 23:12:47 +01005428#ifdef WORDS_BIGENDIAN
5429 le = bo < 0;
5430#else
5431 le = bo <= 0;
5432#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005433 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005434
Victor Stinner8f674cc2013-04-17 23:02:17 +02005435 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005436 writer.min_length = (e - q + 3) / 4;
5437 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005438 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005439
Victor Stinnere64322e2012-10-30 23:12:47 +01005440 while (1) {
5441 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005442 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005443
Victor Stinnere64322e2012-10-30 23:12:47 +01005444 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005445 enum PyUnicode_Kind kind = writer.kind;
5446 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005447 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005448 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005449 if (le) {
5450 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005451 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005452 if (ch > maxch)
5453 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005454 if (kind != PyUnicode_1BYTE_KIND &&
5455 Py_UNICODE_IS_SURROGATE(ch))
5456 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005457 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005458 q += 4;
5459 } while (q <= last);
5460 }
5461 else {
5462 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005463 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005464 if (ch > maxch)
5465 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005466 if (kind != PyUnicode_1BYTE_KIND &&
5467 Py_UNICODE_IS_SURROGATE(ch))
5468 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005469 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005470 q += 4;
5471 } while (q <= last);
5472 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005473 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005474 }
5475
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005476 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005477 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 startinpos = ((const char *)q) - starts;
5479 endinpos = startinpos + 4;
5480 }
5481 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005482 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005484 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005485 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005486 startinpos = ((const char *)q) - starts;
5487 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005488 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005489 else {
5490 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005491 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005492 goto onError;
5493 q += 4;
5494 continue;
5495 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005496 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005497 startinpos = ((const char *)q) - starts;
5498 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005499 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005500
5501 /* The remaining input chars are ignored if the callback
5502 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005503 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005504 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005505 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005506 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005507 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005508 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005509 }
5510
Walter Dörwald41980ca2007-08-16 21:55:45 +00005511 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005513
Walter Dörwald41980ca2007-08-16 21:55:45 +00005514 Py_XDECREF(errorHandler);
5515 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005516 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005517
Benjamin Peterson29060642009-01-31 22:14:21 +00005518 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005519 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005520 Py_XDECREF(errorHandler);
5521 Py_XDECREF(exc);
5522 return NULL;
5523}
5524
5525PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005526_PyUnicode_EncodeUTF32(PyObject *str,
5527 const char *errors,
5528 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005529{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005530 enum PyUnicode_Kind kind;
5531 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005532 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005533 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005534 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005535#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005536 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005537#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005538 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005539#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005540 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005541 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005542 PyObject *errorHandler = NULL;
5543 PyObject *exc = NULL;
5544 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005545
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005546 if (!PyUnicode_Check(str)) {
5547 PyErr_BadArgument();
5548 return NULL;
5549 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005550 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005551 return NULL;
5552 kind = PyUnicode_KIND(str);
5553 data = PyUnicode_DATA(str);
5554 len = PyUnicode_GET_LENGTH(str);
5555
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005556 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005557 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005558 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005559 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005560 if (v == NULL)
5561 return NULL;
5562
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005563 /* output buffer is 4-bytes aligned */
5564 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005565 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005566 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005567 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005568 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005569 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005570
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005571 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005572 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005573 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005574 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005575 else
5576 encoding = "utf-32";
5577
5578 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005579 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5580 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005581 }
5582
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005583 pos = 0;
5584 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005585 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005586
5587 if (kind == PyUnicode_2BYTE_KIND) {
5588 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5589 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005590 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005591 else {
5592 assert(kind == PyUnicode_4BYTE_KIND);
5593 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5594 &out, native_ordering);
5595 }
5596 if (pos == len)
5597 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005598
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005599 rep = unicode_encode_call_errorhandler(
5600 errors, &errorHandler,
5601 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005602 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005603 if (!rep)
5604 goto error;
5605
5606 if (PyBytes_Check(rep)) {
5607 repsize = PyBytes_GET_SIZE(rep);
5608 if (repsize & 3) {
5609 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005610 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005611 "surrogates not allowed");
5612 goto error;
5613 }
5614 moreunits = repsize / 4;
5615 }
5616 else {
5617 assert(PyUnicode_Check(rep));
5618 if (PyUnicode_READY(rep) < 0)
5619 goto error;
5620 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5621 if (!PyUnicode_IS_ASCII(rep)) {
5622 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005623 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005624 "surrogates not allowed");
5625 goto error;
5626 }
5627 }
5628
5629 /* four bytes are reserved for each surrogate */
5630 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005631 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005632 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005633 /* integer overflow */
5634 PyErr_NoMemory();
5635 goto error;
5636 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005637 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005638 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005639 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005640 }
5641
5642 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005643 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005644 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005646 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005647 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5648 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005649 }
5650
5651 Py_CLEAR(rep);
5652 }
5653
5654 /* Cut back to size actually needed. This is necessary for, for example,
5655 encoding of a string containing isolated surrogates and the 'ignore'
5656 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005657 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005658 if (nsize != PyBytes_GET_SIZE(v))
5659 _PyBytes_Resize(&v, nsize);
5660 Py_XDECREF(errorHandler);
5661 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005662 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005663 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005664 error:
5665 Py_XDECREF(rep);
5666 Py_XDECREF(errorHandler);
5667 Py_XDECREF(exc);
5668 Py_XDECREF(v);
5669 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005670}
5671
Alexander Belopolsky40018472011-02-26 01:02:56 +00005672PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005673PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5674 Py_ssize_t size,
5675 const char *errors,
5676 int byteorder)
5677{
5678 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005679 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005680 if (tmp == NULL)
5681 return NULL;
5682 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5683 Py_DECREF(tmp);
5684 return result;
5685}
5686
5687PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005688PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005689{
Victor Stinnerb960b342011-11-20 19:12:52 +01005690 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005691}
5692
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693/* --- UTF-16 Codec ------------------------------------------------------- */
5694
Tim Peters772747b2001-08-09 22:21:55 +00005695PyObject *
5696PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005697 Py_ssize_t size,
5698 const char *errors,
5699 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700{
Walter Dörwald69652032004-09-07 20:24:22 +00005701 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5702}
5703
5704PyObject *
5705PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005706 Py_ssize_t size,
5707 const char *errors,
5708 int *byteorder,
5709 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005710{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005711 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005712 Py_ssize_t startinpos;
5713 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005714 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005715 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005716 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005717 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005718 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005719 PyObject *errorHandler = NULL;
5720 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005721 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722
Tim Peters772747b2001-08-09 22:21:55 +00005723 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005724 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725
5726 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005727 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005729 /* Check for BOM marks (U+FEFF) in the input and adjust current
5730 byte order setting accordingly. In native mode, the leading BOM
5731 mark is skipped, in all other modes, it is copied to the output
5732 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005733 if (bo == 0 && size >= 2) {
5734 const Py_UCS4 bom = (q[1] << 8) | q[0];
5735 if (bom == 0xFEFF) {
5736 q += 2;
5737 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005738 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005739 else if (bom == 0xFFFE) {
5740 q += 2;
5741 bo = 1;
5742 }
5743 if (byteorder)
5744 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005745 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746
Antoine Pitrou63065d72012-05-15 23:48:04 +02005747 if (q == e) {
5748 if (consumed)
5749 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005750 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005751 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005752
Christian Heimes743e0cd2012-10-17 23:52:17 +02005753#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005754 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005755 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005756#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005757 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005758 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005759#endif
Tim Peters772747b2001-08-09 22:21:55 +00005760
Antoine Pitrou63065d72012-05-15 23:48:04 +02005761 /* Note: size will always be longer than the resulting Unicode
5762 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005763 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005764 writer.min_length = (e - q + 1) / 2;
5765 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005766 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005767
Antoine Pitrou63065d72012-05-15 23:48:04 +02005768 while (1) {
5769 Py_UCS4 ch = 0;
5770 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005771 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005772 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005773 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005774 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005775 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005776 native_ordering);
5777 else
5778 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005779 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005780 native_ordering);
5781 } else if (kind == PyUnicode_2BYTE_KIND) {
5782 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005783 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005784 native_ordering);
5785 } else {
5786 assert(kind == PyUnicode_4BYTE_KIND);
5787 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005788 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005789 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005790 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005791 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005792
Antoine Pitrou63065d72012-05-15 23:48:04 +02005793 switch (ch)
5794 {
5795 case 0:
5796 /* remaining byte at the end? (size should be even) */
5797 if (q == e || consumed)
5798 goto End;
5799 errmsg = "truncated data";
5800 startinpos = ((const char *)q) - starts;
5801 endinpos = ((const char *)e) - starts;
5802 break;
5803 /* The remaining input chars are ignored if the callback
5804 chooses to skip the input */
5805 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005806 q -= 2;
5807 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005808 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005809 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005810 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005811 endinpos = ((const char *)e) - starts;
5812 break;
5813 case 2:
5814 errmsg = "illegal encoding";
5815 startinpos = ((const char *)q) - 2 - starts;
5816 endinpos = startinpos + 2;
5817 break;
5818 case 3:
5819 errmsg = "illegal UTF-16 surrogate";
5820 startinpos = ((const char *)q) - 4 - starts;
5821 endinpos = startinpos + 2;
5822 break;
5823 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005824 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005825 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005826 continue;
5827 }
5828
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005829 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005830 errors,
5831 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005832 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005833 &starts,
5834 (const char **)&e,
5835 &startinpos,
5836 &endinpos,
5837 &exc,
5838 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005839 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005840 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005841 }
5842
Antoine Pitrou63065d72012-05-15 23:48:04 +02005843End:
Walter Dörwald69652032004-09-07 20:24:22 +00005844 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005846
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005847 Py_XDECREF(errorHandler);
5848 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005849 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005850
Benjamin Peterson29060642009-01-31 22:14:21 +00005851 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005852 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853 Py_XDECREF(errorHandler);
5854 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855 return NULL;
5856}
5857
Tim Peters772747b2001-08-09 22:21:55 +00005858PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005859_PyUnicode_EncodeUTF16(PyObject *str,
5860 const char *errors,
5861 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005863 enum PyUnicode_Kind kind;
5864 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005865 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005866 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005867 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005868 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005869#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005870 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005871#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005872 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005873#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005874 const char *encoding;
5875 Py_ssize_t nsize, pos;
5876 PyObject *errorHandler = NULL;
5877 PyObject *exc = NULL;
5878 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005879
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005880 if (!PyUnicode_Check(str)) {
5881 PyErr_BadArgument();
5882 return NULL;
5883 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005884 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005885 return NULL;
5886 kind = PyUnicode_KIND(str);
5887 data = PyUnicode_DATA(str);
5888 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005889
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005890 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005891 if (kind == PyUnicode_4BYTE_KIND) {
5892 const Py_UCS4 *in = (const Py_UCS4 *)data;
5893 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005894 while (in < end) {
5895 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005896 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005897 }
5898 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005899 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005900 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005902 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005903 nsize = len + pairs + (byteorder == 0);
5904 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005905 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005907 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005909 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005910 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005911 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005912 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005913 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005914 }
5915 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005916 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005917 }
Tim Peters772747b2001-08-09 22:21:55 +00005918
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005919 if (kind == PyUnicode_1BYTE_KIND) {
5920 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5921 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005922 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005923
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005924 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005925 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005926 }
5927 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005928 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005929 }
5930 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005931 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005932 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005933
5934 pos = 0;
5935 while (pos < len) {
5936 Py_ssize_t repsize, moreunits;
5937
5938 if (kind == PyUnicode_2BYTE_KIND) {
5939 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5940 &out, native_ordering);
5941 }
5942 else {
5943 assert(kind == PyUnicode_4BYTE_KIND);
5944 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5945 &out, native_ordering);
5946 }
5947 if (pos == len)
5948 break;
5949
5950 rep = unicode_encode_call_errorhandler(
5951 errors, &errorHandler,
5952 encoding, "surrogates not allowed",
5953 str, &exc, pos, pos + 1, &pos);
5954 if (!rep)
5955 goto error;
5956
5957 if (PyBytes_Check(rep)) {
5958 repsize = PyBytes_GET_SIZE(rep);
5959 if (repsize & 1) {
5960 raise_encode_exception(&exc, encoding,
5961 str, pos - 1, pos,
5962 "surrogates not allowed");
5963 goto error;
5964 }
5965 moreunits = repsize / 2;
5966 }
5967 else {
5968 assert(PyUnicode_Check(rep));
5969 if (PyUnicode_READY(rep) < 0)
5970 goto error;
5971 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5972 if (!PyUnicode_IS_ASCII(rep)) {
5973 raise_encode_exception(&exc, encoding,
5974 str, pos - 1, pos,
5975 "surrogates not allowed");
5976 goto error;
5977 }
5978 }
5979
5980 /* two bytes are reserved for each surrogate */
5981 if (moreunits > 1) {
5982 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005983 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005984 /* integer overflow */
5985 PyErr_NoMemory();
5986 goto error;
5987 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005988 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005989 goto error;
5990 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5991 }
5992
5993 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005994 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005995 out += moreunits;
5996 } else /* rep is unicode */ {
5997 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5998 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5999 &out, native_ordering);
6000 }
6001
6002 Py_CLEAR(rep);
6003 }
6004
6005 /* Cut back to size actually needed. This is necessary for, for example,
6006 encoding of a string containing isolated surrogates and the 'ignore' handler
6007 is used. */
6008 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
6009 if (nsize != PyBytes_GET_SIZE(v))
6010 _PyBytes_Resize(&v, nsize);
6011 Py_XDECREF(errorHandler);
6012 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00006013 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006014 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006015 error:
6016 Py_XDECREF(rep);
6017 Py_XDECREF(errorHandler);
6018 Py_XDECREF(exc);
6019 Py_XDECREF(v);
6020 return NULL;
6021#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022}
6023
Alexander Belopolsky40018472011-02-26 01:02:56 +00006024PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006025PyUnicode_EncodeUTF16(const Py_UNICODE *s,
6026 Py_ssize_t size,
6027 const char *errors,
6028 int byteorder)
6029{
6030 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006031 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006032 if (tmp == NULL)
6033 return NULL;
6034 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
6035 Py_DECREF(tmp);
6036 return result;
6037}
6038
6039PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006040PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043}
6044
6045/* --- Unicode Escape Codec ----------------------------------------------- */
6046
Fredrik Lundh06d12682001-01-24 07:59:11 +00006047static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00006048
Alexander Belopolsky40018472011-02-26 01:02:56 +00006049PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04006050_PyUnicode_DecodeUnicodeEscape(const char *s,
6051 Py_ssize_t size,
6052 const char *errors,
6053 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006055 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006056 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006058 PyObject *errorHandler = NULL;
6059 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006060
Eric V. Smith42454af2016-10-31 09:22:08 -04006061 // so we can remember if we've seen an invalid escape char or not
6062 *first_invalid_escape = NULL;
6063
Victor Stinner62ec3312016-09-06 17:04:34 -07006064 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006065 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006066 }
6067 /* Escaped strings will always be longer than the resulting
6068 Unicode string, so we start with size here and then reduce the
6069 length after conversion to the true value.
6070 (but if the error callback returns a long replacement string
6071 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006072 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 writer.min_length = size;
6074 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6075 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006076 }
6077
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078 end = s + size;
6079 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006080 unsigned char c = (unsigned char) *s++;
6081 Py_UCS4 ch;
6082 int count;
6083 Py_ssize_t startinpos;
6084 Py_ssize_t endinpos;
6085 const char *message;
6086
6087#define WRITE_ASCII_CHAR(ch) \
6088 do { \
6089 assert(ch <= 127); \
6090 assert(writer.pos < writer.size); \
6091 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6092 } while(0)
6093
6094#define WRITE_CHAR(ch) \
6095 do { \
6096 if (ch <= writer.maxchar) { \
6097 assert(writer.pos < writer.size); \
6098 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6099 } \
6100 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6101 goto onError; \
6102 } \
6103 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006104
6105 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006106 if (c != '\\') {
6107 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006108 continue;
6109 }
6110
Victor Stinner62ec3312016-09-06 17:04:34 -07006111 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006113 if (s >= end) {
6114 message = "\\ at end of string";
6115 goto error;
6116 }
6117 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006118
Victor Stinner62ec3312016-09-06 17:04:34 -07006119 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006120 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006123 case '\n': continue;
6124 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6125 case '\'': WRITE_ASCII_CHAR('\''); continue;
6126 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6127 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006128 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006129 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6130 case 't': WRITE_ASCII_CHAR('\t'); continue;
6131 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6132 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006133 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006134 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006135 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006136 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137
Benjamin Peterson29060642009-01-31 22:14:21 +00006138 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 case '0': case '1': case '2': case '3':
6140 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006141 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006142 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006143 ch = (ch<<3) + *s++ - '0';
6144 if (s < end && '0' <= *s && *s <= '7') {
6145 ch = (ch<<3) + *s++ - '0';
6146 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006148 WRITE_CHAR(ch);
6149 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 /* hex escapes */
6152 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006154 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006155 message = "truncated \\xXX escape";
6156 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006160 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006161 message = "truncated \\uXXXX escape";
6162 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163
Benjamin Peterson29060642009-01-31 22:14:21 +00006164 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006165 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006166 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006167 message = "truncated \\UXXXXXXXX escape";
6168 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006169 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006170 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006171 ch <<= 4;
6172 if (c >= '0' && c <= '9') {
6173 ch += c - '0';
6174 }
6175 else if (c >= 'a' && c <= 'f') {
6176 ch += c - ('a' - 10);
6177 }
6178 else if (c >= 'A' && c <= 'F') {
6179 ch += c - ('A' - 10);
6180 }
6181 else {
6182 break;
6183 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006184 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006185 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006186 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006187 }
6188
6189 /* when we get here, ch is a 32-bit unicode character */
6190 if (ch > MAX_UNICODE) {
6191 message = "illegal Unicode character";
6192 goto error;
6193 }
6194
6195 WRITE_CHAR(ch);
6196 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006197
Benjamin Peterson29060642009-01-31 22:14:21 +00006198 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006199 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006200 if (ucnhash_CAPI == NULL) {
6201 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006202 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6203 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006204 if (ucnhash_CAPI == NULL) {
6205 PyErr_SetString(
6206 PyExc_UnicodeError,
6207 "\\N escapes not supported (can't load unicodedata module)"
6208 );
6209 goto onError;
6210 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006211 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006212
6213 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006214 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006215 const char *start = ++s;
6216 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006217 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006218 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006219 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006220 namelen = s - start;
6221 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006222 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006223 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006224 ch = 0xffffffff; /* in case 'getcode' messes up */
6225 if (namelen <= INT_MAX &&
6226 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6227 &ch, 0)) {
6228 assert(ch <= MAX_UNICODE);
6229 WRITE_CHAR(ch);
6230 continue;
6231 }
6232 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006233 }
6234 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006235 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006236
6237 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006238 if (*first_invalid_escape == NULL) {
6239 *first_invalid_escape = s-1; /* Back up one char, since we've
6240 already incremented s. */
6241 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006242 WRITE_ASCII_CHAR('\\');
6243 WRITE_CHAR(c);
6244 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006246
6247 error:
6248 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006250 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006251 errors, &errorHandler,
6252 "unicodeescape", message,
6253 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006254 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006255 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006256 }
6257 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6258 goto onError;
6259 }
6260
6261#undef WRITE_ASCII_CHAR
6262#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006264
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006265 Py_XDECREF(errorHandler);
6266 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006267 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006268
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006270 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006271 Py_XDECREF(errorHandler);
6272 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273 return NULL;
6274}
6275
Eric V. Smith42454af2016-10-31 09:22:08 -04006276PyObject *
6277PyUnicode_DecodeUnicodeEscape(const char *s,
6278 Py_ssize_t size,
6279 const char *errors)
6280{
6281 const char *first_invalid_escape;
6282 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6283 &first_invalid_escape);
6284 if (result == NULL)
6285 return NULL;
6286 if (first_invalid_escape != NULL) {
6287 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6288 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006289 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006290 Py_DECREF(result);
6291 return NULL;
6292 }
6293 }
6294 return result;
6295}
6296
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006297/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006298
Alexander Belopolsky40018472011-02-26 01:02:56 +00006299PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006300PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006302 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006303 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006305 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006306 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308
Ezio Melottie7f90372012-10-05 03:33:31 +03006309 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006310 escape.
6311
Ezio Melottie7f90372012-10-05 03:33:31 +03006312 For UCS1 strings it's '\xxx', 4 bytes per source character.
6313 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6314 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006315 */
6316
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006317 if (!PyUnicode_Check(unicode)) {
6318 PyErr_BadArgument();
6319 return NULL;
6320 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006321 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006322 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006323 }
Victor Stinner358af132015-10-12 22:36:57 +02006324
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006325 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 if (len == 0) {
6327 return PyBytes_FromStringAndSize(NULL, 0);
6328 }
6329
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006330 kind = PyUnicode_KIND(unicode);
6331 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006332 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6333 bytes, and 1 byte characters 4. */
6334 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006335 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 return PyErr_NoMemory();
6337 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006338 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006339 if (repr == NULL) {
6340 return NULL;
6341 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006342
Victor Stinner62ec3312016-09-06 17:04:34 -07006343 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006344 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006345 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006346
Victor Stinner62ec3312016-09-06 17:04:34 -07006347 /* U+0000-U+00ff range */
6348 if (ch < 0x100) {
6349 if (ch >= ' ' && ch < 127) {
6350 if (ch != '\\') {
6351 /* Copy printable US ASCII as-is */
6352 *p++ = (char) ch;
6353 }
6354 /* Escape backslashes */
6355 else {
6356 *p++ = '\\';
6357 *p++ = '\\';
6358 }
6359 }
Victor Stinner358af132015-10-12 22:36:57 +02006360
Victor Stinner62ec3312016-09-06 17:04:34 -07006361 /* Map special whitespace to '\t', \n', '\r' */
6362 else if (ch == '\t') {
6363 *p++ = '\\';
6364 *p++ = 't';
6365 }
6366 else if (ch == '\n') {
6367 *p++ = '\\';
6368 *p++ = 'n';
6369 }
6370 else if (ch == '\r') {
6371 *p++ = '\\';
6372 *p++ = 'r';
6373 }
6374
6375 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6376 else {
6377 *p++ = '\\';
6378 *p++ = 'x';
6379 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6380 *p++ = Py_hexdigits[ch & 0x000F];
6381 }
Tim Petersced69f82003-09-16 20:30:58 +00006382 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006383 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006385 *p++ = '\\';
6386 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006387 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6388 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6389 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6390 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006392 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6393 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006394
Victor Stinner62ec3312016-09-06 17:04:34 -07006395 /* Make sure that the first two digits are zero */
6396 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006397 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006398 *p++ = 'U';
6399 *p++ = '0';
6400 *p++ = '0';
6401 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6402 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6403 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6404 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6405 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6406 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006407 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409
Victor Stinner62ec3312016-09-06 17:04:34 -07006410 assert(p - PyBytes_AS_STRING(repr) > 0);
6411 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6412 return NULL;
6413 }
6414 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006415}
6416
Alexander Belopolsky40018472011-02-26 01:02:56 +00006417PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006418PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6419 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006420{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006421 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006422 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006423 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 }
6426
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006427 result = PyUnicode_AsUnicodeEscapeString(tmp);
6428 Py_DECREF(tmp);
6429 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006430}
6431
6432/* --- Raw Unicode Escape Codec ------------------------------------------- */
6433
Alexander Belopolsky40018472011-02-26 01:02:56 +00006434PyObject *
6435PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006436 Py_ssize_t size,
6437 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006439 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006440 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006441 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 PyObject *errorHandler = NULL;
6443 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006444
Victor Stinner62ec3312016-09-06 17:04:34 -07006445 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006446 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006447 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006448
Guido van Rossumd57fd912000-03-10 22:53:23 +00006449 /* Escaped strings will always be longer than the resulting
6450 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006451 length after conversion to the true value. (But decoding error
6452 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006453 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006454 writer.min_length = size;
6455 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6456 goto onError;
6457 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006458
Guido van Rossumd57fd912000-03-10 22:53:23 +00006459 end = s + size;
6460 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006461 unsigned char c = (unsigned char) *s++;
6462 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006463 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006464 Py_ssize_t startinpos;
6465 Py_ssize_t endinpos;
6466 const char *message;
6467
6468#define WRITE_CHAR(ch) \
6469 do { \
6470 if (ch <= writer.maxchar) { \
6471 assert(writer.pos < writer.size); \
6472 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6473 } \
6474 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6475 goto onError; \
6476 } \
6477 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006480 if (c != '\\' || s >= end) {
6481 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006483 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006484
Victor Stinner62ec3312016-09-06 17:04:34 -07006485 c = (unsigned char) *s++;
6486 if (c == 'u') {
6487 count = 4;
6488 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006489 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006490 else if (c == 'U') {
6491 count = 8;
6492 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006493 }
6494 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006495 assert(writer.pos < writer.size);
6496 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6497 WRITE_CHAR(c);
6498 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006499 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006500 startinpos = s - starts - 2;
6501
6502 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6503 for (ch = 0; count && s < end; ++s, --count) {
6504 c = (unsigned char)*s;
6505 ch <<= 4;
6506 if (c >= '0' && c <= '9') {
6507 ch += c - '0';
6508 }
6509 else if (c >= 'a' && c <= 'f') {
6510 ch += c - ('a' - 10);
6511 }
6512 else if (c >= 'A' && c <= 'F') {
6513 ch += c - ('A' - 10);
6514 }
6515 else {
6516 break;
6517 }
6518 }
6519 if (!count) {
6520 if (ch <= MAX_UNICODE) {
6521 WRITE_CHAR(ch);
6522 continue;
6523 }
6524 message = "\\Uxxxxxxxx out of range";
6525 }
6526
6527 endinpos = s-starts;
6528 writer.min_length = end - s + writer.pos;
6529 if (unicode_decode_call_errorhandler_writer(
6530 errors, &errorHandler,
6531 "rawunicodeescape", message,
6532 &starts, &end, &startinpos, &endinpos, &exc, &s,
6533 &writer)) {
6534 goto onError;
6535 }
6536 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6537 goto onError;
6538 }
6539
6540#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006541 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542 Py_XDECREF(errorHandler);
6543 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006544 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006545
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006547 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006548 Py_XDECREF(errorHandler);
6549 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006550 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006551
Guido van Rossumd57fd912000-03-10 22:53:23 +00006552}
6553
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006554
Alexander Belopolsky40018472011-02-26 01:02:56 +00006555PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006556PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006557{
Victor Stinner62ec3312016-09-06 17:04:34 -07006558 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006559 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006560 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006561 int kind;
6562 void *data;
6563 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006564
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006565 if (!PyUnicode_Check(unicode)) {
6566 PyErr_BadArgument();
6567 return NULL;
6568 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006569 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006570 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006571 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006572 kind = PyUnicode_KIND(unicode);
6573 data = PyUnicode_DATA(unicode);
6574 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006575 if (kind == PyUnicode_1BYTE_KIND) {
6576 return PyBytes_FromStringAndSize(data, len);
6577 }
Victor Stinner0e368262011-11-10 20:12:49 +01006578
Victor Stinner62ec3312016-09-06 17:04:34 -07006579 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6580 bytes, and 1 byte characters 4. */
6581 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006582
Victor Stinner62ec3312016-09-06 17:04:34 -07006583 if (len > PY_SSIZE_T_MAX / expandsize) {
6584 return PyErr_NoMemory();
6585 }
6586 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6587 if (repr == NULL) {
6588 return NULL;
6589 }
6590 if (len == 0) {
6591 return repr;
6592 }
6593
6594 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006595 for (pos = 0; pos < len; pos++) {
6596 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006597
Victor Stinner62ec3312016-09-06 17:04:34 -07006598 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6599 if (ch < 0x100) {
6600 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006601 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006602 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6603 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604 *p++ = '\\';
6605 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006606 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6607 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6608 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6609 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006610 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006611 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6612 else {
6613 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6614 *p++ = '\\';
6615 *p++ = 'U';
6616 *p++ = '0';
6617 *p++ = '0';
6618 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6619 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6620 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6621 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6622 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6623 *p++ = Py_hexdigits[ch & 15];
6624 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006626
Victor Stinner62ec3312016-09-06 17:04:34 -07006627 assert(p > PyBytes_AS_STRING(repr));
6628 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6629 return NULL;
6630 }
6631 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632}
6633
Alexander Belopolsky40018472011-02-26 01:02:56 +00006634PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006635PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6636 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006637{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006638 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006639 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006640 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006641 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006642 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6643 Py_DECREF(tmp);
6644 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645}
6646
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006647/* --- Unicode Internal Codec ------------------------------------------- */
6648
Alexander Belopolsky40018472011-02-26 01:02:56 +00006649PyObject *
6650_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006651 Py_ssize_t size,
6652 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006653{
6654 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006655 Py_ssize_t startinpos;
6656 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006657 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006658 const char *end;
6659 const char *reason;
6660 PyObject *errorHandler = NULL;
6661 PyObject *exc = NULL;
6662
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006663 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006664 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006665 1))
6666 return NULL;
6667
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006668 if (size < 0) {
6669 PyErr_BadInternalCall();
6670 return NULL;
6671 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006672 if (size == 0)
6673 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006674
Victor Stinner8f674cc2013-04-17 23:02:17 +02006675 _PyUnicodeWriter_Init(&writer);
6676 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6677 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006679 }
6680 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006681
Victor Stinner8f674cc2013-04-17 23:02:17 +02006682 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006683 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006684 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006685 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006686 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006687 endinpos = end-starts;
6688 reason = "truncated input";
6689 goto error;
6690 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006691 /* We copy the raw representation one byte at a time because the
6692 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006693 ((char *) &uch)[0] = s[0];
6694 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006695#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006696 ((char *) &uch)[2] = s[2];
6697 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006698#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006699 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006700#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006701 /* We have to sanity check the raw data, otherwise doom looms for
6702 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006703 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006704 endinpos = s - starts + Py_UNICODE_SIZE;
6705 reason = "illegal code point (> 0x10FFFF)";
6706 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006707 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006708#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006709 s += Py_UNICODE_SIZE;
6710#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006711 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006712 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006713 Py_UNICODE uch2;
6714 ((char *) &uch2)[0] = s[0];
6715 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006716 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006717 {
Victor Stinner551ac952011-11-29 22:58:13 +01006718 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006719 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006720 }
6721 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006722#endif
6723
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006724 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006725 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006726 continue;
6727
6728 error:
6729 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006730 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006731 errors, &errorHandler,
6732 "unicode_internal", reason,
6733 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006734 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006735 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006736 }
6737
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006738 Py_XDECREF(errorHandler);
6739 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006740 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006741
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006743 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006744 Py_XDECREF(errorHandler);
6745 Py_XDECREF(exc);
6746 return NULL;
6747}
6748
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749/* --- Latin-1 Codec ------------------------------------------------------ */
6750
Alexander Belopolsky40018472011-02-26 01:02:56 +00006751PyObject *
6752PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006753 Py_ssize_t size,
6754 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006755{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006756 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006757 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006758}
6759
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006760/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006761static void
6762make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006763 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006764 PyObject *unicode,
6765 Py_ssize_t startpos, Py_ssize_t endpos,
6766 const char *reason)
6767{
6768 if (*exceptionObject == NULL) {
6769 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006770 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006771 encoding, unicode, startpos, endpos, reason);
6772 }
6773 else {
6774 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6775 goto onError;
6776 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6777 goto onError;
6778 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6779 goto onError;
6780 return;
6781 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006782 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006783 }
6784}
6785
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006786/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006787static void
6788raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006789 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006790 PyObject *unicode,
6791 Py_ssize_t startpos, Py_ssize_t endpos,
6792 const char *reason)
6793{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006794 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006795 encoding, unicode, startpos, endpos, reason);
6796 if (*exceptionObject != NULL)
6797 PyCodec_StrictErrors(*exceptionObject);
6798}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006799
6800/* error handling callback helper:
6801 build arguments, call the callback and check the arguments,
6802 put the result into newpos and return the replacement string, which
6803 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006804static PyObject *
6805unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006806 PyObject **errorHandler,
6807 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006808 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006809 Py_ssize_t startpos, Py_ssize_t endpos,
6810 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006811{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006812 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006813 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006814 PyObject *restuple;
6815 PyObject *resunicode;
6816
6817 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006818 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006819 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006821 }
6822
Benjamin Petersonbac79492012-01-14 13:34:47 -05006823 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006824 return NULL;
6825 len = PyUnicode_GET_LENGTH(unicode);
6826
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006827 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006828 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006829 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006830 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006831
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006832 restuple = PyObject_CallFunctionObjArgs(
6833 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006834 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006835 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006836 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006837 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006838 Py_DECREF(restuple);
6839 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006840 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006841 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 &resunicode, newpos)) {
6843 Py_DECREF(restuple);
6844 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006846 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6847 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6848 Py_DECREF(restuple);
6849 return NULL;
6850 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006851 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006852 *newpos = len + *newpos;
6853 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006854 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006855 Py_DECREF(restuple);
6856 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006857 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006858 Py_INCREF(resunicode);
6859 Py_DECREF(restuple);
6860 return resunicode;
6861}
6862
Alexander Belopolsky40018472011-02-26 01:02:56 +00006863static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006864unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006865 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006866 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006867{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006868 /* input state */
6869 Py_ssize_t pos=0, size;
6870 int kind;
6871 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006872 /* pointer into the output */
6873 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006874 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6875 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006876 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006877 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006878 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006879 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006880 /* output object */
6881 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882
Benjamin Petersonbac79492012-01-14 13:34:47 -05006883 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006884 return NULL;
6885 size = PyUnicode_GET_LENGTH(unicode);
6886 kind = PyUnicode_KIND(unicode);
6887 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006888 /* allocate enough for a simple encoding without
6889 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006890 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006891 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006892
6893 _PyBytesWriter_Init(&writer);
6894 str = _PyBytesWriter_Alloc(&writer, size);
6895 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006896 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006897
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006898 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006899 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006900
Benjamin Peterson29060642009-01-31 22:14:21 +00006901 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006902 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006903 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006904 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006905 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006906 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006907 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006908 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006909 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006910 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006911 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006912 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006913
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006914 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006915 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006916
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006917 /* Only overallocate the buffer if it's not the last write */
6918 writer.overallocate = (collend < size);
6919
Benjamin Peterson29060642009-01-31 22:14:21 +00006920 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006921 if (error_handler == _Py_ERROR_UNKNOWN)
6922 error_handler = get_error_handler(errors);
6923
6924 switch (error_handler) {
6925 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006926 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006928
6929 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006930 memset(str, '?', collend - collstart);
6931 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006932 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006933 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006934 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 break;
Victor Stinner50149202015-09-22 00:26:54 +02006936
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006937 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006938 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006939 writer.min_size -= (collend - collstart);
6940 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006941 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006942 if (str == NULL)
6943 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006944 pos = collend;
6945 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006946
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006947 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006948 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006949 writer.min_size -= (collend - collstart);
6950 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006951 unicode, collstart, collend);
6952 if (str == NULL)
6953 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006954 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006955 break;
Victor Stinner50149202015-09-22 00:26:54 +02006956
Victor Stinnerc3713e92015-09-29 12:32:13 +02006957 case _Py_ERROR_SURROGATEESCAPE:
6958 for (i = collstart; i < collend; ++i) {
6959 ch = PyUnicode_READ(kind, data, i);
6960 if (ch < 0xdc80 || 0xdcff < ch) {
6961 /* Not a UTF-8b surrogate */
6962 break;
6963 }
6964 *str++ = (char)(ch - 0xdc00);
6965 ++pos;
6966 }
6967 if (i >= collend)
6968 break;
6969 collstart = pos;
6970 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006971 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006972
Benjamin Peterson29060642009-01-31 22:14:21 +00006973 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006974 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6975 encoding, reason, unicode, &exc,
6976 collstart, collend, &newpos);
6977 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006979
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006980 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006981 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006982
Victor Stinner6bd525b2015-10-09 13:10:05 +02006983 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006984 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006985 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006986 PyBytes_AS_STRING(rep),
6987 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006988 if (str == NULL)
6989 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006990 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006991 else {
6992 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006993
Victor Stinner6bd525b2015-10-09 13:10:05 +02006994 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006995 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006996
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006997 if (limit == 256 ?
6998 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6999 !PyUnicode_IS_ASCII(rep))
7000 {
7001 /* Not all characters are smaller than limit */
7002 raise_encode_exception(&exc, encoding, unicode,
7003 collstart, collend, reason);
7004 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007005 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02007006 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
7007 str = _PyBytesWriter_WriteBytes(&writer, str,
7008 PyUnicode_DATA(rep),
7009 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00007010 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007011 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02007012 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007013 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007014
7015 /* If overallocation was disabled, ensure that it was the last
7016 write. Otherwise, we missed an optimization */
7017 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007018 }
7019 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007020
Victor Stinner50149202015-09-22 00:26:54 +02007021 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007022 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007023 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007024
7025 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02007026 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007027 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02007028 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007029 Py_XDECREF(exc);
7030 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007031}
7032
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007033/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007034PyObject *
7035PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03007036 Py_ssize_t size,
7037 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007038{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007039 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007040 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007041 if (unicode == NULL)
7042 return NULL;
7043 result = unicode_encode_ucs1(unicode, errors, 256);
7044 Py_DECREF(unicode);
7045 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007046}
7047
Alexander Belopolsky40018472011-02-26 01:02:56 +00007048PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007049_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007050{
7051 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007052 PyErr_BadArgument();
7053 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007055 if (PyUnicode_READY(unicode) == -1)
7056 return NULL;
7057 /* Fast path: if it is a one-byte string, construct
7058 bytes object directly. */
7059 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7060 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7061 PyUnicode_GET_LENGTH(unicode));
7062 /* Non-Latin-1 characters present. Defer to above function to
7063 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007064 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007065}
7066
7067PyObject*
7068PyUnicode_AsLatin1String(PyObject *unicode)
7069{
7070 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007071}
7072
7073/* --- 7-bit ASCII Codec -------------------------------------------------- */
7074
Alexander Belopolsky40018472011-02-26 01:02:56 +00007075PyObject *
7076PyUnicode_DecodeASCII(const char *s,
7077 Py_ssize_t size,
7078 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007079{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007080 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007081 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007082 int kind;
7083 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007084 Py_ssize_t startinpos;
7085 Py_ssize_t endinpos;
7086 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007087 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007088 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007089 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007090 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00007091
Guido van Rossumd57fd912000-03-10 22:53:23 +00007092 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02007093 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007094
Guido van Rossumd57fd912000-03-10 22:53:23 +00007095 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02007096 if (size == 1 && (unsigned char)s[0] < 128)
7097 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007098
Victor Stinner8f674cc2013-04-17 23:02:17 +02007099 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007100 writer.min_length = size;
7101 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02007102 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007103
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007104 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007105 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007106 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007107 writer.pos = outpos;
7108 if (writer.pos == size)
7109 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007110
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007111 s += writer.pos;
7112 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007113 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007114 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007115 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007116 PyUnicode_WRITE(kind, data, writer.pos, c);
7117 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007118 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007119 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007120 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007121
7122 /* byte outsize range 0x00..0x7f: call the error handler */
7123
7124 if (error_handler == _Py_ERROR_UNKNOWN)
7125 error_handler = get_error_handler(errors);
7126
7127 switch (error_handler)
7128 {
7129 case _Py_ERROR_REPLACE:
7130 case _Py_ERROR_SURROGATEESCAPE:
7131 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007132 but we may switch to UCS2 at the first write */
7133 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7134 goto onError;
7135 kind = writer.kind;
7136 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007137
7138 if (error_handler == _Py_ERROR_REPLACE)
7139 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7140 else
7141 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7142 writer.pos++;
7143 ++s;
7144 break;
7145
7146 case _Py_ERROR_IGNORE:
7147 ++s;
7148 break;
7149
7150 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007151 startinpos = s-starts;
7152 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007153 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007154 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007155 "ascii", "ordinal not in range(128)",
7156 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007157 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007158 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007159 kind = writer.kind;
7160 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007161 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007162 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007163 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007164 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007165 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007166
Benjamin Peterson29060642009-01-31 22:14:21 +00007167 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007168 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007169 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007170 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007171 return NULL;
7172}
7173
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007174/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007175PyObject *
7176PyUnicode_EncodeASCII(const Py_UNICODE *p,
7177 Py_ssize_t size,
7178 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007179{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007180 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007181 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007182 if (unicode == NULL)
7183 return NULL;
7184 result = unicode_encode_ucs1(unicode, errors, 128);
7185 Py_DECREF(unicode);
7186 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007187}
7188
Alexander Belopolsky40018472011-02-26 01:02:56 +00007189PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007190_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007191{
7192 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 PyErr_BadArgument();
7194 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007196 if (PyUnicode_READY(unicode) == -1)
7197 return NULL;
7198 /* Fast path: if it is an ASCII-only string, construct bytes object
7199 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007200 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007201 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7202 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007203 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007204}
7205
7206PyObject *
7207PyUnicode_AsASCIIString(PyObject *unicode)
7208{
7209 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007210}
7211
Steve Dowercc16be82016-09-08 10:35:16 -07007212#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007213
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007214/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007215
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007216#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007217#define NEED_RETRY
7218#endif
7219
Victor Stinner3a50e702011-10-18 21:21:00 +02007220#ifndef WC_ERR_INVALID_CHARS
7221# define WC_ERR_INVALID_CHARS 0x0080
7222#endif
7223
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007224static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007225code_page_name(UINT code_page, PyObject **obj)
7226{
7227 *obj = NULL;
7228 if (code_page == CP_ACP)
7229 return "mbcs";
7230 if (code_page == CP_UTF7)
7231 return "CP_UTF7";
7232 if (code_page == CP_UTF8)
7233 return "CP_UTF8";
7234
7235 *obj = PyBytes_FromFormat("cp%u", code_page);
7236 if (*obj == NULL)
7237 return NULL;
7238 return PyBytes_AS_STRING(*obj);
7239}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007240
Victor Stinner3a50e702011-10-18 21:21:00 +02007241static DWORD
7242decode_code_page_flags(UINT code_page)
7243{
7244 if (code_page == CP_UTF7) {
7245 /* The CP_UTF7 decoder only supports flags=0 */
7246 return 0;
7247 }
7248 else
7249 return MB_ERR_INVALID_CHARS;
7250}
7251
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007252/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 * Decode a byte string from a Windows code page into unicode object in strict
7254 * mode.
7255 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007256 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7257 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007258 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007259static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007260decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007261 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007262 const char *in,
7263 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007264{
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007266 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007268
7269 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 assert(insize > 0);
7271 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7272 if (outsize <= 0)
7273 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274
7275 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007276 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007277 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007279 if (*v == NULL)
7280 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007281 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282 }
7283 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007284 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007285 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007286 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007287 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007288 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007289 }
7290
7291 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007292 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7293 if (outsize <= 0)
7294 goto error;
7295 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007296
Victor Stinner3a50e702011-10-18 21:21:00 +02007297error:
7298 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7299 return -2;
7300 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007301 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007302}
7303
Victor Stinner3a50e702011-10-18 21:21:00 +02007304/*
7305 * Decode a byte string from a code page into unicode object with an error
7306 * handler.
7307 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007308 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 * UnicodeDecodeError exception and returns -1 on error.
7310 */
7311static int
7312decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007313 PyObject **v,
7314 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007315 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007316{
7317 const char *startin = in;
7318 const char *endin = in + size;
7319 const DWORD flags = decode_code_page_flags(code_page);
7320 /* Ideally, we should get reason from FormatMessage. This is the Windows
7321 2000 English version of the message. */
7322 const char *reason = "No mapping for the Unicode character exists "
7323 "in the target code page.";
7324 /* each step cannot decode more than 1 character, but a character can be
7325 represented as a surrogate pair */
7326 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007327 int insize;
7328 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 PyObject *errorHandler = NULL;
7330 PyObject *exc = NULL;
7331 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007332 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007333 DWORD err;
7334 int ret = -1;
7335
7336 assert(size > 0);
7337
7338 encoding = code_page_name(code_page, &encoding_obj);
7339 if (encoding == NULL)
7340 return -1;
7341
Victor Stinner7d00cc12014-03-17 23:08:06 +01007342 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7344 UnicodeDecodeError. */
7345 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7346 if (exc != NULL) {
7347 PyCodec_StrictErrors(exc);
7348 Py_CLEAR(exc);
7349 }
7350 goto error;
7351 }
7352
7353 if (*v == NULL) {
7354 /* Create unicode object */
7355 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7356 PyErr_NoMemory();
7357 goto error;
7358 }
Victor Stinnerab595942011-12-17 04:59:06 +01007359 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007360 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 if (*v == NULL)
7362 goto error;
7363 startout = PyUnicode_AS_UNICODE(*v);
7364 }
7365 else {
7366 /* Extend unicode object */
7367 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7368 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7369 PyErr_NoMemory();
7370 goto error;
7371 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007372 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 goto error;
7374 startout = PyUnicode_AS_UNICODE(*v) + n;
7375 }
7376
7377 /* Decode the byte string character per character */
7378 out = startout;
7379 while (in < endin)
7380 {
7381 /* Decode a character */
7382 insize = 1;
7383 do
7384 {
7385 outsize = MultiByteToWideChar(code_page, flags,
7386 in, insize,
7387 buffer, Py_ARRAY_LENGTH(buffer));
7388 if (outsize > 0)
7389 break;
7390 err = GetLastError();
7391 if (err != ERROR_NO_UNICODE_TRANSLATION
7392 && err != ERROR_INSUFFICIENT_BUFFER)
7393 {
7394 PyErr_SetFromWindowsErr(0);
7395 goto error;
7396 }
7397 insize++;
7398 }
7399 /* 4=maximum length of a UTF-8 sequence */
7400 while (insize <= 4 && (in + insize) <= endin);
7401
7402 if (outsize <= 0) {
7403 Py_ssize_t startinpos, endinpos, outpos;
7404
Victor Stinner7d00cc12014-03-17 23:08:06 +01007405 /* last character in partial decode? */
7406 if (in + insize >= endin && !final)
7407 break;
7408
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 startinpos = in - startin;
7410 endinpos = startinpos + 1;
7411 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007412 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007413 errors, &errorHandler,
7414 encoding, reason,
7415 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007416 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 {
7418 goto error;
7419 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007420 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 }
7422 else {
7423 in += insize;
7424 memcpy(out, buffer, outsize * sizeof(wchar_t));
7425 out += outsize;
7426 }
7427 }
7428
7429 /* write a NUL character at the end */
7430 *out = 0;
7431
7432 /* Extend unicode object */
7433 outsize = out - startout;
7434 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007435 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007437 /* (in - startin) <= size and size is an int */
7438 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007439
7440error:
7441 Py_XDECREF(encoding_obj);
7442 Py_XDECREF(errorHandler);
7443 Py_XDECREF(exc);
7444 return ret;
7445}
7446
Victor Stinner3a50e702011-10-18 21:21:00 +02007447static PyObject *
7448decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007449 const char *s, Py_ssize_t size,
7450 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007451{
Victor Stinner76a31a62011-11-04 00:05:13 +01007452 PyObject *v = NULL;
7453 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007454
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 if (code_page < 0) {
7456 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7457 return NULL;
7458 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007459 if (size < 0) {
7460 PyErr_BadInternalCall();
7461 return NULL;
7462 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007463
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007464 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007465 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007466
Victor Stinner76a31a62011-11-04 00:05:13 +01007467 do
7468 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007469#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007470 if (size > INT_MAX) {
7471 chunk_size = INT_MAX;
7472 final = 0;
7473 done = 0;
7474 }
7475 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007476#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007477 {
7478 chunk_size = (int)size;
7479 final = (consumed == NULL);
7480 done = 1;
7481 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007482
Victor Stinner76a31a62011-11-04 00:05:13 +01007483 if (chunk_size == 0 && done) {
7484 if (v != NULL)
7485 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007486 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007487 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007488
Victor Stinner76a31a62011-11-04 00:05:13 +01007489 converted = decode_code_page_strict(code_page, &v,
7490 s, chunk_size);
7491 if (converted == -2)
7492 converted = decode_code_page_errors(code_page, &v,
7493 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007494 errors, final);
7495 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007496
7497 if (converted < 0) {
7498 Py_XDECREF(v);
7499 return NULL;
7500 }
7501
7502 if (consumed)
7503 *consumed += converted;
7504
7505 s += converted;
7506 size -= converted;
7507 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007508
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007509 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510}
7511
Alexander Belopolsky40018472011-02-26 01:02:56 +00007512PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007513PyUnicode_DecodeCodePageStateful(int code_page,
7514 const char *s,
7515 Py_ssize_t size,
7516 const char *errors,
7517 Py_ssize_t *consumed)
7518{
7519 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7520}
7521
7522PyObject *
7523PyUnicode_DecodeMBCSStateful(const char *s,
7524 Py_ssize_t size,
7525 const char *errors,
7526 Py_ssize_t *consumed)
7527{
7528 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7529}
7530
7531PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007532PyUnicode_DecodeMBCS(const char *s,
7533 Py_ssize_t size,
7534 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007535{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007536 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7537}
7538
Victor Stinner3a50e702011-10-18 21:21:00 +02007539static DWORD
7540encode_code_page_flags(UINT code_page, const char *errors)
7541{
7542 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007543 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007544 }
7545 else if (code_page == CP_UTF7) {
7546 /* CP_UTF7 only supports flags=0 */
7547 return 0;
7548 }
7549 else {
7550 if (errors != NULL && strcmp(errors, "replace") == 0)
7551 return 0;
7552 else
7553 return WC_NO_BEST_FIT_CHARS;
7554 }
7555}
7556
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007557/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007558 * Encode a Unicode string to a Windows code page into a byte string in strict
7559 * mode.
7560 *
7561 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007562 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007563 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007564static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007565encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007566 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007568{
Victor Stinner554f3f02010-06-16 23:33:54 +00007569 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 BOOL *pusedDefaultChar = &usedDefaultChar;
7571 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007572 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007573 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007574 const DWORD flags = encode_code_page_flags(code_page, NULL);
7575 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007576 /* Create a substring so that we can get the UTF-16 representation
7577 of just the slice under consideration. */
7578 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007579
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007581
Victor Stinner3a50e702011-10-18 21:21:00 +02007582 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007583 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007584 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007585 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007586
Victor Stinner2fc507f2011-11-04 20:06:39 +01007587 substring = PyUnicode_Substring(unicode, offset, offset+len);
7588 if (substring == NULL)
7589 return -1;
7590 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7591 if (p == NULL) {
7592 Py_DECREF(substring);
7593 return -1;
7594 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007595 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007596
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007597 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007598 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007599 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007600 NULL, 0,
7601 NULL, pusedDefaultChar);
7602 if (outsize <= 0)
7603 goto error;
7604 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007605 if (pusedDefaultChar && *pusedDefaultChar) {
7606 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007607 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007608 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007609
Victor Stinner3a50e702011-10-18 21:21:00 +02007610 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007612 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007613 if (*outbytes == NULL) {
7614 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007616 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007617 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007618 }
7619 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007621 const Py_ssize_t n = PyBytes_Size(*outbytes);
7622 if (outsize > PY_SSIZE_T_MAX - n) {
7623 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007624 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007625 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007626 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007627 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7628 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007629 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007630 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007631 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007632 }
7633
7634 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007635 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007636 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007637 out, outsize,
7638 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007639 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007640 if (outsize <= 0)
7641 goto error;
7642 if (pusedDefaultChar && *pusedDefaultChar)
7643 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007644 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007645
Victor Stinner3a50e702011-10-18 21:21:00 +02007646error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007647 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007648 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7649 return -2;
7650 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007651 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007652}
7653
Victor Stinner3a50e702011-10-18 21:21:00 +02007654/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007655 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007656 * error handler.
7657 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007658 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007659 * -1 on other error.
7660 */
7661static int
7662encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007663 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007664 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007665{
Victor Stinner3a50e702011-10-18 21:21:00 +02007666 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007667 Py_ssize_t pos = unicode_offset;
7668 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 /* Ideally, we should get reason from FormatMessage. This is the Windows
7670 2000 English version of the message. */
7671 const char *reason = "invalid character";
7672 /* 4=maximum length of a UTF-8 sequence */
7673 char buffer[4];
7674 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7675 Py_ssize_t outsize;
7676 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007677 PyObject *errorHandler = NULL;
7678 PyObject *exc = NULL;
7679 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007680 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007681 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007682 PyObject *rep;
7683 int ret = -1;
7684
7685 assert(insize > 0);
7686
7687 encoding = code_page_name(code_page, &encoding_obj);
7688 if (encoding == NULL)
7689 return -1;
7690
7691 if (errors == NULL || strcmp(errors, "strict") == 0) {
7692 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7693 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007694 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007695 if (exc != NULL) {
7696 PyCodec_StrictErrors(exc);
7697 Py_DECREF(exc);
7698 }
7699 Py_XDECREF(encoding_obj);
7700 return -1;
7701 }
7702
7703 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7704 pusedDefaultChar = &usedDefaultChar;
7705 else
7706 pusedDefaultChar = NULL;
7707
7708 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7709 PyErr_NoMemory();
7710 goto error;
7711 }
7712 outsize = insize * Py_ARRAY_LENGTH(buffer);
7713
7714 if (*outbytes == NULL) {
7715 /* Create string object */
7716 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7717 if (*outbytes == NULL)
7718 goto error;
7719 out = PyBytes_AS_STRING(*outbytes);
7720 }
7721 else {
7722 /* Extend string object */
7723 Py_ssize_t n = PyBytes_Size(*outbytes);
7724 if (n > PY_SSIZE_T_MAX - outsize) {
7725 PyErr_NoMemory();
7726 goto error;
7727 }
7728 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7729 goto error;
7730 out = PyBytes_AS_STRING(*outbytes) + n;
7731 }
7732
7733 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007734 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007735 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007736 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7737 wchar_t chars[2];
7738 int charsize;
7739 if (ch < 0x10000) {
7740 chars[0] = (wchar_t)ch;
7741 charsize = 1;
7742 }
7743 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007744 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7745 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007746 charsize = 2;
7747 }
7748
Victor Stinner3a50e702011-10-18 21:21:00 +02007749 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007750 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007751 buffer, Py_ARRAY_LENGTH(buffer),
7752 NULL, pusedDefaultChar);
7753 if (outsize > 0) {
7754 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7755 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007756 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007757 memcpy(out, buffer, outsize);
7758 out += outsize;
7759 continue;
7760 }
7761 }
7762 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7763 PyErr_SetFromWindowsErr(0);
7764 goto error;
7765 }
7766
Victor Stinner3a50e702011-10-18 21:21:00 +02007767 rep = unicode_encode_call_errorhandler(
7768 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007769 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007770 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007771 if (rep == NULL)
7772 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007773 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007774
7775 if (PyBytes_Check(rep)) {
7776 outsize = PyBytes_GET_SIZE(rep);
7777 if (outsize != 1) {
7778 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7779 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7780 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7781 Py_DECREF(rep);
7782 goto error;
7783 }
7784 out = PyBytes_AS_STRING(*outbytes) + offset;
7785 }
7786 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7787 out += outsize;
7788 }
7789 else {
7790 Py_ssize_t i;
7791 enum PyUnicode_Kind kind;
7792 void *data;
7793
Benjamin Petersonbac79492012-01-14 13:34:47 -05007794 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007795 Py_DECREF(rep);
7796 goto error;
7797 }
7798
7799 outsize = PyUnicode_GET_LENGTH(rep);
7800 if (outsize != 1) {
7801 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7802 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7803 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7804 Py_DECREF(rep);
7805 goto error;
7806 }
7807 out = PyBytes_AS_STRING(*outbytes) + offset;
7808 }
7809 kind = PyUnicode_KIND(rep);
7810 data = PyUnicode_DATA(rep);
7811 for (i=0; i < outsize; i++) {
7812 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7813 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007814 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007815 encoding, unicode,
7816 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007817 "unable to encode error handler result to ASCII");
7818 Py_DECREF(rep);
7819 goto error;
7820 }
7821 *out = (unsigned char)ch;
7822 out++;
7823 }
7824 }
7825 Py_DECREF(rep);
7826 }
7827 /* write a NUL byte */
7828 *out = 0;
7829 outsize = out - PyBytes_AS_STRING(*outbytes);
7830 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7831 if (_PyBytes_Resize(outbytes, outsize) < 0)
7832 goto error;
7833 ret = 0;
7834
7835error:
7836 Py_XDECREF(encoding_obj);
7837 Py_XDECREF(errorHandler);
7838 Py_XDECREF(exc);
7839 return ret;
7840}
7841
Victor Stinner3a50e702011-10-18 21:21:00 +02007842static PyObject *
7843encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007844 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007845 const char *errors)
7846{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007847 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007848 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007849 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007850 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007851
Victor Stinner29dacf22015-01-26 16:41:32 +01007852 if (!PyUnicode_Check(unicode)) {
7853 PyErr_BadArgument();
7854 return NULL;
7855 }
7856
Benjamin Petersonbac79492012-01-14 13:34:47 -05007857 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007858 return NULL;
7859 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007860
Victor Stinner3a50e702011-10-18 21:21:00 +02007861 if (code_page < 0) {
7862 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7863 return NULL;
7864 }
7865
Martin v. Löwis3d325192011-11-04 18:23:06 +01007866 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007867 return PyBytes_FromStringAndSize(NULL, 0);
7868
Victor Stinner7581cef2011-11-03 22:32:33 +01007869 offset = 0;
7870 do
7871 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007872#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007873 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007874 chunks. */
7875 if (len > INT_MAX/2) {
7876 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007877 done = 0;
7878 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007879 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007880#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007881 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007882 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007883 done = 1;
7884 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007885
Victor Stinner76a31a62011-11-04 00:05:13 +01007886 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007887 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007888 errors);
7889 if (ret == -2)
7890 ret = encode_code_page_errors(code_page, &outbytes,
7891 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007892 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007893 if (ret < 0) {
7894 Py_XDECREF(outbytes);
7895 return NULL;
7896 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007897
Victor Stinner7581cef2011-11-03 22:32:33 +01007898 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007899 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007900 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007901
Victor Stinner3a50e702011-10-18 21:21:00 +02007902 return outbytes;
7903}
7904
7905PyObject *
7906PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7907 Py_ssize_t size,
7908 const char *errors)
7909{
Victor Stinner7581cef2011-11-03 22:32:33 +01007910 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007911 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007912 if (unicode == NULL)
7913 return NULL;
7914 res = encode_code_page(CP_ACP, unicode, errors);
7915 Py_DECREF(unicode);
7916 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007917}
7918
7919PyObject *
7920PyUnicode_EncodeCodePage(int code_page,
7921 PyObject *unicode,
7922 const char *errors)
7923{
Victor Stinner7581cef2011-11-03 22:32:33 +01007924 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007925}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007926
Alexander Belopolsky40018472011-02-26 01:02:56 +00007927PyObject *
7928PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007929{
Victor Stinner7581cef2011-11-03 22:32:33 +01007930 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007931}
7932
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007933#undef NEED_RETRY
7934
Steve Dowercc16be82016-09-08 10:35:16 -07007935#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007936
Guido van Rossumd57fd912000-03-10 22:53:23 +00007937/* --- Character Mapping Codec -------------------------------------------- */
7938
Victor Stinnerfb161b12013-04-18 01:44:27 +02007939static int
7940charmap_decode_string(const char *s,
7941 Py_ssize_t size,
7942 PyObject *mapping,
7943 const char *errors,
7944 _PyUnicodeWriter *writer)
7945{
7946 const char *starts = s;
7947 const char *e;
7948 Py_ssize_t startinpos, endinpos;
7949 PyObject *errorHandler = NULL, *exc = NULL;
7950 Py_ssize_t maplen;
7951 enum PyUnicode_Kind mapkind;
7952 void *mapdata;
7953 Py_UCS4 x;
7954 unsigned char ch;
7955
7956 if (PyUnicode_READY(mapping) == -1)
7957 return -1;
7958
7959 maplen = PyUnicode_GET_LENGTH(mapping);
7960 mapdata = PyUnicode_DATA(mapping);
7961 mapkind = PyUnicode_KIND(mapping);
7962
7963 e = s + size;
7964
7965 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7966 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7967 * is disabled in encoding aliases, latin1 is preferred because
7968 * its implementation is faster. */
7969 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7970 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7971 Py_UCS4 maxchar = writer->maxchar;
7972
7973 assert (writer->kind == PyUnicode_1BYTE_KIND);
7974 while (s < e) {
7975 ch = *s;
7976 x = mapdata_ucs1[ch];
7977 if (x > maxchar) {
7978 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7979 goto onError;
7980 maxchar = writer->maxchar;
7981 outdata = (Py_UCS1 *)writer->data;
7982 }
7983 outdata[writer->pos] = x;
7984 writer->pos++;
7985 ++s;
7986 }
7987 return 0;
7988 }
7989
7990 while (s < e) {
7991 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7992 enum PyUnicode_Kind outkind = writer->kind;
7993 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7994 if (outkind == PyUnicode_1BYTE_KIND) {
7995 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7996 Py_UCS4 maxchar = writer->maxchar;
7997 while (s < e) {
7998 ch = *s;
7999 x = mapdata_ucs2[ch];
8000 if (x > maxchar)
8001 goto Error;
8002 outdata[writer->pos] = x;
8003 writer->pos++;
8004 ++s;
8005 }
8006 break;
8007 }
8008 else if (outkind == PyUnicode_2BYTE_KIND) {
8009 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8010 while (s < e) {
8011 ch = *s;
8012 x = mapdata_ucs2[ch];
8013 if (x == 0xFFFE)
8014 goto Error;
8015 outdata[writer->pos] = x;
8016 writer->pos++;
8017 ++s;
8018 }
8019 break;
8020 }
8021 }
8022 ch = *s;
8023
8024 if (ch < maplen)
8025 x = PyUnicode_READ(mapkind, mapdata, ch);
8026 else
8027 x = 0xfffe; /* invalid value */
8028Error:
8029 if (x == 0xfffe)
8030 {
8031 /* undefined mapping */
8032 startinpos = s-starts;
8033 endinpos = startinpos+1;
8034 if (unicode_decode_call_errorhandler_writer(
8035 errors, &errorHandler,
8036 "charmap", "character maps to <undefined>",
8037 &starts, &e, &startinpos, &endinpos, &exc, &s,
8038 writer)) {
8039 goto onError;
8040 }
8041 continue;
8042 }
8043
8044 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8045 goto onError;
8046 ++s;
8047 }
8048 Py_XDECREF(errorHandler);
8049 Py_XDECREF(exc);
8050 return 0;
8051
8052onError:
8053 Py_XDECREF(errorHandler);
8054 Py_XDECREF(exc);
8055 return -1;
8056}
8057
8058static int
8059charmap_decode_mapping(const char *s,
8060 Py_ssize_t size,
8061 PyObject *mapping,
8062 const char *errors,
8063 _PyUnicodeWriter *writer)
8064{
8065 const char *starts = s;
8066 const char *e;
8067 Py_ssize_t startinpos, endinpos;
8068 PyObject *errorHandler = NULL, *exc = NULL;
8069 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02008070 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008071
8072 e = s + size;
8073
8074 while (s < e) {
8075 ch = *s;
8076
8077 /* Get mapping (char ordinal -> integer, Unicode char or None) */
8078 key = PyLong_FromLong((long)ch);
8079 if (key == NULL)
8080 goto onError;
8081
8082 item = PyObject_GetItem(mapping, key);
8083 Py_DECREF(key);
8084 if (item == NULL) {
8085 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8086 /* No mapping found means: mapping is undefined. */
8087 PyErr_Clear();
8088 goto Undefined;
8089 } else
8090 goto onError;
8091 }
8092
8093 /* Apply mapping */
8094 if (item == Py_None)
8095 goto Undefined;
8096 if (PyLong_Check(item)) {
8097 long value = PyLong_AS_LONG(item);
8098 if (value == 0xFFFE)
8099 goto Undefined;
8100 if (value < 0 || value > MAX_UNICODE) {
8101 PyErr_Format(PyExc_TypeError,
8102 "character mapping must be in range(0x%lx)",
8103 (unsigned long)MAX_UNICODE + 1);
8104 goto onError;
8105 }
8106
8107 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8108 goto onError;
8109 }
8110 else if (PyUnicode_Check(item)) {
8111 if (PyUnicode_READY(item) == -1)
8112 goto onError;
8113 if (PyUnicode_GET_LENGTH(item) == 1) {
8114 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8115 if (value == 0xFFFE)
8116 goto Undefined;
8117 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8118 goto onError;
8119 }
8120 else {
8121 writer->overallocate = 1;
8122 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8123 goto onError;
8124 }
8125 }
8126 else {
8127 /* wrong return value */
8128 PyErr_SetString(PyExc_TypeError,
8129 "character mapping must return integer, None or str");
8130 goto onError;
8131 }
8132 Py_CLEAR(item);
8133 ++s;
8134 continue;
8135
8136Undefined:
8137 /* undefined mapping */
8138 Py_CLEAR(item);
8139 startinpos = s-starts;
8140 endinpos = startinpos+1;
8141 if (unicode_decode_call_errorhandler_writer(
8142 errors, &errorHandler,
8143 "charmap", "character maps to <undefined>",
8144 &starts, &e, &startinpos, &endinpos, &exc, &s,
8145 writer)) {
8146 goto onError;
8147 }
8148 }
8149 Py_XDECREF(errorHandler);
8150 Py_XDECREF(exc);
8151 return 0;
8152
8153onError:
8154 Py_XDECREF(item);
8155 Py_XDECREF(errorHandler);
8156 Py_XDECREF(exc);
8157 return -1;
8158}
8159
Alexander Belopolsky40018472011-02-26 01:02:56 +00008160PyObject *
8161PyUnicode_DecodeCharmap(const char *s,
8162 Py_ssize_t size,
8163 PyObject *mapping,
8164 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008165{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008166 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008167
Guido van Rossumd57fd912000-03-10 22:53:23 +00008168 /* Default to Latin-1 */
8169 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008170 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008171
Guido van Rossumd57fd912000-03-10 22:53:23 +00008172 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008173 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008174 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008175 writer.min_length = size;
8176 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008177 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008178
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008179 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008180 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8181 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008182 }
8183 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008184 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8185 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008187 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008188
Benjamin Peterson29060642009-01-31 22:14:21 +00008189 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008190 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008191 return NULL;
8192}
8193
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194/* Charmap encoding: the lookup table */
8195
Alexander Belopolsky40018472011-02-26 01:02:56 +00008196struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 PyObject_HEAD
8198 unsigned char level1[32];
8199 int count2, count3;
8200 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201};
8202
8203static PyObject*
8204encoding_map_size(PyObject *obj, PyObject* args)
8205{
8206 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008207 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008209}
8210
8211static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008212 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 PyDoc_STR("Return the size (in bytes) of this object") },
8214 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008215};
8216
8217static void
8218encoding_map_dealloc(PyObject* o)
8219{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008220 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008221}
8222
8223static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008224 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 "EncodingMap", /*tp_name*/
8226 sizeof(struct encoding_map), /*tp_basicsize*/
8227 0, /*tp_itemsize*/
8228 /* methods */
8229 encoding_map_dealloc, /*tp_dealloc*/
8230 0, /*tp_print*/
8231 0, /*tp_getattr*/
8232 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008233 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 0, /*tp_repr*/
8235 0, /*tp_as_number*/
8236 0, /*tp_as_sequence*/
8237 0, /*tp_as_mapping*/
8238 0, /*tp_hash*/
8239 0, /*tp_call*/
8240 0, /*tp_str*/
8241 0, /*tp_getattro*/
8242 0, /*tp_setattro*/
8243 0, /*tp_as_buffer*/
8244 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8245 0, /*tp_doc*/
8246 0, /*tp_traverse*/
8247 0, /*tp_clear*/
8248 0, /*tp_richcompare*/
8249 0, /*tp_weaklistoffset*/
8250 0, /*tp_iter*/
8251 0, /*tp_iternext*/
8252 encoding_map_methods, /*tp_methods*/
8253 0, /*tp_members*/
8254 0, /*tp_getset*/
8255 0, /*tp_base*/
8256 0, /*tp_dict*/
8257 0, /*tp_descr_get*/
8258 0, /*tp_descr_set*/
8259 0, /*tp_dictoffset*/
8260 0, /*tp_init*/
8261 0, /*tp_alloc*/
8262 0, /*tp_new*/
8263 0, /*tp_free*/
8264 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008265};
8266
8267PyObject*
8268PyUnicode_BuildEncodingMap(PyObject* string)
8269{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008270 PyObject *result;
8271 struct encoding_map *mresult;
8272 int i;
8273 int need_dict = 0;
8274 unsigned char level1[32];
8275 unsigned char level2[512];
8276 unsigned char *mlevel1, *mlevel2, *mlevel3;
8277 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008278 int kind;
8279 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008280 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008282
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008283 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008284 PyErr_BadArgument();
8285 return NULL;
8286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008287 kind = PyUnicode_KIND(string);
8288 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008289 length = PyUnicode_GET_LENGTH(string);
8290 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008291 memset(level1, 0xFF, sizeof level1);
8292 memset(level2, 0xFF, sizeof level2);
8293
8294 /* If there isn't a one-to-one mapping of NULL to \0,
8295 or if there are non-BMP characters, we need to use
8296 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008297 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008298 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008299 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008300 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008301 ch = PyUnicode_READ(kind, data, i);
8302 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008303 need_dict = 1;
8304 break;
8305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008306 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008307 /* unmapped character */
8308 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008309 l1 = ch >> 11;
8310 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008311 if (level1[l1] == 0xFF)
8312 level1[l1] = count2++;
8313 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008315 }
8316
8317 if (count2 >= 0xFF || count3 >= 0xFF)
8318 need_dict = 1;
8319
8320 if (need_dict) {
8321 PyObject *result = PyDict_New();
8322 PyObject *key, *value;
8323 if (!result)
8324 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008325 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008326 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008327 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008328 if (!key || !value)
8329 goto failed1;
8330 if (PyDict_SetItem(result, key, value) == -1)
8331 goto failed1;
8332 Py_DECREF(key);
8333 Py_DECREF(value);
8334 }
8335 return result;
8336 failed1:
8337 Py_XDECREF(key);
8338 Py_XDECREF(value);
8339 Py_DECREF(result);
8340 return NULL;
8341 }
8342
8343 /* Create a three-level trie */
8344 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8345 16*count2 + 128*count3 - 1);
8346 if (!result)
8347 return PyErr_NoMemory();
8348 PyObject_Init(result, &EncodingMapType);
8349 mresult = (struct encoding_map*)result;
8350 mresult->count2 = count2;
8351 mresult->count3 = count3;
8352 mlevel1 = mresult->level1;
8353 mlevel2 = mresult->level23;
8354 mlevel3 = mresult->level23 + 16*count2;
8355 memcpy(mlevel1, level1, 32);
8356 memset(mlevel2, 0xFF, 16*count2);
8357 memset(mlevel3, 0, 128*count3);
8358 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008359 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008360 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008361 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8362 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008363 /* unmapped character */
8364 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008365 o1 = ch>>11;
8366 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008367 i2 = 16*mlevel1[o1] + o2;
8368 if (mlevel2[i2] == 0xFF)
8369 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008370 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008371 i3 = 128*mlevel2[i2] + o3;
8372 mlevel3[i3] = i;
8373 }
8374 return result;
8375}
8376
8377static int
Victor Stinner22168992011-11-20 17:09:18 +01008378encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008379{
8380 struct encoding_map *map = (struct encoding_map*)mapping;
8381 int l1 = c>>11;
8382 int l2 = (c>>7) & 0xF;
8383 int l3 = c & 0x7F;
8384 int i;
8385
Victor Stinner22168992011-11-20 17:09:18 +01008386 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008388 if (c == 0)
8389 return 0;
8390 /* level 1*/
8391 i = map->level1[l1];
8392 if (i == 0xFF) {
8393 return -1;
8394 }
8395 /* level 2*/
8396 i = map->level23[16*i+l2];
8397 if (i == 0xFF) {
8398 return -1;
8399 }
8400 /* level 3 */
8401 i = map->level23[16*map->count2 + 128*i + l3];
8402 if (i == 0) {
8403 return -1;
8404 }
8405 return i;
8406}
8407
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408/* Lookup the character ch in the mapping. If the character
8409 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008410 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008411static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008412charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008413{
Christian Heimes217cfd12007-12-02 14:31:20 +00008414 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 PyObject *x;
8416
8417 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 x = PyObject_GetItem(mapping, w);
8420 Py_DECREF(w);
8421 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8423 /* No mapping found means: mapping is undefined. */
8424 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008425 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 } else
8427 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008428 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008429 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008431 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 long value = PyLong_AS_LONG(x);
8433 if (value < 0 || value > 255) {
8434 PyErr_SetString(PyExc_TypeError,
8435 "character mapping must be in range(256)");
8436 Py_DECREF(x);
8437 return NULL;
8438 }
8439 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008440 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008441 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008443 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 /* wrong return value */
8445 PyErr_Format(PyExc_TypeError,
8446 "character mapping must return integer, bytes or None, not %.400s",
8447 x->ob_type->tp_name);
8448 Py_DECREF(x);
8449 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008450 }
8451}
8452
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008453static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008454charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008455{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008456 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8457 /* exponentially overallocate to minimize reallocations */
8458 if (requiredsize < 2*outsize)
8459 requiredsize = 2*outsize;
8460 if (_PyBytes_Resize(outobj, requiredsize))
8461 return -1;
8462 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008463}
8464
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008467} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008469 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 space is available. Return a new reference to the object that
8471 was put in the output buffer, or Py_None, if the mapping was undefined
8472 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008473 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008474static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008475charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008476 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008478 PyObject *rep;
8479 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008480 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008481
Christian Heimes90aa7642007-12-19 02:45:37 +00008482 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008483 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008485 if (res == -1)
8486 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 if (outsize<requiredsize)
8488 if (charmapencode_resize(outobj, outpos, requiredsize))
8489 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008490 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 outstart[(*outpos)++] = (char)res;
8492 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008493 }
8494
8495 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008498 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 Py_DECREF(rep);
8500 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008501 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 if (PyLong_Check(rep)) {
8503 Py_ssize_t requiredsize = *outpos+1;
8504 if (outsize<requiredsize)
8505 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8506 Py_DECREF(rep);
8507 return enc_EXCEPTION;
8508 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008509 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008511 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 else {
8513 const char *repchars = PyBytes_AS_STRING(rep);
8514 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8515 Py_ssize_t requiredsize = *outpos+repsize;
8516 if (outsize<requiredsize)
8517 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8518 Py_DECREF(rep);
8519 return enc_EXCEPTION;
8520 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008521 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 memcpy(outstart + *outpos, repchars, repsize);
8523 *outpos += repsize;
8524 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008526 Py_DECREF(rep);
8527 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528}
8529
8530/* handle an error in PyUnicode_EncodeCharmap
8531 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008532static int
8533charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008534 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008536 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008537 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538{
8539 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008540 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008541 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008542 enum PyUnicode_Kind kind;
8543 void *data;
8544 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008545 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008546 Py_ssize_t collstartpos = *inpos;
8547 Py_ssize_t collendpos = *inpos+1;
8548 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008549 const char *encoding = "charmap";
8550 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008551 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008552 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008553 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008554
Benjamin Petersonbac79492012-01-14 13:34:47 -05008555 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008556 return -1;
8557 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558 /* find all unencodable characters */
8559 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008560 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008561 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008562 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008563 val = encoding_map_lookup(ch, mapping);
8564 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 break;
8566 ++collendpos;
8567 continue;
8568 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008569
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008570 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8571 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 if (rep==NULL)
8573 return -1;
8574 else if (rep!=Py_None) {
8575 Py_DECREF(rep);
8576 break;
8577 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008578 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 }
8581 /* cache callback name lookup
8582 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008583 if (*error_handler == _Py_ERROR_UNKNOWN)
8584 *error_handler = get_error_handler(errors);
8585
8586 switch (*error_handler) {
8587 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008588 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008589 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008590
8591 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008592 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 x = charmapencode_output('?', mapping, res, respos);
8594 if (x==enc_EXCEPTION) {
8595 return -1;
8596 }
8597 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008598 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 return -1;
8600 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008601 }
8602 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008603 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008604 *inpos = collendpos;
8605 break;
Victor Stinner50149202015-09-22 00:26:54 +02008606
8607 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008608 /* generate replacement (temporarily (mis)uses p) */
8609 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 char buffer[2+29+1+1];
8611 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008612 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 for (cp = buffer; *cp; ++cp) {
8614 x = charmapencode_output(*cp, mapping, res, respos);
8615 if (x==enc_EXCEPTION)
8616 return -1;
8617 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008618 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 return -1;
8620 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008621 }
8622 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008623 *inpos = collendpos;
8624 break;
Victor Stinner50149202015-09-22 00:26:54 +02008625
Benjamin Peterson14339b62009-01-31 16:36:08 +00008626 default:
Victor Stinner50149202015-09-22 00:26:54 +02008627 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008628 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008630 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008632 if (PyBytes_Check(repunicode)) {
8633 /* Directly copy bytes result to output. */
8634 Py_ssize_t outsize = PyBytes_Size(*res);
8635 Py_ssize_t requiredsize;
8636 repsize = PyBytes_Size(repunicode);
8637 requiredsize = *respos + repsize;
8638 if (requiredsize > outsize)
8639 /* Make room for all additional bytes. */
8640 if (charmapencode_resize(res, respos, requiredsize)) {
8641 Py_DECREF(repunicode);
8642 return -1;
8643 }
8644 memcpy(PyBytes_AsString(*res) + *respos,
8645 PyBytes_AsString(repunicode), repsize);
8646 *respos += repsize;
8647 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008648 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008649 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008650 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008651 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008652 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008653 Py_DECREF(repunicode);
8654 return -1;
8655 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008656 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008657 data = PyUnicode_DATA(repunicode);
8658 kind = PyUnicode_KIND(repunicode);
8659 for (index = 0; index < repsize; index++) {
8660 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8661 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008663 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 return -1;
8665 }
8666 else if (x==enc_FAILED) {
8667 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008668 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 return -1;
8670 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008671 }
8672 *inpos = newpos;
8673 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674 }
8675 return 0;
8676}
8677
Alexander Belopolsky40018472011-02-26 01:02:56 +00008678PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008679_PyUnicode_EncodeCharmap(PyObject *unicode,
8680 PyObject *mapping,
8681 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008682{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683 /* output object */
8684 PyObject *res = NULL;
8685 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008686 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008687 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008689 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008690 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008692 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008693 void *data;
8694 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008695
Benjamin Petersonbac79492012-01-14 13:34:47 -05008696 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008697 return NULL;
8698 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008699 data = PyUnicode_DATA(unicode);
8700 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008701
Guido van Rossumd57fd912000-03-10 22:53:23 +00008702 /* Default to Latin-1 */
8703 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008704 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008706 /* allocate enough for a simple encoding without
8707 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008708 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008709 if (res == NULL)
8710 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008711 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008713
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008715 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008717 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 if (x==enc_EXCEPTION) /* error */
8719 goto onError;
8720 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008721 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008723 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 &res, &respos)) {
8725 goto onError;
8726 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 else
8729 /* done with this character => adjust input position */
8730 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008731 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008732
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008733 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008734 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008735 if (_PyBytes_Resize(&res, respos) < 0)
8736 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008737
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008739 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008740 return res;
8741
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008743 Py_XDECREF(res);
8744 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008745 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 return NULL;
8747}
8748
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008749/* Deprecated */
8750PyObject *
8751PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8752 Py_ssize_t size,
8753 PyObject *mapping,
8754 const char *errors)
8755{
8756 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008757 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008758 if (unicode == NULL)
8759 return NULL;
8760 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8761 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008762 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008763}
8764
Alexander Belopolsky40018472011-02-26 01:02:56 +00008765PyObject *
8766PyUnicode_AsCharmapString(PyObject *unicode,
8767 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008768{
8769 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 PyErr_BadArgument();
8771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008773 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008774}
8775
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008777static void
8778make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008780 Py_ssize_t startpos, Py_ssize_t endpos,
8781 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008782{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008783 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 *exceptionObject = _PyUnicodeTranslateError_Create(
8785 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786 }
8787 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008788 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8789 goto onError;
8790 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8791 goto onError;
8792 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8793 goto onError;
8794 return;
8795 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008796 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008797 }
8798}
8799
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008800/* error handling callback helper:
8801 build arguments, call the callback and check the arguments,
8802 put the result into newpos and return the replacement string, which
8803 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008804static PyObject *
8805unicode_translate_call_errorhandler(const char *errors,
8806 PyObject **errorHandler,
8807 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008809 Py_ssize_t startpos, Py_ssize_t endpos,
8810 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008811{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008812 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008813
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008814 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008815 PyObject *restuple;
8816 PyObject *resunicode;
8817
8818 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008819 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008820 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008822 }
8823
8824 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008825 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008826 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008827 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008828
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008829 restuple = PyObject_CallFunctionObjArgs(
8830 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008831 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008833 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008834 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 Py_DECREF(restuple);
8836 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008837 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008838 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008839 &resunicode, &i_newpos)) {
8840 Py_DECREF(restuple);
8841 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008842 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008843 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008845 else
8846 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008847 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008848 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 Py_DECREF(restuple);
8850 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008851 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008852 Py_INCREF(resunicode);
8853 Py_DECREF(restuple);
8854 return resunicode;
8855}
8856
8857/* Lookup the character ch in the mapping and put the result in result,
8858 which must be decrefed by the caller.
8859 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008860static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008862{
Christian Heimes217cfd12007-12-02 14:31:20 +00008863 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008864 PyObject *x;
8865
8866 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008867 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008868 x = PyObject_GetItem(mapping, w);
8869 Py_DECREF(w);
8870 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008871 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8872 /* No mapping found means: use 1:1 mapping. */
8873 PyErr_Clear();
8874 *result = NULL;
8875 return 0;
8876 } else
8877 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008878 }
8879 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008880 *result = x;
8881 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008882 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008883 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008884 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008885 if (value < 0 || value > MAX_UNICODE) {
8886 PyErr_Format(PyExc_ValueError,
8887 "character mapping must be in range(0x%x)",
8888 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008889 Py_DECREF(x);
8890 return -1;
8891 }
8892 *result = x;
8893 return 0;
8894 }
8895 else if (PyUnicode_Check(x)) {
8896 *result = x;
8897 return 0;
8898 }
8899 else {
8900 /* wrong return value */
8901 PyErr_SetString(PyExc_TypeError,
8902 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008903 Py_DECREF(x);
8904 return -1;
8905 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008906}
Victor Stinner1194ea02014-04-04 19:37:40 +02008907
8908/* lookup the character, write the result into the writer.
8909 Return 1 if the result was written into the writer, return 0 if the mapping
8910 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008911static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008912charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8913 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008914{
Victor Stinner1194ea02014-04-04 19:37:40 +02008915 PyObject *item;
8916
8917 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008919
8920 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008922 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008925 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008926 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008927
8928 if (item == Py_None) {
8929 Py_DECREF(item);
8930 return 0;
8931 }
8932
8933 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008934 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8935 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8936 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008937 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8938 Py_DECREF(item);
8939 return -1;
8940 }
8941 Py_DECREF(item);
8942 return 1;
8943 }
8944
8945 if (!PyUnicode_Check(item)) {
8946 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008947 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008948 }
8949
8950 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8951 Py_DECREF(item);
8952 return -1;
8953 }
8954
8955 Py_DECREF(item);
8956 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008957}
8958
Victor Stinner89a76ab2014-04-05 11:44:04 +02008959static int
8960unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8961 Py_UCS1 *translate)
8962{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008963 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008964 int ret = 0;
8965
Victor Stinner89a76ab2014-04-05 11:44:04 +02008966 if (charmaptranslate_lookup(ch, mapping, &item)) {
8967 return -1;
8968 }
8969
8970 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008971 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008972 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008973 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008974 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008975 /* not found => default to 1:1 mapping */
8976 translate[ch] = ch;
8977 return 1;
8978 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008979 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008980 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008981 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8982 used it */
8983 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008984 /* invalid character or character outside ASCII:
8985 skip the fast translate */
8986 goto exit;
8987 }
8988 translate[ch] = (Py_UCS1)replace;
8989 }
8990 else if (PyUnicode_Check(item)) {
8991 Py_UCS4 replace;
8992
8993 if (PyUnicode_READY(item) == -1) {
8994 Py_DECREF(item);
8995 return -1;
8996 }
8997 if (PyUnicode_GET_LENGTH(item) != 1)
8998 goto exit;
8999
9000 replace = PyUnicode_READ_CHAR(item, 0);
9001 if (replace > 127)
9002 goto exit;
9003 translate[ch] = (Py_UCS1)replace;
9004 }
9005 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04009006 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02009007 goto exit;
9008 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009009 ret = 1;
9010
Benjamin Peterson1365de72014-04-07 20:15:41 -04009011 exit:
9012 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009013 return ret;
9014}
9015
9016/* Fast path for ascii => ascii translation. Return 1 if the whole string
9017 was translated into writer, return 0 if the input string was partially
9018 translated into writer, raise an exception and return -1 on error. */
9019static int
9020unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009021 _PyUnicodeWriter *writer, int ignore,
9022 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009023{
Victor Stinner872b2912014-04-05 14:27:07 +02009024 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009025 Py_ssize_t len;
9026 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02009027 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009028
Victor Stinner89a76ab2014-04-05 11:44:04 +02009029 len = PyUnicode_GET_LENGTH(input);
9030
Victor Stinner872b2912014-04-05 14:27:07 +02009031 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009032
9033 in = PyUnicode_1BYTE_DATA(input);
9034 end = in + len;
9035
9036 assert(PyUnicode_IS_ASCII(writer->buffer));
9037 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9038 out = PyUnicode_1BYTE_DATA(writer->buffer);
9039
Victor Stinner872b2912014-04-05 14:27:07 +02009040 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02009041 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02009042 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02009043 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02009044 int translate = unicode_fast_translate_lookup(mapping, ch,
9045 ascii_table);
9046 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009047 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02009048 if (translate == 0)
9049 goto exit;
9050 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02009051 }
Victor Stinner872b2912014-04-05 14:27:07 +02009052 if (ch2 == 0xfe) {
9053 if (ignore)
9054 continue;
9055 goto exit;
9056 }
9057 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009058 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02009059 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009060 }
Victor Stinner872b2912014-04-05 14:27:07 +02009061 res = 1;
9062
9063exit:
9064 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009065 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02009066 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009067}
9068
Victor Stinner3222da22015-10-01 22:07:32 +02009069static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070_PyUnicode_TranslateCharmap(PyObject *input,
9071 PyObject *mapping,
9072 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02009075 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 Py_ssize_t size, i;
9077 int kind;
9078 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02009079 _PyUnicodeWriter writer;
9080 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02009081 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009082 PyObject *errorHandler = NULL;
9083 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009084 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009085 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009086
Guido van Rossumd57fd912000-03-10 22:53:23 +00009087 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009088 PyErr_BadArgument();
9089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009090 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 if (PyUnicode_READY(input) == -1)
9093 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009094 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 kind = PyUnicode_KIND(input);
9096 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009098 if (size == 0)
9099 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009101 /* allocate enough for a simple 1:1 translation without
9102 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009103 _PyUnicodeWriter_Init(&writer);
9104 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009105 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009106
Victor Stinner872b2912014-04-05 14:27:07 +02009107 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9108
Victor Stinner33798672016-03-01 21:59:58 +01009109 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009110 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009111 if (PyUnicode_IS_ASCII(input)) {
9112 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9113 if (res < 0) {
9114 _PyUnicodeWriter_Dealloc(&writer);
9115 return NULL;
9116 }
9117 if (res == 1)
9118 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009119 }
Victor Stinner33798672016-03-01 21:59:58 +01009120 else {
9121 i = 0;
9122 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009125 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009126 int translate;
9127 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9128 Py_ssize_t newpos;
9129 /* startpos for collecting untranslatable chars */
9130 Py_ssize_t collstart;
9131 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009132 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009133
Victor Stinner1194ea02014-04-04 19:37:40 +02009134 ch = PyUnicode_READ(kind, data, i);
9135 translate = charmaptranslate_output(ch, mapping, &writer);
9136 if (translate < 0)
9137 goto onError;
9138
9139 if (translate != 0) {
9140 /* it worked => adjust input pointer */
9141 ++i;
9142 continue;
9143 }
9144
9145 /* untranslatable character */
9146 collstart = i;
9147 collend = i+1;
9148
9149 /* find all untranslatable characters */
9150 while (collend < size) {
9151 PyObject *x;
9152 ch = PyUnicode_READ(kind, data, collend);
9153 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009154 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009155 Py_XDECREF(x);
9156 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009158 ++collend;
9159 }
9160
9161 if (ignore) {
9162 i = collend;
9163 }
9164 else {
9165 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9166 reason, input, &exc,
9167 collstart, collend, &newpos);
9168 if (repunicode == NULL)
9169 goto onError;
9170 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009172 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009173 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009174 Py_DECREF(repunicode);
9175 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009176 }
9177 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009178 Py_XDECREF(exc);
9179 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009180 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181
Benjamin Peterson29060642009-01-31 22:14:21 +00009182 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009183 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009184 Py_XDECREF(exc);
9185 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009186 return NULL;
9187}
9188
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189/* Deprecated. Use PyUnicode_Translate instead. */
9190PyObject *
9191PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9192 Py_ssize_t size,
9193 PyObject *mapping,
9194 const char *errors)
9195{
Christian Heimes5f520f42012-09-11 14:03:25 +02009196 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009197 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 if (!unicode)
9199 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009200 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9201 Py_DECREF(unicode);
9202 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203}
9204
Alexander Belopolsky40018472011-02-26 01:02:56 +00009205PyObject *
9206PyUnicode_Translate(PyObject *str,
9207 PyObject *mapping,
9208 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009209{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009210 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009211 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009212 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009213}
Tim Petersced69f82003-09-16 20:30:58 +00009214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215PyObject *
9216_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9217{
9218 if (!PyUnicode_Check(unicode)) {
9219 PyErr_BadInternalCall();
9220 return NULL;
9221 }
9222 if (PyUnicode_READY(unicode) == -1)
9223 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009224 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 /* If the string is already ASCII, just return the same string */
9226 Py_INCREF(unicode);
9227 return unicode;
9228 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009229
9230 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9231 PyObject *result = PyUnicode_New(len, 127);
9232 if (result == NULL) {
9233 return NULL;
9234 }
9235
9236 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9237 int kind = PyUnicode_KIND(unicode);
9238 const void *data = PyUnicode_DATA(unicode);
9239 Py_ssize_t i;
9240 for (i = 0; i < len; ++i) {
9241 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9242 if (ch < 127) {
9243 out[i] = ch;
9244 }
9245 else if (Py_UNICODE_ISSPACE(ch)) {
9246 out[i] = ' ';
9247 }
9248 else {
9249 int decimal = Py_UNICODE_TODECIMAL(ch);
9250 if (decimal < 0) {
9251 out[i] = '?';
9252 _PyUnicode_LENGTH(result) = i + 1;
9253 break;
9254 }
9255 out[i] = '0' + decimal;
9256 }
9257 }
9258
9259 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260}
9261
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009262PyObject *
9263PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9264 Py_ssize_t length)
9265{
Victor Stinnerf0124502011-11-21 23:12:56 +01009266 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009267 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009268 Py_UCS4 maxchar;
9269 enum PyUnicode_Kind kind;
9270 void *data;
9271
Victor Stinner99d7ad02012-02-22 13:37:39 +01009272 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009273 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009274 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009275 if (ch > 127) {
9276 int decimal = Py_UNICODE_TODECIMAL(ch);
9277 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009278 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009279 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009280 }
9281 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009282
9283 /* Copy to a new string */
9284 decimal = PyUnicode_New(length, maxchar);
9285 if (decimal == NULL)
9286 return decimal;
9287 kind = PyUnicode_KIND(decimal);
9288 data = PyUnicode_DATA(decimal);
9289 /* Iterate over code points */
9290 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009291 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009292 if (ch > 127) {
9293 int decimal = Py_UNICODE_TODECIMAL(ch);
9294 if (decimal >= 0)
9295 ch = '0' + decimal;
9296 }
9297 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009299 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009300}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009301/* --- Decimal Encoder ---------------------------------------------------- */
9302
Alexander Belopolsky40018472011-02-26 01:02:56 +00009303int
9304PyUnicode_EncodeDecimal(Py_UNICODE *s,
9305 Py_ssize_t length,
9306 char *output,
9307 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009308{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009309 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009310 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009311 enum PyUnicode_Kind kind;
9312 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009313
9314 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009315 PyErr_BadArgument();
9316 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009317 }
9318
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009319 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009320 if (unicode == NULL)
9321 return -1;
9322
Victor Stinner42bf7752011-11-21 22:52:58 +01009323 kind = PyUnicode_KIND(unicode);
9324 data = PyUnicode_DATA(unicode);
9325
Victor Stinnerb84d7232011-11-22 01:50:07 +01009326 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009327 PyObject *exc;
9328 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009329 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009330 Py_ssize_t startpos;
9331
9332 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009333
Benjamin Peterson29060642009-01-31 22:14:21 +00009334 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009335 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009336 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009337 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009338 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009339 decimal = Py_UNICODE_TODECIMAL(ch);
9340 if (decimal >= 0) {
9341 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009342 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009343 continue;
9344 }
9345 if (0 < ch && ch < 256) {
9346 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009347 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009348 continue;
9349 }
Victor Stinner6345be92011-11-25 20:09:01 +01009350
Victor Stinner42bf7752011-11-21 22:52:58 +01009351 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009352 exc = NULL;
9353 raise_encode_exception(&exc, "decimal", unicode,
9354 startpos, startpos+1,
9355 "invalid decimal Unicode string");
9356 Py_XDECREF(exc);
9357 Py_DECREF(unicode);
9358 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009359 }
9360 /* 0-terminate the output string */
9361 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009362 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009363 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009364}
9365
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366/* --- Helpers ------------------------------------------------------------ */
9367
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009368/* helper macro to fixup start/end slice values */
9369#define ADJUST_INDICES(start, end, len) \
9370 if (end > len) \
9371 end = len; \
9372 else if (end < 0) { \
9373 end += len; \
9374 if (end < 0) \
9375 end = 0; \
9376 } \
9377 if (start < 0) { \
9378 start += len; \
9379 if (start < 0) \
9380 start = 0; \
9381 }
9382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009384any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009386 Py_ssize_t end,
9387 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009389 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 void *buf1, *buf2;
9391 Py_ssize_t len1, len2, result;
9392
9393 kind1 = PyUnicode_KIND(s1);
9394 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009395 if (kind1 < kind2)
9396 return -1;
9397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 len1 = PyUnicode_GET_LENGTH(s1);
9399 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009400 ADJUST_INDICES(start, end, len1);
9401 if (end - start < len2)
9402 return -1;
9403
9404 buf1 = PyUnicode_DATA(s1);
9405 buf2 = PyUnicode_DATA(s2);
9406 if (len2 == 1) {
9407 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9408 result = findchar((const char *)buf1 + kind1*start,
9409 kind1, end - start, ch, direction);
9410 if (result == -1)
9411 return -1;
9412 else
9413 return start + result;
9414 }
9415
9416 if (kind2 != kind1) {
9417 buf2 = _PyUnicode_AsKind(s2, kind1);
9418 if (!buf2)
9419 return -2;
9420 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421
Victor Stinner794d5672011-10-10 03:21:36 +02009422 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009423 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009424 case PyUnicode_1BYTE_KIND:
9425 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9426 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9427 else
9428 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9429 break;
9430 case PyUnicode_2BYTE_KIND:
9431 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9432 break;
9433 case PyUnicode_4BYTE_KIND:
9434 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9435 break;
9436 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009437 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009438 }
9439 }
9440 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009441 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009442 case PyUnicode_1BYTE_KIND:
9443 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9444 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9445 else
9446 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9447 break;
9448 case PyUnicode_2BYTE_KIND:
9449 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9450 break;
9451 case PyUnicode_4BYTE_KIND:
9452 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9453 break;
9454 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009455 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009456 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 }
9458
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009459 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 PyMem_Free(buf2);
9461
9462 return result;
9463}
9464
9465Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009466_PyUnicode_InsertThousandsGrouping(
9467 PyObject *unicode, Py_ssize_t index,
9468 Py_ssize_t n_buffer,
9469 void *digits, Py_ssize_t n_digits,
9470 Py_ssize_t min_width,
9471 const char *grouping, PyObject *thousands_sep,
9472 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473{
Victor Stinner41a863c2012-02-24 00:37:51 +01009474 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009475 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009476 Py_ssize_t thousands_sep_len;
9477 Py_ssize_t len;
9478
9479 if (unicode != NULL) {
9480 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009481 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009482 }
9483 else {
9484 kind = PyUnicode_1BYTE_KIND;
9485 data = NULL;
9486 }
9487 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9488 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9489 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9490 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009491 if (thousands_sep_kind < kind) {
9492 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9493 if (!thousands_sep_data)
9494 return -1;
9495 }
9496 else {
9497 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9498 if (!data)
9499 return -1;
9500 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009501 }
9502
Benjamin Petersonead6b532011-12-20 17:23:42 -06009503 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009505 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009506 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009507 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009508 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009509 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009510 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009511 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009512 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009513 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009514 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009515 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009517 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009518 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009519 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009520 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009521 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009523 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009524 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009525 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009526 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009527 break;
9528 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009529 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009531 if (unicode != NULL && thousands_sep_kind != kind) {
9532 if (thousands_sep_kind < kind)
9533 PyMem_Free(thousands_sep_data);
9534 else
9535 PyMem_Free(data);
9536 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009537 if (unicode == NULL) {
9538 *maxchar = 127;
9539 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009540 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009541 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009542 }
9543 }
9544 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545}
9546
9547
Alexander Belopolsky40018472011-02-26 01:02:56 +00009548Py_ssize_t
9549PyUnicode_Count(PyObject *str,
9550 PyObject *substr,
9551 Py_ssize_t start,
9552 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009554 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009555 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 void *buf1 = NULL, *buf2 = NULL;
9557 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009558
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009559 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009560 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009561
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009562 kind1 = PyUnicode_KIND(str);
9563 kind2 = PyUnicode_KIND(substr);
9564 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009565 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009566
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009567 len1 = PyUnicode_GET_LENGTH(str);
9568 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009570 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009571 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009572
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009573 buf1 = PyUnicode_DATA(str);
9574 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009575 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009576 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009577 if (!buf2)
9578 goto onError;
9579 }
9580
9581 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009583 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009584 result = asciilib_count(
9585 ((Py_UCS1*)buf1) + start, end - start,
9586 buf2, len2, PY_SSIZE_T_MAX
9587 );
9588 else
9589 result = ucs1lib_count(
9590 ((Py_UCS1*)buf1) + start, end - start,
9591 buf2, len2, PY_SSIZE_T_MAX
9592 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 break;
9594 case PyUnicode_2BYTE_KIND:
9595 result = ucs2lib_count(
9596 ((Py_UCS2*)buf1) + start, end - start,
9597 buf2, len2, PY_SSIZE_T_MAX
9598 );
9599 break;
9600 case PyUnicode_4BYTE_KIND:
9601 result = ucs4lib_count(
9602 ((Py_UCS4*)buf1) + start, end - start,
9603 buf2, len2, PY_SSIZE_T_MAX
9604 );
9605 break;
9606 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009607 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009609
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009610 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611 PyMem_Free(buf2);
9612
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009614 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009615 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009616 PyMem_Free(buf2);
9617 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009618}
9619
Alexander Belopolsky40018472011-02-26 01:02:56 +00009620Py_ssize_t
9621PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009622 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009623 Py_ssize_t start,
9624 Py_ssize_t end,
9625 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009627 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009628 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009629
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009630 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631}
9632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009633Py_ssize_t
9634PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9635 Py_ssize_t start, Py_ssize_t end,
9636 int direction)
9637{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009639 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 if (PyUnicode_READY(str) == -1)
9641 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009642 len = PyUnicode_GET_LENGTH(str);
9643 ADJUST_INDICES(start, end, len);
9644 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009645 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009647 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9648 kind, end-start, ch, direction);
9649 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009650 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009651 else
9652 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653}
9654
Alexander Belopolsky40018472011-02-26 01:02:56 +00009655static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009656tailmatch(PyObject *self,
9657 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009658 Py_ssize_t start,
9659 Py_ssize_t end,
9660 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009661{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 int kind_self;
9663 int kind_sub;
9664 void *data_self;
9665 void *data_sub;
9666 Py_ssize_t offset;
9667 Py_ssize_t i;
9668 Py_ssize_t end_sub;
9669
9670 if (PyUnicode_READY(self) == -1 ||
9671 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009672 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009674 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9675 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009677 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009679 if (PyUnicode_GET_LENGTH(substring) == 0)
9680 return 1;
9681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 kind_self = PyUnicode_KIND(self);
9683 data_self = PyUnicode_DATA(self);
9684 kind_sub = PyUnicode_KIND(substring);
9685 data_sub = PyUnicode_DATA(substring);
9686 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9687
9688 if (direction > 0)
9689 offset = end;
9690 else
9691 offset = start;
9692
9693 if (PyUnicode_READ(kind_self, data_self, offset) ==
9694 PyUnicode_READ(kind_sub, data_sub, 0) &&
9695 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9696 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9697 /* If both are of the same kind, memcmp is sufficient */
9698 if (kind_self == kind_sub) {
9699 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009700 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 data_sub,
9702 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009703 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009704 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009705 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 else {
9707 /* We do not need to compare 0 and len(substring)-1 because
9708 the if statement above ensured already that they are equal
9709 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009710 for (i = 1; i < end_sub; ++i) {
9711 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9712 PyUnicode_READ(kind_sub, data_sub, i))
9713 return 0;
9714 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009715 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009716 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009717 }
9718
9719 return 0;
9720}
9721
Alexander Belopolsky40018472011-02-26 01:02:56 +00009722Py_ssize_t
9723PyUnicode_Tailmatch(PyObject *str,
9724 PyObject *substr,
9725 Py_ssize_t start,
9726 Py_ssize_t end,
9727 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009728{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009729 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009730 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009731
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009732 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009733}
9734
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009735static PyObject *
9736ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009737{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009738 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9739 char *resdata, *data = PyUnicode_DATA(self);
9740 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009741
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742 res = PyUnicode_New(len, 127);
9743 if (res == NULL)
9744 return NULL;
9745 resdata = PyUnicode_DATA(res);
9746 if (lower)
9747 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009748 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009749 _Py_bytes_upper(resdata, data, len);
9750 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009751}
9752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009754handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009756 Py_ssize_t j;
9757 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009758 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009759 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009760
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009761 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9762
9763 where ! is a negation and \p{xxx} is a character with property xxx.
9764 */
9765 for (j = i - 1; j >= 0; j--) {
9766 c = PyUnicode_READ(kind, data, j);
9767 if (!_PyUnicode_IsCaseIgnorable(c))
9768 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009769 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009770 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9771 if (final_sigma) {
9772 for (j = i + 1; j < length; j++) {
9773 c = PyUnicode_READ(kind, data, j);
9774 if (!_PyUnicode_IsCaseIgnorable(c))
9775 break;
9776 }
9777 final_sigma = j == length || !_PyUnicode_IsCased(c);
9778 }
9779 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009780}
9781
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009782static int
9783lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9784 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009785{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009786 /* Obscure special case. */
9787 if (c == 0x3A3) {
9788 mapped[0] = handle_capital_sigma(kind, data, length, i);
9789 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009791 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009792}
9793
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009794static Py_ssize_t
9795do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009796{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009797 Py_ssize_t i, k = 0;
9798 int n_res, j;
9799 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009800
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009801 c = PyUnicode_READ(kind, data, 0);
9802 n_res = _PyUnicode_ToUpperFull(c, mapped);
9803 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009804 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009805 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009807 for (i = 1; i < length; i++) {
9808 c = PyUnicode_READ(kind, data, i);
9809 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9810 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009811 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009812 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009813 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009814 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009815 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009816}
9817
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009818static Py_ssize_t
9819do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9820 Py_ssize_t i, k = 0;
9821
9822 for (i = 0; i < length; i++) {
9823 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9824 int n_res, j;
9825 if (Py_UNICODE_ISUPPER(c)) {
9826 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9827 }
9828 else if (Py_UNICODE_ISLOWER(c)) {
9829 n_res = _PyUnicode_ToUpperFull(c, mapped);
9830 }
9831 else {
9832 n_res = 1;
9833 mapped[0] = c;
9834 }
9835 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009836 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009837 res[k++] = mapped[j];
9838 }
9839 }
9840 return k;
9841}
9842
9843static Py_ssize_t
9844do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9845 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009847 Py_ssize_t i, k = 0;
9848
9849 for (i = 0; i < length; i++) {
9850 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9851 int n_res, j;
9852 if (lower)
9853 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9854 else
9855 n_res = _PyUnicode_ToUpperFull(c, mapped);
9856 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009857 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009858 res[k++] = mapped[j];
9859 }
9860 }
9861 return k;
9862}
9863
9864static Py_ssize_t
9865do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9866{
9867 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9868}
9869
9870static Py_ssize_t
9871do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9872{
9873 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9874}
9875
Benjamin Petersone51757f2012-01-12 21:10:29 -05009876static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009877do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9878{
9879 Py_ssize_t i, k = 0;
9880
9881 for (i = 0; i < length; i++) {
9882 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9883 Py_UCS4 mapped[3];
9884 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9885 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009886 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009887 res[k++] = mapped[j];
9888 }
9889 }
9890 return k;
9891}
9892
9893static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009894do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9895{
9896 Py_ssize_t i, k = 0;
9897 int previous_is_cased;
9898
9899 previous_is_cased = 0;
9900 for (i = 0; i < length; i++) {
9901 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9902 Py_UCS4 mapped[3];
9903 int n_res, j;
9904
9905 if (previous_is_cased)
9906 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9907 else
9908 n_res = _PyUnicode_ToTitleFull(c, mapped);
9909
9910 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009911 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009912 res[k++] = mapped[j];
9913 }
9914
9915 previous_is_cased = _PyUnicode_IsCased(c);
9916 }
9917 return k;
9918}
9919
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009920static PyObject *
9921case_operation(PyObject *self,
9922 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9923{
9924 PyObject *res = NULL;
9925 Py_ssize_t length, newlength = 0;
9926 int kind, outkind;
9927 void *data, *outdata;
9928 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9929
Benjamin Petersoneea48462012-01-16 14:28:50 -05009930 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009931
9932 kind = PyUnicode_KIND(self);
9933 data = PyUnicode_DATA(self);
9934 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009935 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009936 PyErr_SetString(PyExc_OverflowError, "string is too long");
9937 return NULL;
9938 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009939 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009940 if (tmp == NULL)
9941 return PyErr_NoMemory();
9942 newlength = perform(kind, data, length, tmp, &maxchar);
9943 res = PyUnicode_New(newlength, maxchar);
9944 if (res == NULL)
9945 goto leave;
9946 tmpend = tmp + newlength;
9947 outdata = PyUnicode_DATA(res);
9948 outkind = PyUnicode_KIND(res);
9949 switch (outkind) {
9950 case PyUnicode_1BYTE_KIND:
9951 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9952 break;
9953 case PyUnicode_2BYTE_KIND:
9954 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9955 break;
9956 case PyUnicode_4BYTE_KIND:
9957 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9958 break;
9959 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009960 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009961 }
9962 leave:
9963 PyMem_FREE(tmp);
9964 return res;
9965}
9966
Tim Peters8ce9f162004-08-27 01:49:32 +00009967PyObject *
9968PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009969{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009970 PyObject *res;
9971 PyObject *fseq;
9972 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009973 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009974
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009975 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009976 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009977 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009978 }
9979
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009980 /* NOTE: the following code can't call back into Python code,
9981 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009982 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009983
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009984 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009985 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009986 res = _PyUnicode_JoinArray(separator, items, seqlen);
9987 Py_DECREF(fseq);
9988 return res;
9989}
9990
9991PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009992_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009993{
9994 PyObject *res = NULL; /* the result */
9995 PyObject *sep = NULL;
9996 Py_ssize_t seplen;
9997 PyObject *item;
9998 Py_ssize_t sz, i, res_offset;
9999 Py_UCS4 maxchar;
10000 Py_UCS4 item_maxchar;
10001 int use_memcpy;
10002 unsigned char *res_data = NULL, *sep_data = NULL;
10003 PyObject *last_obj;
10004 unsigned int kind = 0;
10005
Tim Peters05eba1f2004-08-27 21:32:02 +000010006 /* If empty sequence, return u"". */
10007 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010008 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +000010009 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010010
Tim Peters05eba1f2004-08-27 21:32:02 +000010011 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010012 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +020010013 if (seqlen == 1) {
10014 if (PyUnicode_CheckExact(items[0])) {
10015 res = items[0];
10016 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +020010017 return res;
10018 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010019 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +020010020 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +000010021 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010022 else {
Victor Stinneracf47b82011-10-06 12:32:37 +020010023 /* Set up sep and seplen */
10024 if (separator == NULL) {
10025 /* fall back to a blank space separator */
10026 sep = PyUnicode_FromOrdinal(' ');
10027 if (!sep)
10028 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010029 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010030 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010031 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010032 else {
10033 if (!PyUnicode_Check(separator)) {
10034 PyErr_Format(PyExc_TypeError,
10035 "separator: expected str instance,"
10036 " %.80s found",
10037 Py_TYPE(separator)->tp_name);
10038 goto onError;
10039 }
10040 if (PyUnicode_READY(separator))
10041 goto onError;
10042 sep = separator;
10043 seplen = PyUnicode_GET_LENGTH(separator);
10044 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10045 /* inc refcount to keep this code path symmetric with the
10046 above case of a blank separator */
10047 Py_INCREF(sep);
10048 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010049 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010050 }
10051
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010052 /* There are at least two things to join, or else we have a subclass
10053 * of str in the sequence.
10054 * Do a pre-pass to figure out the total amount of space we'll
10055 * need (sz), and see whether all argument are strings.
10056 */
10057 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010058#ifdef Py_DEBUG
10059 use_memcpy = 0;
10060#else
10061 use_memcpy = 1;
10062#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010063 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010064 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010065 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010066 if (!PyUnicode_Check(item)) {
10067 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010068 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010069 " %.80s found",
10070 i, Py_TYPE(item)->tp_name);
10071 goto onError;
10072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 if (PyUnicode_READY(item) == -1)
10074 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010075 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010077 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010078 if (i != 0) {
10079 add_sz += seplen;
10080 }
10081 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010082 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010083 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010084 goto onError;
10085 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010086 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010087 if (use_memcpy && last_obj != NULL) {
10088 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10089 use_memcpy = 0;
10090 }
10091 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010092 }
Tim Petersced69f82003-09-16 20:30:58 +000010093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010095 if (res == NULL)
10096 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010097
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010098 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010099#ifdef Py_DEBUG
10100 use_memcpy = 0;
10101#else
10102 if (use_memcpy) {
10103 res_data = PyUnicode_1BYTE_DATA(res);
10104 kind = PyUnicode_KIND(res);
10105 if (seplen != 0)
10106 sep_data = PyUnicode_1BYTE_DATA(sep);
10107 }
10108#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010109 if (use_memcpy) {
10110 for (i = 0; i < seqlen; ++i) {
10111 Py_ssize_t itemlen;
10112 item = items[i];
10113
10114 /* Copy item, and maybe the separator. */
10115 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010116 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010117 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010118 kind * seplen);
10119 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010120 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010121
10122 itemlen = PyUnicode_GET_LENGTH(item);
10123 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010124 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010125 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010126 kind * itemlen);
10127 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010128 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010129 }
10130 assert(res_data == PyUnicode_1BYTE_DATA(res)
10131 + kind * PyUnicode_GET_LENGTH(res));
10132 }
10133 else {
10134 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10135 Py_ssize_t itemlen;
10136 item = items[i];
10137
10138 /* Copy item, and maybe the separator. */
10139 if (i && seplen != 0) {
10140 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10141 res_offset += seplen;
10142 }
10143
10144 itemlen = PyUnicode_GET_LENGTH(item);
10145 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010146 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010147 res_offset += itemlen;
10148 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010149 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010150 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010151 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010154 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156
Benjamin Peterson29060642009-01-31 22:14:21 +000010157 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010159 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010160 return NULL;
10161}
10162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163#define FILL(kind, data, value, start, length) \
10164 do { \
10165 Py_ssize_t i_ = 0; \
10166 assert(kind != PyUnicode_WCHAR_KIND); \
10167 switch ((kind)) { \
10168 case PyUnicode_1BYTE_KIND: { \
10169 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010170 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 break; \
10172 } \
10173 case PyUnicode_2BYTE_KIND: { \
10174 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10175 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10176 break; \
10177 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010178 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10180 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10181 break; \
10182 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010183 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 } \
10185 } while (0)
10186
Victor Stinnerd3f08822012-05-29 12:57:52 +020010187void
10188_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10189 Py_UCS4 fill_char)
10190{
10191 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10192 const void *data = PyUnicode_DATA(unicode);
10193 assert(PyUnicode_IS_READY(unicode));
10194 assert(unicode_modifiable(unicode));
10195 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10196 assert(start >= 0);
10197 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10198 FILL(kind, data, fill_char, start, length);
10199}
10200
Victor Stinner3fe55312012-01-04 00:33:50 +010010201Py_ssize_t
10202PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10203 Py_UCS4 fill_char)
10204{
10205 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010206
10207 if (!PyUnicode_Check(unicode)) {
10208 PyErr_BadInternalCall();
10209 return -1;
10210 }
10211 if (PyUnicode_READY(unicode) == -1)
10212 return -1;
10213 if (unicode_check_modifiable(unicode))
10214 return -1;
10215
Victor Stinnerd3f08822012-05-29 12:57:52 +020010216 if (start < 0) {
10217 PyErr_SetString(PyExc_IndexError, "string index out of range");
10218 return -1;
10219 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010220 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10221 PyErr_SetString(PyExc_ValueError,
10222 "fill character is bigger than "
10223 "the string maximum character");
10224 return -1;
10225 }
10226
10227 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10228 length = Py_MIN(maxlen, length);
10229 if (length <= 0)
10230 return 0;
10231
Victor Stinnerd3f08822012-05-29 12:57:52 +020010232 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010233 return length;
10234}
10235
Victor Stinner9310abb2011-10-05 00:59:23 +020010236static PyObject *
10237pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010238 Py_ssize_t left,
10239 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 PyObject *u;
10243 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010244 int kind;
10245 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010246
10247 if (left < 0)
10248 left = 0;
10249 if (right < 0)
10250 right = 0;
10251
Victor Stinnerc4b49542011-12-11 22:44:26 +010010252 if (left == 0 && right == 0)
10253 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10256 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010257 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10258 return NULL;
10259 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010261 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010263 if (!u)
10264 return NULL;
10265
10266 kind = PyUnicode_KIND(u);
10267 data = PyUnicode_DATA(u);
10268 if (left)
10269 FILL(kind, data, fill, 0, left);
10270 if (right)
10271 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010272 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010273 assert(_PyUnicode_CheckConsistency(u, 1));
10274 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010275}
10276
Alexander Belopolsky40018472011-02-26 01:02:56 +000010277PyObject *
10278PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010280 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010282 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010283 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284
Benjamin Petersonead6b532011-12-20 17:23:42 -060010285 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010287 if (PyUnicode_IS_ASCII(string))
10288 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010289 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010290 PyUnicode_GET_LENGTH(string), keepends);
10291 else
10292 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010293 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010294 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 break;
10296 case PyUnicode_2BYTE_KIND:
10297 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010298 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 PyUnicode_GET_LENGTH(string), keepends);
10300 break;
10301 case PyUnicode_4BYTE_KIND:
10302 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010303 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 PyUnicode_GET_LENGTH(string), keepends);
10305 break;
10306 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010307 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310}
10311
Alexander Belopolsky40018472011-02-26 01:02:56 +000010312static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010313split(PyObject *self,
10314 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010315 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010317 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 void *buf1, *buf2;
10319 Py_ssize_t len1, len2;
10320 PyObject* out;
10321
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010323 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 if (PyUnicode_READY(self) == -1)
10326 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010329 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010331 if (PyUnicode_IS_ASCII(self))
10332 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010333 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010334 PyUnicode_GET_LENGTH(self), maxcount
10335 );
10336 else
10337 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010338 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010339 PyUnicode_GET_LENGTH(self), maxcount
10340 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 case PyUnicode_2BYTE_KIND:
10342 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010343 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 PyUnicode_GET_LENGTH(self), maxcount
10345 );
10346 case PyUnicode_4BYTE_KIND:
10347 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010348 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 PyUnicode_GET_LENGTH(self), maxcount
10350 );
10351 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010352 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 }
10354
10355 if (PyUnicode_READY(substring) == -1)
10356 return NULL;
10357
10358 kind1 = PyUnicode_KIND(self);
10359 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 len1 = PyUnicode_GET_LENGTH(self);
10361 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010362 if (kind1 < kind2 || len1 < len2) {
10363 out = PyList_New(1);
10364 if (out == NULL)
10365 return NULL;
10366 Py_INCREF(self);
10367 PyList_SET_ITEM(out, 0, self);
10368 return out;
10369 }
10370 buf1 = PyUnicode_DATA(self);
10371 buf2 = PyUnicode_DATA(substring);
10372 if (kind2 != kind1) {
10373 buf2 = _PyUnicode_AsKind(substring, kind1);
10374 if (!buf2)
10375 return NULL;
10376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010378 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010380 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10381 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010382 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010383 else
10384 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010385 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 break;
10387 case PyUnicode_2BYTE_KIND:
10388 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010389 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 break;
10391 case PyUnicode_4BYTE_KIND:
10392 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010393 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 break;
10395 default:
10396 out = NULL;
10397 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010398 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 PyMem_Free(buf2);
10400 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401}
10402
Alexander Belopolsky40018472011-02-26 01:02:56 +000010403static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010404rsplit(PyObject *self,
10405 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010406 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010407{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010408 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 void *buf1, *buf2;
10410 Py_ssize_t len1, len2;
10411 PyObject* out;
10412
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010413 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010414 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 if (PyUnicode_READY(self) == -1)
10417 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010420 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010422 if (PyUnicode_IS_ASCII(self))
10423 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010424 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010425 PyUnicode_GET_LENGTH(self), maxcount
10426 );
10427 else
10428 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010429 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010430 PyUnicode_GET_LENGTH(self), maxcount
10431 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 case PyUnicode_2BYTE_KIND:
10433 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010434 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 PyUnicode_GET_LENGTH(self), maxcount
10436 );
10437 case PyUnicode_4BYTE_KIND:
10438 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010439 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 PyUnicode_GET_LENGTH(self), maxcount
10441 );
10442 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010443 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 }
10445
10446 if (PyUnicode_READY(substring) == -1)
10447 return NULL;
10448
10449 kind1 = PyUnicode_KIND(self);
10450 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 len1 = PyUnicode_GET_LENGTH(self);
10452 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010453 if (kind1 < kind2 || len1 < len2) {
10454 out = PyList_New(1);
10455 if (out == NULL)
10456 return NULL;
10457 Py_INCREF(self);
10458 PyList_SET_ITEM(out, 0, self);
10459 return out;
10460 }
10461 buf1 = PyUnicode_DATA(self);
10462 buf2 = PyUnicode_DATA(substring);
10463 if (kind2 != kind1) {
10464 buf2 = _PyUnicode_AsKind(substring, kind1);
10465 if (!buf2)
10466 return NULL;
10467 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010469 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010471 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10472 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010473 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010474 else
10475 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010476 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 break;
10478 case PyUnicode_2BYTE_KIND:
10479 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010480 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 break;
10482 case PyUnicode_4BYTE_KIND:
10483 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010484 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 break;
10486 default:
10487 out = NULL;
10488 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010489 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 PyMem_Free(buf2);
10491 return out;
10492}
10493
10494static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010495anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10496 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010498 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010500 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10501 return asciilib_find(buf1, len1, buf2, len2, offset);
10502 else
10503 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504 case PyUnicode_2BYTE_KIND:
10505 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10506 case PyUnicode_4BYTE_KIND:
10507 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10508 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010509 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510}
10511
10512static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010513anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10514 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010516 switch (kind) {
10517 case PyUnicode_1BYTE_KIND:
10518 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10519 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10520 else
10521 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10522 case PyUnicode_2BYTE_KIND:
10523 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10524 case PyUnicode_4BYTE_KIND:
10525 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10526 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010527 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010528}
10529
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010530static void
10531replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10532 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10533{
10534 int kind = PyUnicode_KIND(u);
10535 void *data = PyUnicode_DATA(u);
10536 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10537 if (kind == PyUnicode_1BYTE_KIND) {
10538 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10539 (Py_UCS1 *)data + len,
10540 u1, u2, maxcount);
10541 }
10542 else if (kind == PyUnicode_2BYTE_KIND) {
10543 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10544 (Py_UCS2 *)data + len,
10545 u1, u2, maxcount);
10546 }
10547 else {
10548 assert(kind == PyUnicode_4BYTE_KIND);
10549 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10550 (Py_UCS4 *)data + len,
10551 u1, u2, maxcount);
10552 }
10553}
10554
Alexander Belopolsky40018472011-02-26 01:02:56 +000010555static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556replace(PyObject *self, PyObject *str1,
10557 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 PyObject *u;
10560 char *sbuf = PyUnicode_DATA(self);
10561 char *buf1 = PyUnicode_DATA(str1);
10562 char *buf2 = PyUnicode_DATA(str2);
10563 int srelease = 0, release1 = 0, release2 = 0;
10564 int skind = PyUnicode_KIND(self);
10565 int kind1 = PyUnicode_KIND(str1);
10566 int kind2 = PyUnicode_KIND(str2);
10567 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10568 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10569 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010571 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572
10573 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010574 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010576 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010577
Victor Stinner59de0ee2011-10-07 10:01:28 +020010578 if (str1 == str2)
10579 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010582 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10583 if (maxchar < maxchar_str1)
10584 /* substring too wide to be present */
10585 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010586 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10587 /* Replacing str1 with str2 may cause a maxchar reduction in the
10588 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010589 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010590 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010595 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010598 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010599 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010600
Victor Stinner69ed0f42013-04-09 21:48:24 +020010601 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010602 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010603 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010605 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010609
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010610 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10611 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010612 }
10613 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 int rkind = skind;
10615 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010616 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010617
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 if (kind1 < rkind) {
10619 /* widen substring */
10620 buf1 = _PyUnicode_AsKind(str1, rkind);
10621 if (!buf1) goto error;
10622 release1 = 1;
10623 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010624 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625 if (i < 0)
10626 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 if (rkind > kind2) {
10628 /* widen replacement */
10629 buf2 = _PyUnicode_AsKind(str2, rkind);
10630 if (!buf2) goto error;
10631 release2 = 1;
10632 }
10633 else if (rkind < kind2) {
10634 /* widen self and buf1 */
10635 rkind = kind2;
10636 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010637 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 sbuf = _PyUnicode_AsKind(self, rkind);
10639 if (!sbuf) goto error;
10640 srelease = 1;
10641 buf1 = _PyUnicode_AsKind(str1, rkind);
10642 if (!buf1) goto error;
10643 release1 = 1;
10644 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010645 u = PyUnicode_New(slen, maxchar);
10646 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010648 assert(PyUnicode_KIND(u) == rkind);
10649 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010650
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010651 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010652 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010653 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010655 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010657
10658 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010659 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010660 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010661 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010662 if (i == -1)
10663 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010664 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010666 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010668 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010669 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010670 }
10671 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010673 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010674 int rkind = skind;
10675 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010678 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 buf1 = _PyUnicode_AsKind(str1, rkind);
10680 if (!buf1) goto error;
10681 release1 = 1;
10682 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010683 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010684 if (n == 0)
10685 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010686 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010687 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 buf2 = _PyUnicode_AsKind(str2, rkind);
10689 if (!buf2) goto error;
10690 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010693 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 rkind = kind2;
10695 sbuf = _PyUnicode_AsKind(self, rkind);
10696 if (!sbuf) goto error;
10697 srelease = 1;
10698 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010699 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 buf1 = _PyUnicode_AsKind(str1, rkind);
10701 if (!buf1) goto error;
10702 release1 = 1;
10703 }
10704 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10705 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010706 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 PyErr_SetString(PyExc_OverflowError,
10708 "replace string is too long");
10709 goto error;
10710 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010711 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010712 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010713 _Py_INCREF_UNICODE_EMPTY();
10714 if (!unicode_empty)
10715 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010716 u = unicode_empty;
10717 goto done;
10718 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010719 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 PyErr_SetString(PyExc_OverflowError,
10721 "replace string is too long");
10722 goto error;
10723 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010724 u = PyUnicode_New(new_size, maxchar);
10725 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010727 assert(PyUnicode_KIND(u) == rkind);
10728 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010729 ires = i = 0;
10730 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010731 while (n-- > 0) {
10732 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010733 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010734 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010735 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010736 if (j == -1)
10737 break;
10738 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010739 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010740 memcpy(res + rkind * ires,
10741 sbuf + rkind * i,
10742 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010744 }
10745 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010746 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010747 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010749 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010751 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010752 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010753 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010754 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010755 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010756 memcpy(res + rkind * ires,
10757 sbuf + rkind * i,
10758 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010759 }
10760 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010761 /* interleave */
10762 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010763 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010765 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010767 if (--n <= 0)
10768 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010769 memcpy(res + rkind * ires,
10770 sbuf + rkind * i,
10771 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 ires++;
10773 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010774 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010775 memcpy(res + rkind * ires,
10776 sbuf + rkind * i,
10777 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010778 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010779 }
10780
10781 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010782 unicode_adjust_maxchar(&u);
10783 if (u == NULL)
10784 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010786
10787 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 if (srelease)
10789 PyMem_FREE(sbuf);
10790 if (release1)
10791 PyMem_FREE(buf1);
10792 if (release2)
10793 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010794 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010796
Benjamin Peterson29060642009-01-31 22:14:21 +000010797 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010798 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 if (srelease)
10800 PyMem_FREE(sbuf);
10801 if (release1)
10802 PyMem_FREE(buf1);
10803 if (release2)
10804 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010805 return unicode_result_unchanged(self);
10806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 error:
10808 if (srelease && sbuf)
10809 PyMem_FREE(sbuf);
10810 if (release1 && buf1)
10811 PyMem_FREE(buf1);
10812 if (release2 && buf2)
10813 PyMem_FREE(buf2);
10814 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815}
10816
10817/* --- Unicode Object Methods --------------------------------------------- */
10818
INADA Naoki3ae20562017-01-16 20:41:20 +090010819/*[clinic input]
10820str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821
INADA Naoki3ae20562017-01-16 20:41:20 +090010822Return a version of the string where each word is titlecased.
10823
10824More specifically, words start with uppercased characters and all remaining
10825cased characters have lower case.
10826[clinic start generated code]*/
10827
10828static PyObject *
10829unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010830/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010831{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010832 if (PyUnicode_READY(self) == -1)
10833 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010834 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835}
10836
INADA Naoki3ae20562017-01-16 20:41:20 +090010837/*[clinic input]
10838str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839
INADA Naoki3ae20562017-01-16 20:41:20 +090010840Return a capitalized version of the string.
10841
10842More specifically, make the first character have upper case and the rest lower
10843case.
10844[clinic start generated code]*/
10845
10846static PyObject *
10847unicode_capitalize_impl(PyObject *self)
10848/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010850 if (PyUnicode_READY(self) == -1)
10851 return NULL;
10852 if (PyUnicode_GET_LENGTH(self) == 0)
10853 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010854 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855}
10856
INADA Naoki3ae20562017-01-16 20:41:20 +090010857/*[clinic input]
10858str.casefold as unicode_casefold
10859
10860Return a version of the string suitable for caseless comparisons.
10861[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010862
10863static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010864unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010865/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010866{
10867 if (PyUnicode_READY(self) == -1)
10868 return NULL;
10869 if (PyUnicode_IS_ASCII(self))
10870 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010871 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010872}
10873
10874
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010875/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010876
10877static int
10878convert_uc(PyObject *obj, void *addr)
10879{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010880 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010881
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010882 if (!PyUnicode_Check(obj)) {
10883 PyErr_Format(PyExc_TypeError,
10884 "The fill character must be a unicode character, "
10885 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010886 return 0;
10887 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010888 if (PyUnicode_READY(obj) < 0)
10889 return 0;
10890 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010891 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010892 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010893 return 0;
10894 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010895 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010896 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010897}
10898
INADA Naoki3ae20562017-01-16 20:41:20 +090010899/*[clinic input]
10900str.center as unicode_center
10901
10902 width: Py_ssize_t
10903 fillchar: Py_UCS4 = ' '
10904 /
10905
10906Return a centered string of length width.
10907
10908Padding is done using the specified fill character (default is a space).
10909[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910
10911static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010912unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10913/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010914{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010915 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
Benjamin Petersonbac79492012-01-14 13:34:47 -050010917 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918 return NULL;
10919
Victor Stinnerc4b49542011-12-11 22:44:26 +010010920 if (PyUnicode_GET_LENGTH(self) >= width)
10921 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922
Victor Stinnerc4b49542011-12-11 22:44:26 +010010923 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924 left = marg / 2 + (marg & width & 1);
10925
Victor Stinner9310abb2011-10-05 00:59:23 +020010926 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927}
10928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929/* This function assumes that str1 and str2 are readied by the caller. */
10930
Marc-André Lemburge5034372000-08-08 08:04:29 +000010931static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010932unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010933{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010934#define COMPARE(TYPE1, TYPE2) \
10935 do { \
10936 TYPE1* p1 = (TYPE1 *)data1; \
10937 TYPE2* p2 = (TYPE2 *)data2; \
10938 TYPE1* end = p1 + len; \
10939 Py_UCS4 c1, c2; \
10940 for (; p1 != end; p1++, p2++) { \
10941 c1 = *p1; \
10942 c2 = *p2; \
10943 if (c1 != c2) \
10944 return (c1 < c2) ? -1 : 1; \
10945 } \
10946 } \
10947 while (0)
10948
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949 int kind1, kind2;
10950 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010951 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953 kind1 = PyUnicode_KIND(str1);
10954 kind2 = PyUnicode_KIND(str2);
10955 data1 = PyUnicode_DATA(str1);
10956 data2 = PyUnicode_DATA(str2);
10957 len1 = PyUnicode_GET_LENGTH(str1);
10958 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010959 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010960
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010961 switch(kind1) {
10962 case PyUnicode_1BYTE_KIND:
10963 {
10964 switch(kind2) {
10965 case PyUnicode_1BYTE_KIND:
10966 {
10967 int cmp = memcmp(data1, data2, len);
10968 /* normalize result of memcmp() into the range [-1; 1] */
10969 if (cmp < 0)
10970 return -1;
10971 if (cmp > 0)
10972 return 1;
10973 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010974 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010975 case PyUnicode_2BYTE_KIND:
10976 COMPARE(Py_UCS1, Py_UCS2);
10977 break;
10978 case PyUnicode_4BYTE_KIND:
10979 COMPARE(Py_UCS1, Py_UCS4);
10980 break;
10981 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010982 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010983 }
10984 break;
10985 }
10986 case PyUnicode_2BYTE_KIND:
10987 {
10988 switch(kind2) {
10989 case PyUnicode_1BYTE_KIND:
10990 COMPARE(Py_UCS2, Py_UCS1);
10991 break;
10992 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010993 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010994 COMPARE(Py_UCS2, Py_UCS2);
10995 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010996 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010997 case PyUnicode_4BYTE_KIND:
10998 COMPARE(Py_UCS2, Py_UCS4);
10999 break;
11000 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011001 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011002 }
11003 break;
11004 }
11005 case PyUnicode_4BYTE_KIND:
11006 {
11007 switch(kind2) {
11008 case PyUnicode_1BYTE_KIND:
11009 COMPARE(Py_UCS4, Py_UCS1);
11010 break;
11011 case PyUnicode_2BYTE_KIND:
11012 COMPARE(Py_UCS4, Py_UCS2);
11013 break;
11014 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020011015 {
11016#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11017 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11018 /* normalize result of wmemcmp() into the range [-1; 1] */
11019 if (cmp < 0)
11020 return -1;
11021 if (cmp > 0)
11022 return 1;
11023#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011024 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020011025#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011026 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020011027 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011028 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011029 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011030 }
11031 break;
11032 }
11033 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011034 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000011035 }
11036
Victor Stinner770e19e2012-10-04 22:59:45 +020011037 if (len1 == len2)
11038 return 0;
11039 if (len1 < len2)
11040 return -1;
11041 else
11042 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011043
11044#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011045}
11046
Benjamin Peterson621b4302016-09-09 13:54:34 -070011047static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011048unicode_compare_eq(PyObject *str1, PyObject *str2)
11049{
11050 int kind;
11051 void *data1, *data2;
11052 Py_ssize_t len;
11053 int cmp;
11054
Victor Stinnere5567ad2012-10-23 02:48:49 +020011055 len = PyUnicode_GET_LENGTH(str1);
11056 if (PyUnicode_GET_LENGTH(str2) != len)
11057 return 0;
11058 kind = PyUnicode_KIND(str1);
11059 if (PyUnicode_KIND(str2) != kind)
11060 return 0;
11061 data1 = PyUnicode_DATA(str1);
11062 data2 = PyUnicode_DATA(str2);
11063
11064 cmp = memcmp(data1, data2, len * kind);
11065 return (cmp == 0);
11066}
11067
11068
Alexander Belopolsky40018472011-02-26 01:02:56 +000011069int
11070PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011072 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11073 if (PyUnicode_READY(left) == -1 ||
11074 PyUnicode_READY(right) == -1)
11075 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011076
11077 /* a string is equal to itself */
11078 if (left == right)
11079 return 0;
11080
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011081 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011083 PyErr_Format(PyExc_TypeError,
11084 "Can't compare %.100s and %.100s",
11085 left->ob_type->tp_name,
11086 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087 return -1;
11088}
11089
Martin v. Löwis5b222132007-06-10 09:51:05 +000011090int
11091PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011093 Py_ssize_t i;
11094 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011095 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011096 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011097
Victor Stinner910337b2011-10-03 03:20:16 +020011098 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011099 if (!PyUnicode_IS_READY(uni)) {
11100 const wchar_t *ws = _PyUnicode_WSTR(uni);
11101 /* Compare Unicode string and source character set string */
11102 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11103 if (chr != ustr[i])
11104 return (chr < ustr[i]) ? -1 : 1;
11105 }
11106 /* This check keeps Python strings that end in '\0' from comparing equal
11107 to C strings identical up to that point. */
11108 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11109 return 1; /* uni is longer */
11110 if (ustr[i])
11111 return -1; /* str is longer */
11112 return 0;
11113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011115 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011116 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011117 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011118 size_t len, len2 = strlen(str);
11119 int cmp;
11120
11121 len = Py_MIN(len1, len2);
11122 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011123 if (cmp != 0) {
11124 if (cmp < 0)
11125 return -1;
11126 else
11127 return 1;
11128 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011129 if (len1 > len2)
11130 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011131 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011132 return -1; /* str is longer */
11133 return 0;
11134 }
11135 else {
11136 void *data = PyUnicode_DATA(uni);
11137 /* Compare Unicode string and source character set string */
11138 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011139 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011140 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11141 /* This check keeps Python strings that end in '\0' from comparing equal
11142 to C strings identical up to that point. */
11143 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11144 return 1; /* uni is longer */
11145 if (str[i])
11146 return -1; /* str is longer */
11147 return 0;
11148 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011149}
11150
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011151static int
11152non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11153{
11154 size_t i, len;
11155 const wchar_t *p;
11156 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11157 if (strlen(str) != len)
11158 return 0;
11159 p = _PyUnicode_WSTR(unicode);
11160 assert(p);
11161 for (i = 0; i < len; i++) {
11162 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011163 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011164 return 0;
11165 }
11166 return 1;
11167}
11168
11169int
11170_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11171{
11172 size_t len;
11173 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011174 assert(str);
11175#ifndef NDEBUG
11176 for (const char *p = str; *p; p++) {
11177 assert((unsigned char)*p < 128);
11178 }
11179#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011180 if (PyUnicode_READY(unicode) == -1) {
11181 /* Memory error or bad data */
11182 PyErr_Clear();
11183 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11184 }
11185 if (!PyUnicode_IS_ASCII(unicode))
11186 return 0;
11187 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11188 return strlen(str) == len &&
11189 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11190}
11191
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011192int
11193_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11194{
11195 PyObject *right_uni;
11196 Py_hash_t hash;
11197
11198 assert(_PyUnicode_CHECK(left));
11199 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011200#ifndef NDEBUG
11201 for (const char *p = right->string; *p; p++) {
11202 assert((unsigned char)*p < 128);
11203 }
11204#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011205
11206 if (PyUnicode_READY(left) == -1) {
11207 /* memory error or bad data */
11208 PyErr_Clear();
11209 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11210 }
11211
11212 if (!PyUnicode_IS_ASCII(left))
11213 return 0;
11214
11215 right_uni = _PyUnicode_FromId(right); /* borrowed */
11216 if (right_uni == NULL) {
11217 /* memory error or bad data */
11218 PyErr_Clear();
11219 return _PyUnicode_EqualToASCIIString(left, right->string);
11220 }
11221
11222 if (left == right_uni)
11223 return 1;
11224
11225 if (PyUnicode_CHECK_INTERNED(left))
11226 return 0;
11227
11228 assert(_PyUnicode_HASH(right_uni) != 1);
11229 hash = _PyUnicode_HASH(left);
11230 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11231 return 0;
11232
11233 return unicode_compare_eq(left, right_uni);
11234}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011235
Alexander Belopolsky40018472011-02-26 01:02:56 +000011236PyObject *
11237PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011238{
11239 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011240
Victor Stinnere5567ad2012-10-23 02:48:49 +020011241 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11242 Py_RETURN_NOTIMPLEMENTED;
11243
11244 if (PyUnicode_READY(left) == -1 ||
11245 PyUnicode_READY(right) == -1)
11246 return NULL;
11247
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011248 if (left == right) {
11249 switch (op) {
11250 case Py_EQ:
11251 case Py_LE:
11252 case Py_GE:
11253 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011254 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011255 case Py_NE:
11256 case Py_LT:
11257 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011258 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011259 default:
11260 PyErr_BadArgument();
11261 return NULL;
11262 }
11263 }
11264 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011265 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011266 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011267 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011268 }
11269 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011270 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011271 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011272 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011273}
11274
Alexander Belopolsky40018472011-02-26 01:02:56 +000011275int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011276_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11277{
11278 return unicode_eq(aa, bb);
11279}
11280
11281int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011282PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011283{
Victor Stinner77282cb2013-04-14 19:22:47 +020011284 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285 void *buf1, *buf2;
11286 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011287 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011288
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011289 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011291 "'in <string>' requires string as left operand, not %.100s",
11292 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011293 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011294 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011295 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011296 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011297 if (ensure_unicode(str) < 0)
11298 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011299
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011301 kind2 = PyUnicode_KIND(substr);
11302 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011303 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011305 len2 = PyUnicode_GET_LENGTH(substr);
11306 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011307 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011308 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011309 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011310 if (len2 == 1) {
11311 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11312 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011313 return result;
11314 }
11315 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011316 buf2 = _PyUnicode_AsKind(substr, kind1);
11317 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011318 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320
Victor Stinner77282cb2013-04-14 19:22:47 +020011321 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011322 case PyUnicode_1BYTE_KIND:
11323 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11324 break;
11325 case PyUnicode_2BYTE_KIND:
11326 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11327 break;
11328 case PyUnicode_4BYTE_KIND:
11329 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11330 break;
11331 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011332 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011334
Victor Stinner77282cb2013-04-14 19:22:47 +020011335 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 PyMem_Free(buf2);
11337
Guido van Rossum403d68b2000-03-13 15:55:09 +000011338 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011339}
11340
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341/* Concat to string or Unicode object giving a new Unicode object. */
11342
Alexander Belopolsky40018472011-02-26 01:02:56 +000011343PyObject *
11344PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011346 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011347 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011348 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011350 if (ensure_unicode(left) < 0)
11351 return NULL;
11352
11353 if (!PyUnicode_Check(right)) {
11354 PyErr_Format(PyExc_TypeError,
11355 "can only concatenate str (not \"%.200s\") to str",
11356 right->ob_type->tp_name);
11357 return NULL;
11358 }
11359 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011360 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361
11362 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011363 if (left == unicode_empty)
11364 return PyUnicode_FromObject(right);
11365 if (right == unicode_empty)
11366 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011368 left_len = PyUnicode_GET_LENGTH(left);
11369 right_len = PyUnicode_GET_LENGTH(right);
11370 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011371 PyErr_SetString(PyExc_OverflowError,
11372 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011373 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011374 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011375 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011376
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011377 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11378 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011379 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011382 result = PyUnicode_New(new_len, maxchar);
11383 if (result == NULL)
11384 return NULL;
11385 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11386 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11387 assert(_PyUnicode_CheckConsistency(result, 1));
11388 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389}
11390
Walter Dörwald1ab83302007-05-18 17:15:44 +000011391void
Victor Stinner23e56682011-10-03 03:54:37 +020011392PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011393{
Victor Stinner23e56682011-10-03 03:54:37 +020011394 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011395 Py_UCS4 maxchar, maxchar2;
11396 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011397
11398 if (p_left == NULL) {
11399 if (!PyErr_Occurred())
11400 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011401 return;
11402 }
Victor Stinner23e56682011-10-03 03:54:37 +020011403 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011404 if (right == NULL || left == NULL
11405 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011406 if (!PyErr_Occurred())
11407 PyErr_BadInternalCall();
11408 goto error;
11409 }
11410
Benjamin Petersonbac79492012-01-14 13:34:47 -050011411 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011412 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011413 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011414 goto error;
11415
Victor Stinner488fa492011-12-12 00:01:39 +010011416 /* Shortcuts */
11417 if (left == unicode_empty) {
11418 Py_DECREF(left);
11419 Py_INCREF(right);
11420 *p_left = right;
11421 return;
11422 }
11423 if (right == unicode_empty)
11424 return;
11425
11426 left_len = PyUnicode_GET_LENGTH(left);
11427 right_len = PyUnicode_GET_LENGTH(right);
11428 if (left_len > PY_SSIZE_T_MAX - right_len) {
11429 PyErr_SetString(PyExc_OverflowError,
11430 "strings are too large to concat");
11431 goto error;
11432 }
11433 new_len = left_len + right_len;
11434
11435 if (unicode_modifiable(left)
11436 && PyUnicode_CheckExact(right)
11437 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011438 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11439 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011440 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011441 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011442 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11443 {
11444 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011445 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011446 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011447
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011448 /* copy 'right' into the newly allocated area of 'left' */
11449 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011450 }
Victor Stinner488fa492011-12-12 00:01:39 +010011451 else {
11452 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11453 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011454 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011455
Victor Stinner488fa492011-12-12 00:01:39 +010011456 /* Concat the two Unicode strings */
11457 res = PyUnicode_New(new_len, maxchar);
11458 if (res == NULL)
11459 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011460 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11461 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011462 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011463 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011464 }
11465 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011466 return;
11467
11468error:
Victor Stinner488fa492011-12-12 00:01:39 +010011469 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011470}
11471
11472void
11473PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11474{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011475 PyUnicode_Append(pleft, right);
11476 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011477}
11478
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011479/*
11480Wraps stringlib_parse_args_finds() and additionally ensures that the
11481first argument is a unicode object.
11482*/
11483
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011484static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011485parse_args_finds_unicode(const char * function_name, PyObject *args,
11486 PyObject **substring,
11487 Py_ssize_t *start, Py_ssize_t *end)
11488{
11489 if(stringlib_parse_args_finds(function_name, args, substring,
11490 start, end)) {
11491 if (ensure_unicode(*substring) < 0)
11492 return 0;
11493 return 1;
11494 }
11495 return 0;
11496}
11497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011498PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011501Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011502string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011503interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504
11505static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011506unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011508 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011509 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011510 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011512 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 void *buf1, *buf2;
11514 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011516 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 kind1 = PyUnicode_KIND(self);
11520 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011521 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011522 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524 len1 = PyUnicode_GET_LENGTH(self);
11525 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011527 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011528 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011529
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011530 buf1 = PyUnicode_DATA(self);
11531 buf2 = PyUnicode_DATA(substring);
11532 if (kind2 != kind1) {
11533 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011534 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011535 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011536 }
11537 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 case PyUnicode_1BYTE_KIND:
11539 iresult = ucs1lib_count(
11540 ((Py_UCS1*)buf1) + start, end - start,
11541 buf2, len2, PY_SSIZE_T_MAX
11542 );
11543 break;
11544 case PyUnicode_2BYTE_KIND:
11545 iresult = ucs2lib_count(
11546 ((Py_UCS2*)buf1) + start, end - start,
11547 buf2, len2, PY_SSIZE_T_MAX
11548 );
11549 break;
11550 case PyUnicode_4BYTE_KIND:
11551 iresult = ucs4lib_count(
11552 ((Py_UCS4*)buf1) + start, end - start,
11553 buf2, len2, PY_SSIZE_T_MAX
11554 );
11555 break;
11556 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011557 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 }
11559
11560 result = PyLong_FromSsize_t(iresult);
11561
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011562 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011563 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565 return result;
11566}
11567
INADA Naoki3ae20562017-01-16 20:41:20 +090011568/*[clinic input]
11569str.encode as unicode_encode
11570
11571 encoding: str(c_default="NULL") = 'utf-8'
11572 The encoding in which to encode the string.
11573 errors: str(c_default="NULL") = 'strict'
11574 The error handling scheme to use for encoding errors.
11575 The default is 'strict' meaning that encoding errors raise a
11576 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11577 'xmlcharrefreplace' as well as any other name registered with
11578 codecs.register_error that can handle UnicodeEncodeErrors.
11579
11580Encode the string using the codec registered for encoding.
11581[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582
11583static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011584unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011585/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011587 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011588}
11589
INADA Naoki3ae20562017-01-16 20:41:20 +090011590/*[clinic input]
11591str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
INADA Naoki3ae20562017-01-16 20:41:20 +090011593 tabsize: int = 8
11594
11595Return a copy where all tab characters are expanded using spaces.
11596
11597If tabsize is not given, a tab size of 8 characters is assumed.
11598[clinic start generated code]*/
11599
11600static PyObject *
11601unicode_expandtabs_impl(PyObject *self, int tabsize)
11602/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011604 Py_ssize_t i, j, line_pos, src_len, incr;
11605 Py_UCS4 ch;
11606 PyObject *u;
11607 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011608 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011609 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Antoine Pitrou22425222011-10-04 19:10:51 +020011611 if (PyUnicode_READY(self) == -1)
11612 return NULL;
11613
Thomas Wouters7e474022000-07-16 12:04:32 +000011614 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011615 src_len = PyUnicode_GET_LENGTH(self);
11616 i = j = line_pos = 0;
11617 kind = PyUnicode_KIND(self);
11618 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011619 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011620 for (; i < src_len; i++) {
11621 ch = PyUnicode_READ(kind, src_data, i);
11622 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011623 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011625 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011626 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011627 goto overflow;
11628 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011629 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011630 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011633 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011634 goto overflow;
11635 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011637 if (ch == '\n' || ch == '\r')
11638 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011640 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011641 if (!found)
11642 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011643
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011645 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646 if (!u)
11647 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011648 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011649
Antoine Pitroue71d5742011-10-04 15:55:09 +020011650 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651
Antoine Pitroue71d5742011-10-04 15:55:09 +020011652 for (; i < src_len; i++) {
11653 ch = PyUnicode_READ(kind, src_data, i);
11654 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011656 incr = tabsize - (line_pos % tabsize);
11657 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011658 FILL(kind, dest_data, ' ', j, incr);
11659 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011660 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011661 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011662 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011663 line_pos++;
11664 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011665 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011666 if (ch == '\n' || ch == '\r')
11667 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011669 }
11670 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011671 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011672
Antoine Pitroue71d5742011-10-04 15:55:09 +020011673 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011674 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11675 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676}
11677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011678PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011679 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680\n\
11681Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011682such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683arguments start and end are interpreted as in slice notation.\n\
11684\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011685Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686
11687static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011690 /* initialize variables to prevent gcc warning */
11691 PyObject *substring = NULL;
11692 Py_ssize_t start = 0;
11693 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011694 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011696 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011699 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011702 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011703
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011704 if (result == -2)
11705 return NULL;
11706
Christian Heimes217cfd12007-12-02 14:31:20 +000011707 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708}
11709
11710static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011711unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011713 void *data;
11714 enum PyUnicode_Kind kind;
11715 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011716
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011717 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011718 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011720 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011721 if (PyUnicode_READY(self) == -1) {
11722 return NULL;
11723 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011724 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11725 PyErr_SetString(PyExc_IndexError, "string index out of range");
11726 return NULL;
11727 }
11728 kind = PyUnicode_KIND(self);
11729 data = PyUnicode_DATA(self);
11730 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011731 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732}
11733
Guido van Rossumc2504932007-09-18 19:42:40 +000011734/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011735 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011736static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011737unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738{
Guido van Rossumc2504932007-09-18 19:42:40 +000011739 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011740 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011741
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011742#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011743 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011744#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 if (_PyUnicode_HASH(self) != -1)
11746 return _PyUnicode_HASH(self);
11747 if (PyUnicode_READY(self) == -1)
11748 return -1;
11749 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011750 /*
11751 We make the hash of the empty string be 0, rather than using
11752 (prefix ^ suffix), since this slightly obfuscates the hash secret
11753 */
11754 if (len == 0) {
11755 _PyUnicode_HASH(self) = 0;
11756 return 0;
11757 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011758 x = _Py_HashBytes(PyUnicode_DATA(self),
11759 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011761 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762}
11763
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011764PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011765 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011767Return the lowest index in S where substring sub is found, \n\
11768such that sub is contained within S[start:end]. Optional\n\
11769arguments start and end are interpreted as in slice notation.\n\
11770\n\
11771Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772
11773static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011776 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011777 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011778 PyObject *substring = NULL;
11779 Py_ssize_t start = 0;
11780 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011782 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011785 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011788 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 if (result == -2)
11791 return NULL;
11792
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793 if (result < 0) {
11794 PyErr_SetString(PyExc_ValueError, "substring not found");
11795 return NULL;
11796 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011797
Christian Heimes217cfd12007-12-02 14:31:20 +000011798 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799}
11800
INADA Naoki3ae20562017-01-16 20:41:20 +090011801/*[clinic input]
11802str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803
INADA Naoki3ae20562017-01-16 20:41:20 +090011804Return True if the string is a lowercase string, False otherwise.
11805
11806A string is lowercase if all cased characters in the string are lowercase and
11807there is at least one cased character in the string.
11808[clinic start generated code]*/
11809
11810static PyObject *
11811unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011812/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 Py_ssize_t i, length;
11815 int kind;
11816 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817 int cased;
11818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 if (PyUnicode_READY(self) == -1)
11820 return NULL;
11821 length = PyUnicode_GET_LENGTH(self);
11822 kind = PyUnicode_KIND(self);
11823 data = PyUnicode_DATA(self);
11824
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 if (length == 1)
11827 return PyBool_FromLong(
11828 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011830 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011831 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011832 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011833
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 for (i = 0; i < length; i++) {
11836 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011837
Benjamin Peterson29060642009-01-31 22:14:21 +000011838 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011839 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011840 else if (!cased && Py_UNICODE_ISLOWER(ch))
11841 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011843 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844}
11845
INADA Naoki3ae20562017-01-16 20:41:20 +090011846/*[clinic input]
11847str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848
INADA Naoki3ae20562017-01-16 20:41:20 +090011849Return True if the string is an uppercase string, False otherwise.
11850
11851A string is uppercase if all cased characters in the string are uppercase and
11852there is at least one cased character in the string.
11853[clinic start generated code]*/
11854
11855static PyObject *
11856unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011857/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 Py_ssize_t i, length;
11860 int kind;
11861 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 int cased;
11863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 if (PyUnicode_READY(self) == -1)
11865 return NULL;
11866 length = PyUnicode_GET_LENGTH(self);
11867 kind = PyUnicode_KIND(self);
11868 data = PyUnicode_DATA(self);
11869
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011871 if (length == 1)
11872 return PyBool_FromLong(
11873 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011875 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011877 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011878
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 for (i = 0; i < length; i++) {
11881 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011882
Benjamin Peterson29060642009-01-31 22:14:21 +000011883 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011884 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011885 else if (!cased && Py_UNICODE_ISUPPER(ch))
11886 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011888 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889}
11890
INADA Naoki3ae20562017-01-16 20:41:20 +090011891/*[clinic input]
11892str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893
INADA Naoki3ae20562017-01-16 20:41:20 +090011894Return True if the string is a title-cased string, False otherwise.
11895
11896In a title-cased string, upper- and title-case characters may only
11897follow uncased characters and lowercase characters only cased ones.
11898[clinic start generated code]*/
11899
11900static PyObject *
11901unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011902/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 Py_ssize_t i, length;
11905 int kind;
11906 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907 int cased, previous_is_cased;
11908
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 if (PyUnicode_READY(self) == -1)
11910 return NULL;
11911 length = PyUnicode_GET_LENGTH(self);
11912 kind = PyUnicode_KIND(self);
11913 data = PyUnicode_DATA(self);
11914
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916 if (length == 1) {
11917 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11918 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11919 (Py_UNICODE_ISUPPER(ch) != 0));
11920 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011922 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011924 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011925
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926 cased = 0;
11927 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 for (i = 0; i < length; i++) {
11929 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011930
Benjamin Peterson29060642009-01-31 22:14:21 +000011931 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11932 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011933 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011934 previous_is_cased = 1;
11935 cased = 1;
11936 }
11937 else if (Py_UNICODE_ISLOWER(ch)) {
11938 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011939 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011940 previous_is_cased = 1;
11941 cased = 1;
11942 }
11943 else
11944 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011946 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947}
11948
INADA Naoki3ae20562017-01-16 20:41:20 +090011949/*[clinic input]
11950str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951
INADA Naoki3ae20562017-01-16 20:41:20 +090011952Return True if the string is a whitespace string, False otherwise.
11953
11954A string is whitespace if all characters in the string are whitespace and there
11955is at least one character in the string.
11956[clinic start generated code]*/
11957
11958static PyObject *
11959unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011960/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011961{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 Py_ssize_t i, length;
11963 int kind;
11964 void *data;
11965
11966 if (PyUnicode_READY(self) == -1)
11967 return NULL;
11968 length = PyUnicode_GET_LENGTH(self);
11969 kind = PyUnicode_KIND(self);
11970 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 if (length == 1)
11974 return PyBool_FromLong(
11975 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011977 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011978 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011979 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 for (i = 0; i < length; i++) {
11982 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011983 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011984 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011986 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011987}
11988
INADA Naoki3ae20562017-01-16 20:41:20 +090011989/*[clinic input]
11990str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011991
INADA Naoki3ae20562017-01-16 20:41:20 +090011992Return True if the string is an alphabetic string, False otherwise.
11993
11994A string is alphabetic if all characters in the string are alphabetic and there
11995is at least one character in the string.
11996[clinic start generated code]*/
11997
11998static PyObject *
11999unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012000/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 Py_ssize_t i, length;
12003 int kind;
12004 void *data;
12005
12006 if (PyUnicode_READY(self) == -1)
12007 return NULL;
12008 length = PyUnicode_GET_LENGTH(self);
12009 kind = PyUnicode_KIND(self);
12010 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012011
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012012 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 if (length == 1)
12014 return PyBool_FromLong(
12015 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012016
12017 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012019 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 for (i = 0; i < length; i++) {
12022 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012023 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012024 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012025 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012026}
12027
INADA Naoki3ae20562017-01-16 20:41:20 +090012028/*[clinic input]
12029str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012030
INADA Naoki3ae20562017-01-16 20:41:20 +090012031Return True if the string is an alpha-numeric string, False otherwise.
12032
12033A string is alpha-numeric if all characters in the string are alpha-numeric and
12034there is at least one character in the string.
12035[clinic start generated code]*/
12036
12037static PyObject *
12038unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012039/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 int kind;
12042 void *data;
12043 Py_ssize_t len, i;
12044
12045 if (PyUnicode_READY(self) == -1)
12046 return NULL;
12047
12048 kind = PyUnicode_KIND(self);
12049 data = PyUnicode_DATA(self);
12050 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012051
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012052 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 if (len == 1) {
12054 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12055 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12056 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012057
12058 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012060 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 for (i = 0; i < len; i++) {
12063 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012064 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012065 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012066 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012067 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012068}
12069
INADA Naoki3ae20562017-01-16 20:41:20 +090012070/*[clinic input]
12071str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072
INADA Naoki3ae20562017-01-16 20:41:20 +090012073Return True if the string is a decimal string, False otherwise.
12074
12075A string is a decimal string if all characters in the string are decimal and
12076there is at least one character in the string.
12077[clinic start generated code]*/
12078
12079static PyObject *
12080unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012081/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012082{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 Py_ssize_t i, length;
12084 int kind;
12085 void *data;
12086
12087 if (PyUnicode_READY(self) == -1)
12088 return NULL;
12089 length = PyUnicode_GET_LENGTH(self);
12090 kind = PyUnicode_KIND(self);
12091 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012094 if (length == 1)
12095 return PyBool_FromLong(
12096 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012097
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012098 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012100 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 for (i = 0; i < length; i++) {
12103 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012104 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012106 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107}
12108
INADA Naoki3ae20562017-01-16 20:41:20 +090012109/*[clinic input]
12110str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111
INADA Naoki3ae20562017-01-16 20:41:20 +090012112Return True if the string is a digit string, False otherwise.
12113
12114A string is a digit string if all characters in the string are digits and there
12115is at least one character in the string.
12116[clinic start generated code]*/
12117
12118static PyObject *
12119unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012120/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 Py_ssize_t i, length;
12123 int kind;
12124 void *data;
12125
12126 if (PyUnicode_READY(self) == -1)
12127 return NULL;
12128 length = PyUnicode_GET_LENGTH(self);
12129 kind = PyUnicode_KIND(self);
12130 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 if (length == 1) {
12134 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12135 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12136 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012138 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012140 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 for (i = 0; i < length; i++) {
12143 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012144 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012146 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147}
12148
INADA Naoki3ae20562017-01-16 20:41:20 +090012149/*[clinic input]
12150str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151
INADA Naoki3ae20562017-01-16 20:41:20 +090012152Return True if the string is a numeric string, False otherwise.
12153
12154A string is numeric if all characters in the string are numeric and there is at
12155least one character in the string.
12156[clinic start generated code]*/
12157
12158static PyObject *
12159unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012160/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162 Py_ssize_t i, length;
12163 int kind;
12164 void *data;
12165
12166 if (PyUnicode_READY(self) == -1)
12167 return NULL;
12168 length = PyUnicode_GET_LENGTH(self);
12169 kind = PyUnicode_KIND(self);
12170 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 if (length == 1)
12174 return PyBool_FromLong(
12175 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012177 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012179 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012181 for (i = 0; i < length; i++) {
12182 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012183 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012185 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186}
12187
Martin v. Löwis47383402007-08-15 07:32:56 +000012188int
12189PyUnicode_IsIdentifier(PyObject *self)
12190{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 int kind;
12192 void *data;
12193 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012194 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012195
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012196 if (PyUnicode_READY(self) == -1) {
12197 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012198 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 }
12200
12201 /* Special case for empty strings */
12202 if (PyUnicode_GET_LENGTH(self) == 0)
12203 return 0;
12204 kind = PyUnicode_KIND(self);
12205 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012206
12207 /* PEP 3131 says that the first character must be in
12208 XID_Start and subsequent characters in XID_Continue,
12209 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012210 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012211 letters, digits, underscore). However, given the current
12212 definition of XID_Start and XID_Continue, it is sufficient
12213 to check just for these, except that _ must be allowed
12214 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012216 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012217 return 0;
12218
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012219 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012221 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012222 return 1;
12223}
12224
INADA Naoki3ae20562017-01-16 20:41:20 +090012225/*[clinic input]
12226str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012227
INADA Naoki3ae20562017-01-16 20:41:20 +090012228Return True if the string is a valid Python identifier, False otherwise.
12229
12230Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12231"class".
12232[clinic start generated code]*/
12233
12234static PyObject *
12235unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012236/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012237{
12238 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12239}
12240
INADA Naoki3ae20562017-01-16 20:41:20 +090012241/*[clinic input]
12242str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012243
INADA Naoki3ae20562017-01-16 20:41:20 +090012244Return True if the string is printable, False otherwise.
12245
12246A string is printable if all of its characters are considered printable in
12247repr() or if it is empty.
12248[clinic start generated code]*/
12249
12250static PyObject *
12251unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012252/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012253{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 Py_ssize_t i, length;
12255 int kind;
12256 void *data;
12257
12258 if (PyUnicode_READY(self) == -1)
12259 return NULL;
12260 length = PyUnicode_GET_LENGTH(self);
12261 kind = PyUnicode_KIND(self);
12262 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012263
12264 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 if (length == 1)
12266 return PyBool_FromLong(
12267 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012269 for (i = 0; i < length; i++) {
12270 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012271 Py_RETURN_FALSE;
12272 }
12273 }
12274 Py_RETURN_TRUE;
12275}
12276
INADA Naoki3ae20562017-01-16 20:41:20 +090012277/*[clinic input]
12278str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279
INADA Naoki3ae20562017-01-16 20:41:20 +090012280 iterable: object
12281 /
12282
12283Concatenate any number of strings.
12284
Martin Panter91a88662017-01-24 00:30:06 +000012285The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012286The result is returned as a new string.
12287
12288Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12289[clinic start generated code]*/
12290
12291static PyObject *
12292unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012293/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294{
INADA Naoki3ae20562017-01-16 20:41:20 +090012295 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296}
12297
Martin v. Löwis18e16552006-02-15 17:27:45 +000012298static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012299unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 if (PyUnicode_READY(self) == -1)
12302 return -1;
12303 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012304}
12305
INADA Naoki3ae20562017-01-16 20:41:20 +090012306/*[clinic input]
12307str.ljust as unicode_ljust
12308
12309 width: Py_ssize_t
12310 fillchar: Py_UCS4 = ' '
12311 /
12312
12313Return a left-justified string of length width.
12314
12315Padding is done using the specified fill character (default is a space).
12316[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317
12318static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012319unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12320/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012322 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012323 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324
Victor Stinnerc4b49542011-12-11 22:44:26 +010012325 if (PyUnicode_GET_LENGTH(self) >= width)
12326 return unicode_result_unchanged(self);
12327
12328 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012329}
12330
INADA Naoki3ae20562017-01-16 20:41:20 +090012331/*[clinic input]
12332str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333
INADA Naoki3ae20562017-01-16 20:41:20 +090012334Return a copy of the string converted to lowercase.
12335[clinic start generated code]*/
12336
12337static PyObject *
12338unicode_lower_impl(PyObject *self)
12339/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012341 if (PyUnicode_READY(self) == -1)
12342 return NULL;
12343 if (PyUnicode_IS_ASCII(self))
12344 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012345 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346}
12347
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012348#define LEFTSTRIP 0
12349#define RIGHTSTRIP 1
12350#define BOTHSTRIP 2
12351
12352/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012353static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354
INADA Naoki3ae20562017-01-16 20:41:20 +090012355#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012356
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012357/* externally visible for str.strip(unicode) */
12358PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012359_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012360{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 void *data;
12362 int kind;
12363 Py_ssize_t i, j, len;
12364 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012365 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012366
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12368 return NULL;
12369
12370 kind = PyUnicode_KIND(self);
12371 data = PyUnicode_DATA(self);
12372 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012373 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12375 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012376 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012377
Benjamin Peterson14339b62009-01-31 16:36:08 +000012378 i = 0;
12379 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012380 while (i < len) {
12381 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12382 if (!BLOOM(sepmask, ch))
12383 break;
12384 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12385 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012386 i++;
12387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012388 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012389
Benjamin Peterson14339b62009-01-31 16:36:08 +000012390 j = len;
12391 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012392 j--;
12393 while (j >= i) {
12394 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12395 if (!BLOOM(sepmask, ch))
12396 break;
12397 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12398 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012399 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012400 }
12401
Benjamin Peterson29060642009-01-31 22:14:21 +000012402 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012403 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012404
Victor Stinner7931d9a2011-11-04 00:22:48 +010012405 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012406}
12407
12408PyObject*
12409PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12410{
12411 unsigned char *data;
12412 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012413 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414
Victor Stinnerde636f32011-10-01 03:55:54 +020012415 if (PyUnicode_READY(self) == -1)
12416 return NULL;
12417
Victor Stinner684d5fd2012-05-03 02:32:34 +020012418 length = PyUnicode_GET_LENGTH(self);
12419 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012420
Victor Stinner684d5fd2012-05-03 02:32:34 +020012421 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012422 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423
Victor Stinnerde636f32011-10-01 03:55:54 +020012424 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012425 PyErr_SetString(PyExc_IndexError, "string index out of range");
12426 return NULL;
12427 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012428 if (start >= length || end < start)
12429 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012430
Victor Stinner684d5fd2012-05-03 02:32:34 +020012431 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012432 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012433 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012434 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012435 }
12436 else {
12437 kind = PyUnicode_KIND(self);
12438 data = PyUnicode_1BYTE_DATA(self);
12439 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012440 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012441 length);
12442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444
12445static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012446do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 Py_ssize_t len, i, j;
12449
12450 if (PyUnicode_READY(self) == -1)
12451 return NULL;
12452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012454
Victor Stinnercc7af722013-04-09 22:39:24 +020012455 if (PyUnicode_IS_ASCII(self)) {
12456 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12457
12458 i = 0;
12459 if (striptype != RIGHTSTRIP) {
12460 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012461 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012462 if (!_Py_ascii_whitespace[ch])
12463 break;
12464 i++;
12465 }
12466 }
12467
12468 j = len;
12469 if (striptype != LEFTSTRIP) {
12470 j--;
12471 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012472 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012473 if (!_Py_ascii_whitespace[ch])
12474 break;
12475 j--;
12476 }
12477 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012478 }
12479 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012480 else {
12481 int kind = PyUnicode_KIND(self);
12482 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012483
Victor Stinnercc7af722013-04-09 22:39:24 +020012484 i = 0;
12485 if (striptype != RIGHTSTRIP) {
12486 while (i < len) {
12487 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12488 if (!Py_UNICODE_ISSPACE(ch))
12489 break;
12490 i++;
12491 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012492 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012493
12494 j = len;
12495 if (striptype != LEFTSTRIP) {
12496 j--;
12497 while (j >= i) {
12498 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12499 if (!Py_UNICODE_ISSPACE(ch))
12500 break;
12501 j--;
12502 }
12503 j++;
12504 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012505 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012506
Victor Stinner7931d9a2011-11-04 00:22:48 +010012507 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508}
12509
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012510
12511static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012512do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012513{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012514 if (sep != NULL && sep != Py_None) {
12515 if (PyUnicode_Check(sep))
12516 return _PyUnicode_XStrip(self, striptype, sep);
12517 else {
12518 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012519 "%s arg must be None or str",
12520 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012521 return NULL;
12522 }
12523 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012524
Benjamin Peterson14339b62009-01-31 16:36:08 +000012525 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012526}
12527
12528
INADA Naoki3ae20562017-01-16 20:41:20 +090012529/*[clinic input]
12530str.strip as unicode_strip
12531
12532 chars: object = None
12533 /
12534
Victor Stinner0c4a8282017-01-17 02:21:47 +010012535Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012536
12537If chars is given and not None, remove characters in chars instead.
12538[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012539
12540static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012541unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012542/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012543{
INADA Naoki3ae20562017-01-16 20:41:20 +090012544 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012545}
12546
12547
INADA Naoki3ae20562017-01-16 20:41:20 +090012548/*[clinic input]
12549str.lstrip as unicode_lstrip
12550
12551 chars: object = NULL
12552 /
12553
12554Return a copy of the string with leading whitespace removed.
12555
12556If chars is given and not None, remove characters in chars instead.
12557[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012558
12559static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012560unicode_lstrip_impl(PyObject *self, PyObject *chars)
12561/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012562{
INADA Naoki3ae20562017-01-16 20:41:20 +090012563 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012564}
12565
12566
INADA Naoki3ae20562017-01-16 20:41:20 +090012567/*[clinic input]
12568str.rstrip as unicode_rstrip
12569
12570 chars: object = NULL
12571 /
12572
12573Return a copy of the string with trailing whitespace removed.
12574
12575If chars is given and not None, remove characters in chars instead.
12576[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012577
12578static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012579unicode_rstrip_impl(PyObject *self, PyObject *chars)
12580/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012581{
INADA Naoki3ae20562017-01-16 20:41:20 +090012582 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012583}
12584
12585
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012587unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012589 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591
Serhiy Storchaka05997252013-01-26 12:14:02 +020012592 if (len < 1)
12593 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594
Victor Stinnerc4b49542011-12-11 22:44:26 +010012595 /* no repeat, return original string */
12596 if (len == 1)
12597 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012598
Benjamin Petersonbac79492012-01-14 13:34:47 -050012599 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600 return NULL;
12601
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012602 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012603 PyErr_SetString(PyExc_OverflowError,
12604 "repeated string is too long");
12605 return NULL;
12606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012608
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012609 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610 if (!u)
12611 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012612 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012614 if (PyUnicode_GET_LENGTH(str) == 1) {
12615 const int kind = PyUnicode_KIND(str);
12616 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012617 if (kind == PyUnicode_1BYTE_KIND) {
12618 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012619 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012620 }
12621 else if (kind == PyUnicode_2BYTE_KIND) {
12622 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012623 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012624 ucs2[n] = fill_char;
12625 } else {
12626 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12627 assert(kind == PyUnicode_4BYTE_KIND);
12628 for (n = 0; n < len; ++n)
12629 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 }
12632 else {
12633 /* number of characters copied this far */
12634 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012635 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012637 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012638 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012639 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012641 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012642 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012643 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644 }
12645
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012646 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012647 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648}
12649
Alexander Belopolsky40018472011-02-26 01:02:56 +000012650PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012651PyUnicode_Replace(PyObject *str,
12652 PyObject *substr,
12653 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012654 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012656 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12657 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012658 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012659 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660}
12661
INADA Naoki3ae20562017-01-16 20:41:20 +090012662/*[clinic input]
12663str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664
INADA Naoki3ae20562017-01-16 20:41:20 +090012665 old: unicode
12666 new: unicode
12667 count: Py_ssize_t = -1
12668 Maximum number of occurrences to replace.
12669 -1 (the default value) means replace all occurrences.
12670 /
12671
12672Return a copy with all occurrences of substring old replaced by new.
12673
12674If the optional argument count is given, only the first count occurrences are
12675replaced.
12676[clinic start generated code]*/
12677
12678static PyObject *
12679unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12680 Py_ssize_t count)
12681/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012683 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012684 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012685 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686}
12687
Alexander Belopolsky40018472011-02-26 01:02:56 +000012688static PyObject *
12689unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012691 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 Py_ssize_t isize;
12693 Py_ssize_t osize, squote, dquote, i, o;
12694 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012695 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012699 return NULL;
12700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701 isize = PyUnicode_GET_LENGTH(unicode);
12702 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012703
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704 /* Compute length of output, quote characters, and
12705 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012706 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707 max = 127;
12708 squote = dquote = 0;
12709 ikind = PyUnicode_KIND(unicode);
12710 for (i = 0; i < isize; i++) {
12711 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012712 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012713 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012714 case '\'': squote++; break;
12715 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012717 incr = 2;
12718 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 default:
12720 /* Fast-path ASCII */
12721 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012722 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012724 ;
12725 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012728 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012729 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012730 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012731 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012732 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012733 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012734 if (osize > PY_SSIZE_T_MAX - incr) {
12735 PyErr_SetString(PyExc_OverflowError,
12736 "string is too long to generate repr");
12737 return NULL;
12738 }
12739 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 }
12741
12742 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012743 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012744 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012745 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012746 if (dquote)
12747 /* Both squote and dquote present. Use squote,
12748 and escape them */
12749 osize += squote;
12750 else
12751 quote = '"';
12752 }
Victor Stinner55c08782013-04-14 18:45:39 +020012753 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754
12755 repr = PyUnicode_New(osize, max);
12756 if (repr == NULL)
12757 return NULL;
12758 okind = PyUnicode_KIND(repr);
12759 odata = PyUnicode_DATA(repr);
12760
12761 PyUnicode_WRITE(okind, odata, 0, quote);
12762 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012763 if (unchanged) {
12764 _PyUnicode_FastCopyCharacters(repr, 1,
12765 unicode, 0,
12766 isize);
12767 }
12768 else {
12769 for (i = 0, o = 1; i < isize; i++) {
12770 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012771
Victor Stinner55c08782013-04-14 18:45:39 +020012772 /* Escape quotes and backslashes */
12773 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012774 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012775 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012776 continue;
12777 }
12778
12779 /* Map special whitespace to '\t', \n', '\r' */
12780 if (ch == '\t') {
12781 PyUnicode_WRITE(okind, odata, o++, '\\');
12782 PyUnicode_WRITE(okind, odata, o++, 't');
12783 }
12784 else if (ch == '\n') {
12785 PyUnicode_WRITE(okind, odata, o++, '\\');
12786 PyUnicode_WRITE(okind, odata, o++, 'n');
12787 }
12788 else if (ch == '\r') {
12789 PyUnicode_WRITE(okind, odata, o++, '\\');
12790 PyUnicode_WRITE(okind, odata, o++, 'r');
12791 }
12792
12793 /* Map non-printable US ASCII to '\xhh' */
12794 else if (ch < ' ' || ch == 0x7F) {
12795 PyUnicode_WRITE(okind, odata, o++, '\\');
12796 PyUnicode_WRITE(okind, odata, o++, 'x');
12797 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12798 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12799 }
12800
12801 /* Copy ASCII characters as-is */
12802 else if (ch < 0x7F) {
12803 PyUnicode_WRITE(okind, odata, o++, ch);
12804 }
12805
12806 /* Non-ASCII characters */
12807 else {
12808 /* Map Unicode whitespace and control characters
12809 (categories Z* and C* except ASCII space)
12810 */
12811 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12812 PyUnicode_WRITE(okind, odata, o++, '\\');
12813 /* Map 8-bit characters to '\xhh' */
12814 if (ch <= 0xff) {
12815 PyUnicode_WRITE(okind, odata, o++, 'x');
12816 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12817 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12818 }
12819 /* Map 16-bit characters to '\uxxxx' */
12820 else if (ch <= 0xffff) {
12821 PyUnicode_WRITE(okind, odata, o++, 'u');
12822 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12823 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12824 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12825 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12826 }
12827 /* Map 21-bit characters to '\U00xxxxxx' */
12828 else {
12829 PyUnicode_WRITE(okind, odata, o++, 'U');
12830 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12831 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12832 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12833 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12834 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12835 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12836 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12837 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12838 }
12839 }
12840 /* Copy characters as-is */
12841 else {
12842 PyUnicode_WRITE(okind, odata, o++, ch);
12843 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012844 }
12845 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012847 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012848 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012849 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012850}
12851
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012852PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012853 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012854\n\
12855Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012856such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012857arguments start and end are interpreted as in slice notation.\n\
12858\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012859Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860
12861static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012862unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012864 /* initialize variables to prevent gcc warning */
12865 PyObject *substring = NULL;
12866 Py_ssize_t start = 0;
12867 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012868 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012870 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012871 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012873 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012875
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012876 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 if (result == -2)
12879 return NULL;
12880
Christian Heimes217cfd12007-12-02 14:31:20 +000012881 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882}
12883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012884PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012885 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012887Return the highest index in S where substring sub is found,\n\
12888such that sub is contained within S[start:end]. Optional\n\
12889arguments start and end are interpreted as in slice notation.\n\
12890\n\
12891Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892
12893static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012894unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012896 /* initialize variables to prevent gcc warning */
12897 PyObject *substring = NULL;
12898 Py_ssize_t start = 0;
12899 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012900 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012902 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012903 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012904
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012905 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012907
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012908 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012910 if (result == -2)
12911 return NULL;
12912
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913 if (result < 0) {
12914 PyErr_SetString(PyExc_ValueError, "substring not found");
12915 return NULL;
12916 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917
Christian Heimes217cfd12007-12-02 14:31:20 +000012918 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012919}
12920
INADA Naoki3ae20562017-01-16 20:41:20 +090012921/*[clinic input]
12922str.rjust as unicode_rjust
12923
12924 width: Py_ssize_t
12925 fillchar: Py_UCS4 = ' '
12926 /
12927
12928Return a right-justified string of length width.
12929
12930Padding is done using the specified fill character (default is a space).
12931[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932
12933static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012934unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12935/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012936{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012937 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938 return NULL;
12939
Victor Stinnerc4b49542011-12-11 22:44:26 +010012940 if (PyUnicode_GET_LENGTH(self) >= width)
12941 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942
Victor Stinnerc4b49542011-12-11 22:44:26 +010012943 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012944}
12945
Alexander Belopolsky40018472011-02-26 01:02:56 +000012946PyObject *
12947PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012948{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012949 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012950 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012951
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012952 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012953}
12954
INADA Naoki3ae20562017-01-16 20:41:20 +090012955/*[clinic input]
12956str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012957
INADA Naoki3ae20562017-01-16 20:41:20 +090012958 sep: object = None
12959 The delimiter according which to split the string.
12960 None (the default value) means split according to any whitespace,
12961 and discard empty strings from the result.
12962 maxsplit: Py_ssize_t = -1
12963 Maximum number of splits to do.
12964 -1 (the default value) means no limit.
12965
12966Return a list of the words in the string, using sep as the delimiter string.
12967[clinic start generated code]*/
12968
12969static PyObject *
12970unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12971/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012972{
INADA Naoki3ae20562017-01-16 20:41:20 +090012973 if (sep == Py_None)
12974 return split(self, NULL, maxsplit);
12975 if (PyUnicode_Check(sep))
12976 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012977
12978 PyErr_Format(PyExc_TypeError,
12979 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012980 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012981 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012982}
12983
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012985PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012986{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012987 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012988 int kind1, kind2;
12989 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012991
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012992 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012993 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012994
Victor Stinner14f8f022011-10-05 20:58:25 +020012995 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 len1 = PyUnicode_GET_LENGTH(str_obj);
12998 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012999 if (kind1 < kind2 || len1 < len2) {
13000 _Py_INCREF_UNICODE_EMPTY();
13001 if (!unicode_empty)
13002 out = NULL;
13003 else {
13004 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
13005 Py_DECREF(unicode_empty);
13006 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013007 return out;
13008 }
13009 buf1 = PyUnicode_DATA(str_obj);
13010 buf2 = PyUnicode_DATA(sep_obj);
13011 if (kind2 != kind1) {
13012 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13013 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013014 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013015 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013016
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013017 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013018 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013019 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13020 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13021 else
13022 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 break;
13024 case PyUnicode_2BYTE_KIND:
13025 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13026 break;
13027 case PyUnicode_4BYTE_KIND:
13028 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13029 break;
13030 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013031 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013032 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013033
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013034 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013035 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013036
13037 return out;
13038}
13039
13040
13041PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013042PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013043{
Thomas Wouters477c8d52006-05-27 19:21:47 +000013044 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013045 int kind1, kind2;
13046 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013047 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013048
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013049 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013050 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013051
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013052 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013053 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013054 len1 = PyUnicode_GET_LENGTH(str_obj);
13055 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013056 if (kind1 < kind2 || len1 < len2) {
13057 _Py_INCREF_UNICODE_EMPTY();
13058 if (!unicode_empty)
13059 out = NULL;
13060 else {
13061 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13062 Py_DECREF(unicode_empty);
13063 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013064 return out;
13065 }
13066 buf1 = PyUnicode_DATA(str_obj);
13067 buf2 = PyUnicode_DATA(sep_obj);
13068 if (kind2 != kind1) {
13069 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13070 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013071 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013073
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013074 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013075 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013076 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13077 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13078 else
13079 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013080 break;
13081 case PyUnicode_2BYTE_KIND:
13082 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13083 break;
13084 case PyUnicode_4BYTE_KIND:
13085 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13086 break;
13087 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013088 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013089 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013090
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013091 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013093
13094 return out;
13095}
13096
INADA Naoki3ae20562017-01-16 20:41:20 +090013097/*[clinic input]
13098str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013099
INADA Naoki3ae20562017-01-16 20:41:20 +090013100 sep: object
13101 /
13102
13103Partition the string into three parts using the given separator.
13104
13105This will search for the separator in the string. If the separator is found,
13106returns a 3-tuple containing the part before the separator, the separator
13107itself, and the part after it.
13108
13109If the separator is not found, returns a 3-tuple containing the original string
13110and two empty strings.
13111[clinic start generated code]*/
13112
13113static PyObject *
13114unicode_partition(PyObject *self, PyObject *sep)
13115/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013116{
INADA Naoki3ae20562017-01-16 20:41:20 +090013117 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013118}
13119
INADA Naoki3ae20562017-01-16 20:41:20 +090013120/*[clinic input]
13121str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013122
INADA Naoki3ae20562017-01-16 20:41:20 +090013123Partition the string into three parts using the given separator.
13124
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013125This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013126the separator is found, returns a 3-tuple containing the part before the
13127separator, the separator itself, and the part after it.
13128
13129If the separator is not found, returns a 3-tuple containing two empty strings
13130and the original string.
13131[clinic start generated code]*/
13132
13133static PyObject *
13134unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013135/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013136{
INADA Naoki3ae20562017-01-16 20:41:20 +090013137 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013138}
13139
Alexander Belopolsky40018472011-02-26 01:02:56 +000013140PyObject *
13141PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013142{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013143 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013144 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013145
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013146 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013147}
13148
INADA Naoki3ae20562017-01-16 20:41:20 +090013149/*[clinic input]
13150str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013151
INADA Naoki3ae20562017-01-16 20:41:20 +090013152Return a list of the words in the string, using sep as the delimiter string.
13153
13154Splits are done starting at the end of the string and working to the front.
13155[clinic start generated code]*/
13156
13157static PyObject *
13158unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13159/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013160{
INADA Naoki3ae20562017-01-16 20:41:20 +090013161 if (sep == Py_None)
13162 return rsplit(self, NULL, maxsplit);
13163 if (PyUnicode_Check(sep))
13164 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013165
13166 PyErr_Format(PyExc_TypeError,
13167 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013168 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013169 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013170}
13171
INADA Naoki3ae20562017-01-16 20:41:20 +090013172/*[clinic input]
13173str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013175 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013176
13177Return a list of the lines in the string, breaking at line boundaries.
13178
13179Line breaks are not included in the resulting list unless keepends is given and
13180true.
13181[clinic start generated code]*/
13182
13183static PyObject *
13184unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013185/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013187 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188}
13189
13190static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013191PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013193 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194}
13195
INADA Naoki3ae20562017-01-16 20:41:20 +090013196/*[clinic input]
13197str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198
INADA Naoki3ae20562017-01-16 20:41:20 +090013199Convert uppercase characters to lowercase and lowercase characters to uppercase.
13200[clinic start generated code]*/
13201
13202static PyObject *
13203unicode_swapcase_impl(PyObject *self)
13204/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013206 if (PyUnicode_READY(self) == -1)
13207 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013208 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209}
13210
Larry Hastings61272b72014-01-07 12:41:53 -080013211/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013212
Larry Hastings31826802013-10-19 00:09:25 -070013213@staticmethod
13214str.maketrans as unicode_maketrans
13215
13216 x: object
13217
13218 y: unicode=NULL
13219
13220 z: unicode=NULL
13221
13222 /
13223
13224Return a translation table usable for str.translate().
13225
13226If there is only one argument, it must be a dictionary mapping Unicode
13227ordinals (integers) or characters to Unicode ordinals, strings or None.
13228Character keys will be then converted to ordinals.
13229If there are two arguments, they must be strings of equal length, and
13230in the resulting dictionary, each character in x will be mapped to the
13231character at the same position in y. If there is a third argument, it
13232must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013233[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013234
Larry Hastings31826802013-10-19 00:09:25 -070013235static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013236unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013237/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013238{
Georg Brandlceee0772007-11-27 23:48:05 +000013239 PyObject *new = NULL, *key, *value;
13240 Py_ssize_t i = 0;
13241 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013242
Georg Brandlceee0772007-11-27 23:48:05 +000013243 new = PyDict_New();
13244 if (!new)
13245 return NULL;
13246 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013247 int x_kind, y_kind, z_kind;
13248 void *x_data, *y_data, *z_data;
13249
Georg Brandlceee0772007-11-27 23:48:05 +000013250 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013251 if (!PyUnicode_Check(x)) {
13252 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13253 "be a string if there is a second argument");
13254 goto err;
13255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013256 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013257 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13258 "arguments must have equal length");
13259 goto err;
13260 }
13261 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 x_kind = PyUnicode_KIND(x);
13263 y_kind = PyUnicode_KIND(y);
13264 x_data = PyUnicode_DATA(x);
13265 y_data = PyUnicode_DATA(y);
13266 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13267 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013268 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013269 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013270 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013271 if (!value) {
13272 Py_DECREF(key);
13273 goto err;
13274 }
Georg Brandlceee0772007-11-27 23:48:05 +000013275 res = PyDict_SetItem(new, key, value);
13276 Py_DECREF(key);
13277 Py_DECREF(value);
13278 if (res < 0)
13279 goto err;
13280 }
13281 /* create entries for deleting chars in z */
13282 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013283 z_kind = PyUnicode_KIND(z);
13284 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013285 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013286 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013287 if (!key)
13288 goto err;
13289 res = PyDict_SetItem(new, key, Py_None);
13290 Py_DECREF(key);
13291 if (res < 0)
13292 goto err;
13293 }
13294 }
13295 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013296 int kind;
13297 void *data;
13298
Georg Brandlceee0772007-11-27 23:48:05 +000013299 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013300 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013301 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13302 "to maketrans it must be a dict");
13303 goto err;
13304 }
13305 /* copy entries into the new dict, converting string keys to int keys */
13306 while (PyDict_Next(x, &i, &key, &value)) {
13307 if (PyUnicode_Check(key)) {
13308 /* convert string keys to integer keys */
13309 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013310 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013311 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13312 "table must be of length 1");
13313 goto err;
13314 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 kind = PyUnicode_KIND(key);
13316 data = PyUnicode_DATA(key);
13317 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013318 if (!newkey)
13319 goto err;
13320 res = PyDict_SetItem(new, newkey, value);
13321 Py_DECREF(newkey);
13322 if (res < 0)
13323 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013324 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013325 /* just keep integer keys */
13326 if (PyDict_SetItem(new, key, value) < 0)
13327 goto err;
13328 } else {
13329 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13330 "be strings or integers");
13331 goto err;
13332 }
13333 }
13334 }
13335 return new;
13336 err:
13337 Py_DECREF(new);
13338 return NULL;
13339}
13340
INADA Naoki3ae20562017-01-16 20:41:20 +090013341/*[clinic input]
13342str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343
INADA Naoki3ae20562017-01-16 20:41:20 +090013344 table: object
13345 Translation table, which must be a mapping of Unicode ordinals to
13346 Unicode ordinals, strings, or None.
13347 /
13348
13349Replace each character in the string using the given translation table.
13350
13351The table must implement lookup/indexing via __getitem__, for instance a
13352dictionary or list. If this operation raises LookupError, the character is
13353left untouched. Characters mapped to None are deleted.
13354[clinic start generated code]*/
13355
13356static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013357unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013358/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013359{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361}
13362
INADA Naoki3ae20562017-01-16 20:41:20 +090013363/*[clinic input]
13364str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013365
INADA Naoki3ae20562017-01-16 20:41:20 +090013366Return a copy of the string converted to uppercase.
13367[clinic start generated code]*/
13368
13369static PyObject *
13370unicode_upper_impl(PyObject *self)
13371/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013372{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013373 if (PyUnicode_READY(self) == -1)
13374 return NULL;
13375 if (PyUnicode_IS_ASCII(self))
13376 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013377 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013378}
13379
INADA Naoki3ae20562017-01-16 20:41:20 +090013380/*[clinic input]
13381str.zfill as unicode_zfill
13382
13383 width: Py_ssize_t
13384 /
13385
13386Pad a numeric string with zeros on the left, to fill a field of the given width.
13387
13388The string is never truncated.
13389[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013390
13391static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013392unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013393/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013394{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013395 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013396 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013397 int kind;
13398 void *data;
13399 Py_UCS4 chr;
13400
Benjamin Petersonbac79492012-01-14 13:34:47 -050013401 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013402 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013403
Victor Stinnerc4b49542011-12-11 22:44:26 +010013404 if (PyUnicode_GET_LENGTH(self) >= width)
13405 return unicode_result_unchanged(self);
13406
13407 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013408
13409 u = pad(self, fill, 0, '0');
13410
Walter Dörwald068325e2002-04-15 13:36:47 +000013411 if (u == NULL)
13412 return NULL;
13413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013414 kind = PyUnicode_KIND(u);
13415 data = PyUnicode_DATA(u);
13416 chr = PyUnicode_READ(kind, data, fill);
13417
13418 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013419 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013420 PyUnicode_WRITE(kind, data, 0, chr);
13421 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422 }
13423
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013424 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013425 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013427
13428#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013429static PyObject *
13430unicode__decimal2ascii(PyObject *self)
13431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013432 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013433}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013434#endif
13435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013436PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013438\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013439Return True if S starts with the specified prefix, False otherwise.\n\
13440With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013441With optional end, stop comparing S at that position.\n\
13442prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013443
13444static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013445unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013446 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013447{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013448 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013449 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013450 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013451 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013452 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013453
Jesus Ceaac451502011-04-20 17:09:23 +020013454 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013455 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013456 if (PyTuple_Check(subobj)) {
13457 Py_ssize_t i;
13458 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013459 substring = PyTuple_GET_ITEM(subobj, i);
13460 if (!PyUnicode_Check(substring)) {
13461 PyErr_Format(PyExc_TypeError,
13462 "tuple for startswith must only contain str, "
13463 "not %.100s",
13464 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013465 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013466 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013467 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013468 if (result == -1)
13469 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013470 if (result) {
13471 Py_RETURN_TRUE;
13472 }
13473 }
13474 /* nothing matched */
13475 Py_RETURN_FALSE;
13476 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013477 if (!PyUnicode_Check(subobj)) {
13478 PyErr_Format(PyExc_TypeError,
13479 "startswith first arg must be str or "
13480 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013482 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013483 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013484 if (result == -1)
13485 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013486 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013487}
13488
13489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013490PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013491 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013492\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013493Return True if S ends with the specified suffix, False otherwise.\n\
13494With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013495With optional end, stop comparing S at that position.\n\
13496suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013497
13498static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013499unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013500 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013501{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013502 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013503 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013504 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013505 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013506 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013507
Jesus Ceaac451502011-04-20 17:09:23 +020013508 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013509 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013510 if (PyTuple_Check(subobj)) {
13511 Py_ssize_t i;
13512 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013513 substring = PyTuple_GET_ITEM(subobj, i);
13514 if (!PyUnicode_Check(substring)) {
13515 PyErr_Format(PyExc_TypeError,
13516 "tuple for endswith must only contain str, "
13517 "not %.100s",
13518 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013519 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013520 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013521 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013522 if (result == -1)
13523 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013524 if (result) {
13525 Py_RETURN_TRUE;
13526 }
13527 }
13528 Py_RETURN_FALSE;
13529 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013530 if (!PyUnicode_Check(subobj)) {
13531 PyErr_Format(PyExc_TypeError,
13532 "endswith first arg must be str or "
13533 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013535 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013536 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013537 if (result == -1)
13538 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013539 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013540}
13541
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013542static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013543_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013544{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013545 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13546 writer->data = PyUnicode_DATA(writer->buffer);
13547
13548 if (!writer->readonly) {
13549 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013550 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013551 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013552 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013553 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13554 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13555 writer->kind = PyUnicode_WCHAR_KIND;
13556 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13557
Victor Stinner8f674cc2013-04-17 23:02:17 +020013558 /* Copy-on-write mode: set buffer size to 0 so
13559 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13560 * next write. */
13561 writer->size = 0;
13562 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013563}
13564
Victor Stinnerd3f08822012-05-29 12:57:52 +020013565void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013566_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013567{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013568 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013569
13570 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013571 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013572
13573 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13574 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13575 writer->kind = PyUnicode_WCHAR_KIND;
13576 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013577}
13578
Victor Stinnerd3f08822012-05-29 12:57:52 +020013579int
13580_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13581 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013582{
13583 Py_ssize_t newlen;
13584 PyObject *newbuffer;
13585
Victor Stinner2740e462016-09-06 16:58:36 -070013586 assert(maxchar <= MAX_UNICODE);
13587
Victor Stinnerca9381e2015-09-22 00:58:32 +020013588 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013589 assert((maxchar > writer->maxchar && length >= 0)
13590 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013591
Victor Stinner202fdca2012-05-07 12:47:02 +020013592 if (length > PY_SSIZE_T_MAX - writer->pos) {
13593 PyErr_NoMemory();
13594 return -1;
13595 }
13596 newlen = writer->pos + length;
13597
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013598 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013599
Victor Stinnerd3f08822012-05-29 12:57:52 +020013600 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013601 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013602 if (writer->overallocate
13603 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13604 /* overallocate to limit the number of realloc() */
13605 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013606 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013607 if (newlen < writer->min_length)
13608 newlen = writer->min_length;
13609
Victor Stinnerd3f08822012-05-29 12:57:52 +020013610 writer->buffer = PyUnicode_New(newlen, maxchar);
13611 if (writer->buffer == NULL)
13612 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013613 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013614 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013615 if (writer->overallocate
13616 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13617 /* overallocate to limit the number of realloc() */
13618 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013619 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013620 if (newlen < writer->min_length)
13621 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013622
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013623 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013624 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013625 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013626 newbuffer = PyUnicode_New(newlen, maxchar);
13627 if (newbuffer == NULL)
13628 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013629 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13630 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013631 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013632 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013633 }
13634 else {
13635 newbuffer = resize_compact(writer->buffer, newlen);
13636 if (newbuffer == NULL)
13637 return -1;
13638 }
13639 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013640 }
13641 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013642 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013643 newbuffer = PyUnicode_New(writer->size, maxchar);
13644 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013645 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013646 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13647 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013648 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013649 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013650 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013651 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013652
13653#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013654}
13655
Victor Stinnerca9381e2015-09-22 00:58:32 +020013656int
13657_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13658 enum PyUnicode_Kind kind)
13659{
13660 Py_UCS4 maxchar;
13661
13662 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13663 assert(writer->kind < kind);
13664
13665 switch (kind)
13666 {
13667 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13668 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13669 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13670 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013671 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013672 }
13673
13674 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13675}
13676
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013677static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013678_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013679{
Victor Stinner2740e462016-09-06 16:58:36 -070013680 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013681 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13682 return -1;
13683 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13684 writer->pos++;
13685 return 0;
13686}
13687
13688int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013689_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13690{
13691 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13692}
13693
13694int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013695_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13696{
13697 Py_UCS4 maxchar;
13698 Py_ssize_t len;
13699
13700 if (PyUnicode_READY(str) == -1)
13701 return -1;
13702 len = PyUnicode_GET_LENGTH(str);
13703 if (len == 0)
13704 return 0;
13705 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13706 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013707 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013708 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013709 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013710 Py_INCREF(str);
13711 writer->buffer = str;
13712 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013713 writer->pos += len;
13714 return 0;
13715 }
13716 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13717 return -1;
13718 }
13719 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13720 str, 0, len);
13721 writer->pos += len;
13722 return 0;
13723}
13724
Victor Stinnere215d962012-10-06 23:03:36 +020013725int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013726_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13727 Py_ssize_t start, Py_ssize_t end)
13728{
13729 Py_UCS4 maxchar;
13730 Py_ssize_t len;
13731
13732 if (PyUnicode_READY(str) == -1)
13733 return -1;
13734
13735 assert(0 <= start);
13736 assert(end <= PyUnicode_GET_LENGTH(str));
13737 assert(start <= end);
13738
13739 if (end == 0)
13740 return 0;
13741
13742 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13743 return _PyUnicodeWriter_WriteStr(writer, str);
13744
13745 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13746 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13747 else
13748 maxchar = writer->maxchar;
13749 len = end - start;
13750
13751 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13752 return -1;
13753
13754 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13755 str, start, len);
13756 writer->pos += len;
13757 return 0;
13758}
13759
13760int
Victor Stinner4a587072013-11-19 12:54:53 +010013761_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13762 const char *ascii, Py_ssize_t len)
13763{
13764 if (len == -1)
13765 len = strlen(ascii);
13766
13767 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13768
13769 if (writer->buffer == NULL && !writer->overallocate) {
13770 PyObject *str;
13771
13772 str = _PyUnicode_FromASCII(ascii, len);
13773 if (str == NULL)
13774 return -1;
13775
13776 writer->readonly = 1;
13777 writer->buffer = str;
13778 _PyUnicodeWriter_Update(writer);
13779 writer->pos += len;
13780 return 0;
13781 }
13782
13783 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13784 return -1;
13785
13786 switch (writer->kind)
13787 {
13788 case PyUnicode_1BYTE_KIND:
13789 {
13790 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13791 Py_UCS1 *data = writer->data;
13792
Christian Heimesf051e432016-09-13 20:22:02 +020013793 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013794 break;
13795 }
13796 case PyUnicode_2BYTE_KIND:
13797 {
13798 _PyUnicode_CONVERT_BYTES(
13799 Py_UCS1, Py_UCS2,
13800 ascii, ascii + len,
13801 (Py_UCS2 *)writer->data + writer->pos);
13802 break;
13803 }
13804 case PyUnicode_4BYTE_KIND:
13805 {
13806 _PyUnicode_CONVERT_BYTES(
13807 Py_UCS1, Py_UCS4,
13808 ascii, ascii + len,
13809 (Py_UCS4 *)writer->data + writer->pos);
13810 break;
13811 }
13812 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013813 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013814 }
13815
13816 writer->pos += len;
13817 return 0;
13818}
13819
13820int
13821_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13822 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013823{
13824 Py_UCS4 maxchar;
13825
13826 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13827 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13828 return -1;
13829 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13830 writer->pos += len;
13831 return 0;
13832}
13833
Victor Stinnerd3f08822012-05-29 12:57:52 +020013834PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013835_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013836{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013837 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013838
Victor Stinnerd3f08822012-05-29 12:57:52 +020013839 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013840 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013841 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013842 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013843
13844 str = writer->buffer;
13845 writer->buffer = NULL;
13846
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013847 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013848 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13849 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013851
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013852 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13853 PyObject *str2;
13854 str2 = resize_compact(str, writer->pos);
13855 if (str2 == NULL) {
13856 Py_DECREF(str);
13857 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013858 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013859 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013860 }
13861
Victor Stinner15a0bd32013-07-08 22:29:55 +020013862 assert(_PyUnicode_CheckConsistency(str, 1));
13863 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013864}
13865
Victor Stinnerd3f08822012-05-29 12:57:52 +020013866void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013867_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013868{
13869 Py_CLEAR(writer->buffer);
13870}
13871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013872#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013873
13874PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013875 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013876\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013877Return a formatted version of S, using substitutions from args and kwargs.\n\
13878The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013879
Eric Smith27bbca62010-11-04 17:06:58 +000013880PyDoc_STRVAR(format_map__doc__,
13881 "S.format_map(mapping) -> str\n\
13882\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013883Return a formatted version of S, using substitutions from mapping.\n\
13884The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013885
INADA Naoki3ae20562017-01-16 20:41:20 +090013886/*[clinic input]
13887str.__format__ as unicode___format__
13888
13889 format_spec: unicode
13890 /
13891
13892Return a formatted version of the string as described by format_spec.
13893[clinic start generated code]*/
13894
Eric Smith4a7d76d2008-05-30 18:10:19 +000013895static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013896unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013897/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013898{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013899 _PyUnicodeWriter writer;
13900 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013901
Victor Stinnerd3f08822012-05-29 12:57:52 +020013902 if (PyUnicode_READY(self) == -1)
13903 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013904 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013905 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13906 self, format_spec, 0,
13907 PyUnicode_GET_LENGTH(format_spec));
13908 if (ret == -1) {
13909 _PyUnicodeWriter_Dealloc(&writer);
13910 return NULL;
13911 }
13912 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013913}
13914
INADA Naoki3ae20562017-01-16 20:41:20 +090013915/*[clinic input]
13916str.__sizeof__ as unicode_sizeof
13917
13918Return the size of the string in memory, in bytes.
13919[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013920
13921static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013922unicode_sizeof_impl(PyObject *self)
13923/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013924{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013925 Py_ssize_t size;
13926
13927 /* If it's a compact object, account for base structure +
13928 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013929 if (PyUnicode_IS_COMPACT_ASCII(self))
13930 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13931 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013932 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013933 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013934 else {
13935 /* If it is a two-block object, account for base object, and
13936 for character block if present. */
13937 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013938 if (_PyUnicode_DATA_ANY(self))
13939 size += (PyUnicode_GET_LENGTH(self) + 1) *
13940 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013941 }
13942 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013943 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013944 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13945 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13946 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13947 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013948
13949 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013950}
13951
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013952static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013953unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013954{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013955 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013956 if (!copy)
13957 return NULL;
13958 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013959}
13960
Guido van Rossumd57fd912000-03-10 22:53:23 +000013961static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013962 UNICODE_ENCODE_METHODDEF
13963 UNICODE_REPLACE_METHODDEF
13964 UNICODE_SPLIT_METHODDEF
13965 UNICODE_RSPLIT_METHODDEF
13966 UNICODE_JOIN_METHODDEF
13967 UNICODE_CAPITALIZE_METHODDEF
13968 UNICODE_CASEFOLD_METHODDEF
13969 UNICODE_TITLE_METHODDEF
13970 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013971 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013972 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013973 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013974 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013975 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013976 UNICODE_LJUST_METHODDEF
13977 UNICODE_LOWER_METHODDEF
13978 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013979 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13980 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013981 UNICODE_RJUST_METHODDEF
13982 UNICODE_RSTRIP_METHODDEF
13983 UNICODE_RPARTITION_METHODDEF
13984 UNICODE_SPLITLINES_METHODDEF
13985 UNICODE_STRIP_METHODDEF
13986 UNICODE_SWAPCASE_METHODDEF
13987 UNICODE_TRANSLATE_METHODDEF
13988 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013989 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13990 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013991 UNICODE_ISLOWER_METHODDEF
13992 UNICODE_ISUPPER_METHODDEF
13993 UNICODE_ISTITLE_METHODDEF
13994 UNICODE_ISSPACE_METHODDEF
13995 UNICODE_ISDECIMAL_METHODDEF
13996 UNICODE_ISDIGIT_METHODDEF
13997 UNICODE_ISNUMERIC_METHODDEF
13998 UNICODE_ISALPHA_METHODDEF
13999 UNICODE_ISALNUM_METHODDEF
14000 UNICODE_ISIDENTIFIER_METHODDEF
14001 UNICODE_ISPRINTABLE_METHODDEF
14002 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000014003 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000014004 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014005 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070014006 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090014007 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000014008#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014009 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014010 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014011#endif
14012
Benjamin Peterson14339b62009-01-31 16:36:08 +000014013 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014014 {NULL, NULL}
14015};
14016
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014017static PyObject *
14018unicode_mod(PyObject *v, PyObject *w)
14019{
Brian Curtindfc80e32011-08-10 20:28:54 -050014020 if (!PyUnicode_Check(v))
14021 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000014022 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014023}
14024
14025static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014026 0, /*nb_add*/
14027 0, /*nb_subtract*/
14028 0, /*nb_multiply*/
14029 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014030};
14031
Guido van Rossumd57fd912000-03-10 22:53:23 +000014032static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014033 (lenfunc) unicode_length, /* sq_length */
14034 PyUnicode_Concat, /* sq_concat */
14035 (ssizeargfunc) unicode_repeat, /* sq_repeat */
14036 (ssizeargfunc) unicode_getitem, /* sq_item */
14037 0, /* sq_slice */
14038 0, /* sq_ass_item */
14039 0, /* sq_ass_slice */
14040 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014041};
14042
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014043static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014044unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014045{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014046 if (PyUnicode_READY(self) == -1)
14047 return NULL;
14048
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000014049 if (PyIndex_Check(item)) {
14050 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014051 if (i == -1 && PyErr_Occurred())
14052 return NULL;
14053 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014054 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014055 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014056 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000014057 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014058 PyObject *result;
14059 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014060 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014061 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014062
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014063 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014064 return NULL;
14065 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014066 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14067 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014068
14069 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014070 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014071 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014072 slicelength == PyUnicode_GET_LENGTH(self)) {
14073 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014074 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014075 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014076 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014077 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014078 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014079 src_kind = PyUnicode_KIND(self);
14080 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014081 if (!PyUnicode_IS_ASCII(self)) {
14082 kind_limit = kind_maxchar_limit(src_kind);
14083 max_char = 0;
14084 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14085 ch = PyUnicode_READ(src_kind, src_data, cur);
14086 if (ch > max_char) {
14087 max_char = ch;
14088 if (max_char >= kind_limit)
14089 break;
14090 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014091 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014092 }
Victor Stinner55c99112011-10-13 01:17:06 +020014093 else
14094 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014095 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014096 if (result == NULL)
14097 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014098 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014099 dest_data = PyUnicode_DATA(result);
14100
14101 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014102 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14103 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014104 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014105 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014106 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014107 } else {
14108 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14109 return NULL;
14110 }
14111}
14112
14113static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014114 (lenfunc)unicode_length, /* mp_length */
14115 (binaryfunc)unicode_subscript, /* mp_subscript */
14116 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014117};
14118
Guido van Rossumd57fd912000-03-10 22:53:23 +000014119
Guido van Rossumd57fd912000-03-10 22:53:23 +000014120/* Helpers for PyUnicode_Format() */
14121
Victor Stinnera47082312012-10-04 02:19:54 +020014122struct unicode_formatter_t {
14123 PyObject *args;
14124 int args_owned;
14125 Py_ssize_t arglen, argidx;
14126 PyObject *dict;
14127
14128 enum PyUnicode_Kind fmtkind;
14129 Py_ssize_t fmtcnt, fmtpos;
14130 void *fmtdata;
14131 PyObject *fmtstr;
14132
14133 _PyUnicodeWriter writer;
14134};
14135
14136struct unicode_format_arg_t {
14137 Py_UCS4 ch;
14138 int flags;
14139 Py_ssize_t width;
14140 int prec;
14141 int sign;
14142};
14143
Guido van Rossumd57fd912000-03-10 22:53:23 +000014144static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014145unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014146{
Victor Stinnera47082312012-10-04 02:19:54 +020014147 Py_ssize_t argidx = ctx->argidx;
14148
14149 if (argidx < ctx->arglen) {
14150 ctx->argidx++;
14151 if (ctx->arglen < 0)
14152 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014153 else
Victor Stinnera47082312012-10-04 02:19:54 +020014154 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014155 }
14156 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014157 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014158 return NULL;
14159}
14160
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014161/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014162
Victor Stinnera47082312012-10-04 02:19:54 +020014163/* Format a float into the writer if the writer is not NULL, or into *p_output
14164 otherwise.
14165
14166 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014167static int
Victor Stinnera47082312012-10-04 02:19:54 +020014168formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14169 PyObject **p_output,
14170 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014171{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014172 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014173 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014174 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014175 int prec;
14176 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014177
Guido van Rossumd57fd912000-03-10 22:53:23 +000014178 x = PyFloat_AsDouble(v);
14179 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014180 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014181
Victor Stinnera47082312012-10-04 02:19:54 +020014182 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014183 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014184 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014185
Victor Stinnera47082312012-10-04 02:19:54 +020014186 if (arg->flags & F_ALT)
14187 dtoa_flags = Py_DTSF_ALT;
14188 else
14189 dtoa_flags = 0;
14190 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014191 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014192 return -1;
14193 len = strlen(p);
14194 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014195 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014196 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014197 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014198 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014199 }
14200 else
14201 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014202 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014203 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014204}
14205
Victor Stinnerd0880d52012-04-27 23:40:13 +020014206/* formatlong() emulates the format codes d, u, o, x and X, and
14207 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14208 * Python's regular ints.
14209 * Return value: a new PyUnicodeObject*, or NULL if error.
14210 * The output string is of the form
14211 * "-"? ("0x" | "0X")? digit+
14212 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14213 * set in flags. The case of hex digits will be correct,
14214 * There will be at least prec digits, zero-filled on the left if
14215 * necessary to get that many.
14216 * val object to be converted
14217 * flags bitmask of format flags; only F_ALT is looked at
14218 * prec minimum number of digits; 0-fill on left if needed
14219 * type a character in [duoxX]; u acts the same as d
14220 *
14221 * CAUTION: o, x and X conversions on regular ints can never
14222 * produce a '-' sign, but can for Python's unbounded ints.
14223 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014224PyObject *
14225_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014226{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014227 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014228 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014229 Py_ssize_t i;
14230 int sign; /* 1 if '-', else 0 */
14231 int len; /* number of characters */
14232 Py_ssize_t llen;
14233 int numdigits; /* len == numnondigits + numdigits */
14234 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014235
Victor Stinnerd0880d52012-04-27 23:40:13 +020014236 /* Avoid exceeding SSIZE_T_MAX */
14237 if (prec > INT_MAX-3) {
14238 PyErr_SetString(PyExc_OverflowError,
14239 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014240 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014241 }
14242
14243 assert(PyLong_Check(val));
14244
14245 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014246 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014247 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014248 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014250 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014251 /* int and int subclasses should print numerically when a numeric */
14252 /* format code is used (see issue18780) */
14253 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014254 break;
14255 case 'o':
14256 numnondigits = 2;
14257 result = PyNumber_ToBase(val, 8);
14258 break;
14259 case 'x':
14260 case 'X':
14261 numnondigits = 2;
14262 result = PyNumber_ToBase(val, 16);
14263 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014264 }
14265 if (!result)
14266 return NULL;
14267
14268 assert(unicode_modifiable(result));
14269 assert(PyUnicode_IS_READY(result));
14270 assert(PyUnicode_IS_ASCII(result));
14271
14272 /* To modify the string in-place, there can only be one reference. */
14273 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014274 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014275 PyErr_BadInternalCall();
14276 return NULL;
14277 }
14278 buf = PyUnicode_DATA(result);
14279 llen = PyUnicode_GET_LENGTH(result);
14280 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014281 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014282 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014283 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014284 return NULL;
14285 }
14286 len = (int)llen;
14287 sign = buf[0] == '-';
14288 numnondigits += sign;
14289 numdigits = len - numnondigits;
14290 assert(numdigits > 0);
14291
14292 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014293 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014294 (type == 'o' || type == 'x' || type == 'X'))) {
14295 assert(buf[sign] == '0');
14296 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14297 buf[sign+1] == 'o');
14298 numnondigits -= 2;
14299 buf += 2;
14300 len -= 2;
14301 if (sign)
14302 buf[0] = '-';
14303 assert(len == numnondigits + numdigits);
14304 assert(numdigits > 0);
14305 }
14306
14307 /* Fill with leading zeroes to meet minimum width. */
14308 if (prec > numdigits) {
14309 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14310 numnondigits + prec);
14311 char *b1;
14312 if (!r1) {
14313 Py_DECREF(result);
14314 return NULL;
14315 }
14316 b1 = PyBytes_AS_STRING(r1);
14317 for (i = 0; i < numnondigits; ++i)
14318 *b1++ = *buf++;
14319 for (i = 0; i < prec - numdigits; i++)
14320 *b1++ = '0';
14321 for (i = 0; i < numdigits; i++)
14322 *b1++ = *buf++;
14323 *b1 = '\0';
14324 Py_DECREF(result);
14325 result = r1;
14326 buf = PyBytes_AS_STRING(result);
14327 len = numnondigits + prec;
14328 }
14329
14330 /* Fix up case for hex conversions. */
14331 if (type == 'X') {
14332 /* Need to convert all lower case letters to upper case.
14333 and need to convert 0x to 0X (and -0x to -0X). */
14334 for (i = 0; i < len; i++)
14335 if (buf[i] >= 'a' && buf[i] <= 'x')
14336 buf[i] -= 'a'-'A';
14337 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014338 if (!PyUnicode_Check(result)
14339 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014340 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014341 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014342 Py_DECREF(result);
14343 result = unicode;
14344 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014345 else if (len != PyUnicode_GET_LENGTH(result)) {
14346 if (PyUnicode_Resize(&result, len) < 0)
14347 Py_CLEAR(result);
14348 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014349 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014350}
14351
Ethan Furmandf3ed242014-01-05 06:50:30 -080014352/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014353 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014354 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014355 * -1 and raise an exception on error */
14356static int
Victor Stinnera47082312012-10-04 02:19:54 +020014357mainformatlong(PyObject *v,
14358 struct unicode_format_arg_t *arg,
14359 PyObject **p_output,
14360 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014361{
14362 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014363 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014364
14365 if (!PyNumber_Check(v))
14366 goto wrongtype;
14367
Ethan Furman9ab74802014-03-21 06:38:46 -070014368 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014369 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014370 if (type == 'o' || type == 'x' || type == 'X') {
14371 iobj = PyNumber_Index(v);
14372 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014373 if (PyErr_ExceptionMatches(PyExc_TypeError))
14374 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014375 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014376 }
14377 }
14378 else {
14379 iobj = PyNumber_Long(v);
14380 if (iobj == NULL ) {
14381 if (PyErr_ExceptionMatches(PyExc_TypeError))
14382 goto wrongtype;
14383 return -1;
14384 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014385 }
14386 assert(PyLong_Check(iobj));
14387 }
14388 else {
14389 iobj = v;
14390 Py_INCREF(iobj);
14391 }
14392
14393 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014394 && arg->width == -1 && arg->prec == -1
14395 && !(arg->flags & (F_SIGN | F_BLANK))
14396 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014397 {
14398 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014399 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014400 int base;
14401
Victor Stinnera47082312012-10-04 02:19:54 +020014402 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014403 {
14404 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014405 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014406 case 'd':
14407 case 'i':
14408 case 'u':
14409 base = 10;
14410 break;
14411 case 'o':
14412 base = 8;
14413 break;
14414 case 'x':
14415 case 'X':
14416 base = 16;
14417 break;
14418 }
14419
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014420 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14421 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014422 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014423 }
14424 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014425 return 1;
14426 }
14427
Ethan Furmanb95b5612015-01-23 20:05:18 -080014428 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014429 Py_DECREF(iobj);
14430 if (res == NULL)
14431 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014432 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014433 return 0;
14434
14435wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014436 switch(type)
14437 {
14438 case 'o':
14439 case 'x':
14440 case 'X':
14441 PyErr_Format(PyExc_TypeError,
14442 "%%%c format: an integer is required, "
14443 "not %.200s",
14444 type, Py_TYPE(v)->tp_name);
14445 break;
14446 default:
14447 PyErr_Format(PyExc_TypeError,
14448 "%%%c format: a number is required, "
14449 "not %.200s",
14450 type, Py_TYPE(v)->tp_name);
14451 break;
14452 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014453 return -1;
14454}
14455
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014456static Py_UCS4
14457formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014458{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014459 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014460 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014461 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014462 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014463 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014464 goto onError;
14465 }
14466 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014467 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014468 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014469 /* make sure number is a type of integer */
14470 if (!PyLong_Check(v)) {
14471 iobj = PyNumber_Index(v);
14472 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014473 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014474 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014475 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014476 Py_DECREF(iobj);
14477 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014478 else {
14479 x = PyLong_AsLong(v);
14480 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014481 if (x == -1 && PyErr_Occurred())
14482 goto onError;
14483
Victor Stinner8faf8212011-12-08 22:14:11 +010014484 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014485 PyErr_SetString(PyExc_OverflowError,
14486 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014487 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014488 }
14489
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014490 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014491 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014492
Benjamin Peterson29060642009-01-31 22:14:21 +000014493 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014494 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014495 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014496 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014497}
14498
Victor Stinnera47082312012-10-04 02:19:54 +020014499/* Parse options of an argument: flags, width, precision.
14500 Handle also "%(name)" syntax.
14501
14502 Return 0 if the argument has been formatted into arg->str.
14503 Return 1 if the argument has been written into ctx->writer,
14504 Raise an exception and return -1 on error. */
14505static int
14506unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14507 struct unicode_format_arg_t *arg)
14508{
14509#define FORMAT_READ(ctx) \
14510 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14511
14512 PyObject *v;
14513
Victor Stinnera47082312012-10-04 02:19:54 +020014514 if (arg->ch == '(') {
14515 /* Get argument value from a dictionary. Example: "%(name)s". */
14516 Py_ssize_t keystart;
14517 Py_ssize_t keylen;
14518 PyObject *key;
14519 int pcount = 1;
14520
14521 if (ctx->dict == NULL) {
14522 PyErr_SetString(PyExc_TypeError,
14523 "format requires a mapping");
14524 return -1;
14525 }
14526 ++ctx->fmtpos;
14527 --ctx->fmtcnt;
14528 keystart = ctx->fmtpos;
14529 /* Skip over balanced parentheses */
14530 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14531 arg->ch = FORMAT_READ(ctx);
14532 if (arg->ch == ')')
14533 --pcount;
14534 else if (arg->ch == '(')
14535 ++pcount;
14536 ctx->fmtpos++;
14537 }
14538 keylen = ctx->fmtpos - keystart - 1;
14539 if (ctx->fmtcnt < 0 || pcount > 0) {
14540 PyErr_SetString(PyExc_ValueError,
14541 "incomplete format key");
14542 return -1;
14543 }
14544 key = PyUnicode_Substring(ctx->fmtstr,
14545 keystart, keystart + keylen);
14546 if (key == NULL)
14547 return -1;
14548 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014549 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014550 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014551 }
14552 ctx->args = PyObject_GetItem(ctx->dict, key);
14553 Py_DECREF(key);
14554 if (ctx->args == NULL)
14555 return -1;
14556 ctx->args_owned = 1;
14557 ctx->arglen = -1;
14558 ctx->argidx = -2;
14559 }
14560
14561 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014562 while (--ctx->fmtcnt >= 0) {
14563 arg->ch = FORMAT_READ(ctx);
14564 ctx->fmtpos++;
14565 switch (arg->ch) {
14566 case '-': arg->flags |= F_LJUST; continue;
14567 case '+': arg->flags |= F_SIGN; continue;
14568 case ' ': arg->flags |= F_BLANK; continue;
14569 case '#': arg->flags |= F_ALT; continue;
14570 case '0': arg->flags |= F_ZERO; continue;
14571 }
14572 break;
14573 }
14574
14575 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014576 if (arg->ch == '*') {
14577 v = unicode_format_getnextarg(ctx);
14578 if (v == NULL)
14579 return -1;
14580 if (!PyLong_Check(v)) {
14581 PyErr_SetString(PyExc_TypeError,
14582 "* wants int");
14583 return -1;
14584 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014585 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014586 if (arg->width == -1 && PyErr_Occurred())
14587 return -1;
14588 if (arg->width < 0) {
14589 arg->flags |= F_LJUST;
14590 arg->width = -arg->width;
14591 }
14592 if (--ctx->fmtcnt >= 0) {
14593 arg->ch = FORMAT_READ(ctx);
14594 ctx->fmtpos++;
14595 }
14596 }
14597 else if (arg->ch >= '0' && arg->ch <= '9') {
14598 arg->width = arg->ch - '0';
14599 while (--ctx->fmtcnt >= 0) {
14600 arg->ch = FORMAT_READ(ctx);
14601 ctx->fmtpos++;
14602 if (arg->ch < '0' || arg->ch > '9')
14603 break;
14604 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14605 mixing signed and unsigned comparison. Since arg->ch is between
14606 '0' and '9', casting to int is safe. */
14607 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14608 PyErr_SetString(PyExc_ValueError,
14609 "width too big");
14610 return -1;
14611 }
14612 arg->width = arg->width*10 + (arg->ch - '0');
14613 }
14614 }
14615
14616 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014617 if (arg->ch == '.') {
14618 arg->prec = 0;
14619 if (--ctx->fmtcnt >= 0) {
14620 arg->ch = FORMAT_READ(ctx);
14621 ctx->fmtpos++;
14622 }
14623 if (arg->ch == '*') {
14624 v = unicode_format_getnextarg(ctx);
14625 if (v == NULL)
14626 return -1;
14627 if (!PyLong_Check(v)) {
14628 PyErr_SetString(PyExc_TypeError,
14629 "* wants int");
14630 return -1;
14631 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014632 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014633 if (arg->prec == -1 && PyErr_Occurred())
14634 return -1;
14635 if (arg->prec < 0)
14636 arg->prec = 0;
14637 if (--ctx->fmtcnt >= 0) {
14638 arg->ch = FORMAT_READ(ctx);
14639 ctx->fmtpos++;
14640 }
14641 }
14642 else if (arg->ch >= '0' && arg->ch <= '9') {
14643 arg->prec = arg->ch - '0';
14644 while (--ctx->fmtcnt >= 0) {
14645 arg->ch = FORMAT_READ(ctx);
14646 ctx->fmtpos++;
14647 if (arg->ch < '0' || arg->ch > '9')
14648 break;
14649 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14650 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014651 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014652 return -1;
14653 }
14654 arg->prec = arg->prec*10 + (arg->ch - '0');
14655 }
14656 }
14657 }
14658
14659 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14660 if (ctx->fmtcnt >= 0) {
14661 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14662 if (--ctx->fmtcnt >= 0) {
14663 arg->ch = FORMAT_READ(ctx);
14664 ctx->fmtpos++;
14665 }
14666 }
14667 }
14668 if (ctx->fmtcnt < 0) {
14669 PyErr_SetString(PyExc_ValueError,
14670 "incomplete format");
14671 return -1;
14672 }
14673 return 0;
14674
14675#undef FORMAT_READ
14676}
14677
14678/* Format one argument. Supported conversion specifiers:
14679
14680 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014681 - "i", "d", "u": int or float
14682 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014683 - "e", "E", "f", "F", "g", "G": float
14684 - "c": int or str (1 character)
14685
Victor Stinner8dbd4212012-12-04 09:30:24 +010014686 When possible, the output is written directly into the Unicode writer
14687 (ctx->writer). A string is created when padding is required.
14688
Victor Stinnera47082312012-10-04 02:19:54 +020014689 Return 0 if the argument has been formatted into *p_str,
14690 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014691 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014692static int
14693unicode_format_arg_format(struct unicode_formatter_t *ctx,
14694 struct unicode_format_arg_t *arg,
14695 PyObject **p_str)
14696{
14697 PyObject *v;
14698 _PyUnicodeWriter *writer = &ctx->writer;
14699
14700 if (ctx->fmtcnt == 0)
14701 ctx->writer.overallocate = 0;
14702
Victor Stinnera47082312012-10-04 02:19:54 +020014703 v = unicode_format_getnextarg(ctx);
14704 if (v == NULL)
14705 return -1;
14706
Victor Stinnera47082312012-10-04 02:19:54 +020014707
14708 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014709 case 's':
14710 case 'r':
14711 case 'a':
14712 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14713 /* Fast path */
14714 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14715 return -1;
14716 return 1;
14717 }
14718
14719 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14720 *p_str = v;
14721 Py_INCREF(*p_str);
14722 }
14723 else {
14724 if (arg->ch == 's')
14725 *p_str = PyObject_Str(v);
14726 else if (arg->ch == 'r')
14727 *p_str = PyObject_Repr(v);
14728 else
14729 *p_str = PyObject_ASCII(v);
14730 }
14731 break;
14732
14733 case 'i':
14734 case 'd':
14735 case 'u':
14736 case 'o':
14737 case 'x':
14738 case 'X':
14739 {
14740 int ret = mainformatlong(v, arg, p_str, writer);
14741 if (ret != 0)
14742 return ret;
14743 arg->sign = 1;
14744 break;
14745 }
14746
14747 case 'e':
14748 case 'E':
14749 case 'f':
14750 case 'F':
14751 case 'g':
14752 case 'G':
14753 if (arg->width == -1 && arg->prec == -1
14754 && !(arg->flags & (F_SIGN | F_BLANK)))
14755 {
14756 /* Fast path */
14757 if (formatfloat(v, arg, NULL, writer) == -1)
14758 return -1;
14759 return 1;
14760 }
14761
14762 arg->sign = 1;
14763 if (formatfloat(v, arg, p_str, NULL) == -1)
14764 return -1;
14765 break;
14766
14767 case 'c':
14768 {
14769 Py_UCS4 ch = formatchar(v);
14770 if (ch == (Py_UCS4) -1)
14771 return -1;
14772 if (arg->width == -1 && arg->prec == -1) {
14773 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014774 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014775 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014776 return 1;
14777 }
14778 *p_str = PyUnicode_FromOrdinal(ch);
14779 break;
14780 }
14781
14782 default:
14783 PyErr_Format(PyExc_ValueError,
14784 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014785 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014786 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14787 (int)arg->ch,
14788 ctx->fmtpos - 1);
14789 return -1;
14790 }
14791 if (*p_str == NULL)
14792 return -1;
14793 assert (PyUnicode_Check(*p_str));
14794 return 0;
14795}
14796
14797static int
14798unicode_format_arg_output(struct unicode_formatter_t *ctx,
14799 struct unicode_format_arg_t *arg,
14800 PyObject *str)
14801{
14802 Py_ssize_t len;
14803 enum PyUnicode_Kind kind;
14804 void *pbuf;
14805 Py_ssize_t pindex;
14806 Py_UCS4 signchar;
14807 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014808 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014809 Py_ssize_t sublen;
14810 _PyUnicodeWriter *writer = &ctx->writer;
14811 Py_UCS4 fill;
14812
14813 fill = ' ';
14814 if (arg->sign && arg->flags & F_ZERO)
14815 fill = '0';
14816
14817 if (PyUnicode_READY(str) == -1)
14818 return -1;
14819
14820 len = PyUnicode_GET_LENGTH(str);
14821 if ((arg->width == -1 || arg->width <= len)
14822 && (arg->prec == -1 || arg->prec >= len)
14823 && !(arg->flags & (F_SIGN | F_BLANK)))
14824 {
14825 /* Fast path */
14826 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14827 return -1;
14828 return 0;
14829 }
14830
14831 /* Truncate the string for "s", "r" and "a" formats
14832 if the precision is set */
14833 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14834 if (arg->prec >= 0 && len > arg->prec)
14835 len = arg->prec;
14836 }
14837
14838 /* Adjust sign and width */
14839 kind = PyUnicode_KIND(str);
14840 pbuf = PyUnicode_DATA(str);
14841 pindex = 0;
14842 signchar = '\0';
14843 if (arg->sign) {
14844 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14845 if (ch == '-' || ch == '+') {
14846 signchar = ch;
14847 len--;
14848 pindex++;
14849 }
14850 else if (arg->flags & F_SIGN)
14851 signchar = '+';
14852 else if (arg->flags & F_BLANK)
14853 signchar = ' ';
14854 else
14855 arg->sign = 0;
14856 }
14857 if (arg->width < len)
14858 arg->width = len;
14859
14860 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014861 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014862 if (!(arg->flags & F_LJUST)) {
14863 if (arg->sign) {
14864 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014865 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014866 }
14867 else {
14868 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014869 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014870 }
14871 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014872 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14873 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014874 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014875 }
14876
Victor Stinnera47082312012-10-04 02:19:54 +020014877 buflen = arg->width;
14878 if (arg->sign && len == arg->width)
14879 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014880 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014881 return -1;
14882
14883 /* Write the sign if needed */
14884 if (arg->sign) {
14885 if (fill != ' ') {
14886 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14887 writer->pos += 1;
14888 }
14889 if (arg->width > len)
14890 arg->width--;
14891 }
14892
14893 /* Write the numeric prefix for "x", "X" and "o" formats
14894 if the alternate form is used.
14895 For example, write "0x" for the "%#x" format. */
14896 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14897 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14898 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14899 if (fill != ' ') {
14900 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14901 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14902 writer->pos += 2;
14903 pindex += 2;
14904 }
14905 arg->width -= 2;
14906 if (arg->width < 0)
14907 arg->width = 0;
14908 len -= 2;
14909 }
14910
14911 /* Pad left with the fill character if needed */
14912 if (arg->width > len && !(arg->flags & F_LJUST)) {
14913 sublen = arg->width - len;
14914 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14915 writer->pos += sublen;
14916 arg->width = len;
14917 }
14918
14919 /* If padding with spaces: write sign if needed and/or numeric prefix if
14920 the alternate form is used */
14921 if (fill == ' ') {
14922 if (arg->sign) {
14923 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14924 writer->pos += 1;
14925 }
14926 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14927 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14928 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14929 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14930 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14931 writer->pos += 2;
14932 pindex += 2;
14933 }
14934 }
14935
14936 /* Write characters */
14937 if (len) {
14938 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14939 str, pindex, len);
14940 writer->pos += len;
14941 }
14942
14943 /* Pad right with the fill character if needed */
14944 if (arg->width > len) {
14945 sublen = arg->width - len;
14946 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14947 writer->pos += sublen;
14948 }
14949 return 0;
14950}
14951
14952/* Helper of PyUnicode_Format(): format one arg.
14953 Return 0 on success, raise an exception and return -1 on error. */
14954static int
14955unicode_format_arg(struct unicode_formatter_t *ctx)
14956{
14957 struct unicode_format_arg_t arg;
14958 PyObject *str;
14959 int ret;
14960
Victor Stinner8dbd4212012-12-04 09:30:24 +010014961 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014962 if (arg.ch == '%') {
14963 ctx->fmtpos++;
14964 ctx->fmtcnt--;
14965 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14966 return -1;
14967 return 0;
14968 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014969 arg.flags = 0;
14970 arg.width = -1;
14971 arg.prec = -1;
14972 arg.sign = 0;
14973 str = NULL;
14974
Victor Stinnera47082312012-10-04 02:19:54 +020014975 ret = unicode_format_arg_parse(ctx, &arg);
14976 if (ret == -1)
14977 return -1;
14978
14979 ret = unicode_format_arg_format(ctx, &arg, &str);
14980 if (ret == -1)
14981 return -1;
14982
14983 if (ret != 1) {
14984 ret = unicode_format_arg_output(ctx, &arg, str);
14985 Py_DECREF(str);
14986 if (ret == -1)
14987 return -1;
14988 }
14989
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014990 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014991 PyErr_SetString(PyExc_TypeError,
14992 "not all arguments converted during string formatting");
14993 return -1;
14994 }
14995 return 0;
14996}
14997
Alexander Belopolsky40018472011-02-26 01:02:56 +000014998PyObject *
14999PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015000{
Victor Stinnera47082312012-10-04 02:19:54 +020015001 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000015002
Guido van Rossumd57fd912000-03-10 22:53:23 +000015003 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015004 PyErr_BadInternalCall();
15005 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015006 }
Victor Stinnera47082312012-10-04 02:19:54 +020015007
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015008 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015009 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015010
15011 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020015012 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
15013 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
15014 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
15015 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015016
Victor Stinner8f674cc2013-04-17 23:02:17 +020015017 _PyUnicodeWriter_Init(&ctx.writer);
15018 ctx.writer.min_length = ctx.fmtcnt + 100;
15019 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015020
Guido van Rossumd57fd912000-03-10 22:53:23 +000015021 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020015022 ctx.arglen = PyTuple_Size(args);
15023 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015024 }
15025 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015026 ctx.arglen = -1;
15027 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015028 }
Victor Stinnera47082312012-10-04 02:19:54 +020015029 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040015030 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020015031 ctx.dict = args;
15032 else
15033 ctx.dict = NULL;
15034 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015035
Victor Stinnera47082312012-10-04 02:19:54 +020015036 while (--ctx.fmtcnt >= 0) {
15037 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020015038 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020015039
15040 nonfmtpos = ctx.fmtpos++;
15041 while (ctx.fmtcnt >= 0 &&
15042 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
15043 ctx.fmtpos++;
15044 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015045 }
Victor Stinnera47082312012-10-04 02:19:54 +020015046 if (ctx.fmtcnt < 0) {
15047 ctx.fmtpos--;
15048 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020015049 }
Victor Stinneree4544c2012-05-09 22:24:08 +020015050
Victor Stinnercfc4c132013-04-03 01:48:39 +020015051 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
15052 nonfmtpos, ctx.fmtpos) < 0)
15053 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015054 }
15055 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015056 ctx.fmtpos++;
15057 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000015058 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020015059 }
15060 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020015061
Victor Stinnera47082312012-10-04 02:19:54 +020015062 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015063 PyErr_SetString(PyExc_TypeError,
15064 "not all arguments converted during string formatting");
15065 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015066 }
15067
Victor Stinnera47082312012-10-04 02:19:54 +020015068 if (ctx.args_owned) {
15069 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015070 }
Victor Stinnera47082312012-10-04 02:19:54 +020015071 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015072
Benjamin Peterson29060642009-01-31 22:14:21 +000015073 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015074 _PyUnicodeWriter_Dealloc(&ctx.writer);
15075 if (ctx.args_owned) {
15076 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015077 }
15078 return NULL;
15079}
15080
Jeremy Hylton938ace62002-07-17 16:30:39 +000015081static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015082unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15083
Tim Peters6d6c1a32001-08-02 04:15:00 +000015084static PyObject *
15085unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15086{
Benjamin Peterson29060642009-01-31 22:14:21 +000015087 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015088 static char *kwlist[] = {"object", "encoding", "errors", 0};
15089 char *encoding = NULL;
15090 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015091
Benjamin Peterson14339b62009-01-31 16:36:08 +000015092 if (type != &PyUnicode_Type)
15093 return unicode_subtype_new(type, args, kwds);
15094 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015095 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015096 return NULL;
15097 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015098 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015099 if (encoding == NULL && errors == NULL)
15100 return PyObject_Str(x);
15101 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015102 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015103}
15104
Guido van Rossume023fe02001-08-30 03:12:59 +000015105static PyObject *
15106unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15107{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015108 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015109 Py_ssize_t length, char_size;
15110 int share_wstr, share_utf8;
15111 unsigned int kind;
15112 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015113
Benjamin Peterson14339b62009-01-31 16:36:08 +000015114 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015115
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015116 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015117 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015118 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015119 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015120 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015121 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015122 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015123 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015124
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015125 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015126 if (self == NULL) {
15127 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 return NULL;
15129 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015130 kind = PyUnicode_KIND(unicode);
15131 length = PyUnicode_GET_LENGTH(unicode);
15132
15133 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015134#ifdef Py_DEBUG
15135 _PyUnicode_HASH(self) = -1;
15136#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015137 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015138#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015139 _PyUnicode_STATE(self).interned = 0;
15140 _PyUnicode_STATE(self).kind = kind;
15141 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015142 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015143 _PyUnicode_STATE(self).ready = 1;
15144 _PyUnicode_WSTR(self) = NULL;
15145 _PyUnicode_UTF8_LENGTH(self) = 0;
15146 _PyUnicode_UTF8(self) = NULL;
15147 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015148 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015149
15150 share_utf8 = 0;
15151 share_wstr = 0;
15152 if (kind == PyUnicode_1BYTE_KIND) {
15153 char_size = 1;
15154 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15155 share_utf8 = 1;
15156 }
15157 else if (kind == PyUnicode_2BYTE_KIND) {
15158 char_size = 2;
15159 if (sizeof(wchar_t) == 2)
15160 share_wstr = 1;
15161 }
15162 else {
15163 assert(kind == PyUnicode_4BYTE_KIND);
15164 char_size = 4;
15165 if (sizeof(wchar_t) == 4)
15166 share_wstr = 1;
15167 }
15168
15169 /* Ensure we won't overflow the length. */
15170 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15171 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015172 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015173 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015174 data = PyObject_MALLOC((length + 1) * char_size);
15175 if (data == NULL) {
15176 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015177 goto onError;
15178 }
15179
Victor Stinnerc3c74152011-10-02 20:39:55 +020015180 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015181 if (share_utf8) {
15182 _PyUnicode_UTF8_LENGTH(self) = length;
15183 _PyUnicode_UTF8(self) = data;
15184 }
15185 if (share_wstr) {
15186 _PyUnicode_WSTR_LENGTH(self) = length;
15187 _PyUnicode_WSTR(self) = (wchar_t *)data;
15188 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015189
Christian Heimesf051e432016-09-13 20:22:02 +020015190 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015191 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015192 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015193#ifdef Py_DEBUG
15194 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15195#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015196 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015197 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015198
15199onError:
15200 Py_DECREF(unicode);
15201 Py_DECREF(self);
15202 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015203}
15204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015205PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015206"str(object='') -> str\n\
15207str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015208\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015209Create a new string object from the given object. If encoding or\n\
15210errors is specified, then the object must expose a data buffer\n\
15211that will be decoded using the given encoding and error handler.\n\
15212Otherwise, returns the result of object.__str__() (if defined)\n\
15213or repr(object).\n\
15214encoding defaults to sys.getdefaultencoding().\n\
15215errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015216
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015217static PyObject *unicode_iter(PyObject *seq);
15218
Guido van Rossumd57fd912000-03-10 22:53:23 +000015219PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015220 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015221 "str", /* tp_name */
15222 sizeof(PyUnicodeObject), /* tp_size */
15223 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015224 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015225 (destructor)unicode_dealloc, /* tp_dealloc */
15226 0, /* tp_print */
15227 0, /* tp_getattr */
15228 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015229 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015230 unicode_repr, /* tp_repr */
15231 &unicode_as_number, /* tp_as_number */
15232 &unicode_as_sequence, /* tp_as_sequence */
15233 &unicode_as_mapping, /* tp_as_mapping */
15234 (hashfunc) unicode_hash, /* tp_hash*/
15235 0, /* tp_call*/
15236 (reprfunc) unicode_str, /* tp_str */
15237 PyObject_GenericGetAttr, /* tp_getattro */
15238 0, /* tp_setattro */
15239 0, /* tp_as_buffer */
15240 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015241 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015242 unicode_doc, /* tp_doc */
15243 0, /* tp_traverse */
15244 0, /* tp_clear */
15245 PyUnicode_RichCompare, /* tp_richcompare */
15246 0, /* tp_weaklistoffset */
15247 unicode_iter, /* tp_iter */
15248 0, /* tp_iternext */
15249 unicode_methods, /* tp_methods */
15250 0, /* tp_members */
15251 0, /* tp_getset */
15252 &PyBaseObject_Type, /* tp_base */
15253 0, /* tp_dict */
15254 0, /* tp_descr_get */
15255 0, /* tp_descr_set */
15256 0, /* tp_dictoffset */
15257 0, /* tp_init */
15258 0, /* tp_alloc */
15259 unicode_new, /* tp_new */
15260 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015261};
15262
15263/* Initialize the Unicode implementation */
15264
Victor Stinner3a50e702011-10-18 21:21:00 +020015265int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015266{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015267 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015268 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015269 0x000A, /* LINE FEED */
15270 0x000D, /* CARRIAGE RETURN */
15271 0x001C, /* FILE SEPARATOR */
15272 0x001D, /* GROUP SEPARATOR */
15273 0x001E, /* RECORD SEPARATOR */
15274 0x0085, /* NEXT LINE */
15275 0x2028, /* LINE SEPARATOR */
15276 0x2029, /* PARAGRAPH SEPARATOR */
15277 };
15278
Fred Drakee4315f52000-05-09 19:53:39 +000015279 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015280 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015281 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015282 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015283 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015284
Guido van Rossumcacfc072002-05-24 19:01:59 +000015285 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015286 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015287
15288 /* initialize the linebreak bloom filter */
15289 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015290 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015291 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015292
Christian Heimes26532f72013-07-20 14:57:16 +020015293 if (PyType_Ready(&EncodingMapType) < 0)
15294 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015295
Benjamin Petersonc4311282012-10-30 23:21:10 -040015296 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15297 Py_FatalError("Can't initialize field name iterator type");
15298
15299 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15300 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015301
Victor Stinner3a50e702011-10-18 21:21:00 +020015302 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015303}
15304
15305/* Finalize the Unicode implementation */
15306
Christian Heimesa156e092008-02-16 07:38:31 +000015307int
15308PyUnicode_ClearFreeList(void)
15309{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015310 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015311}
15312
Guido van Rossumd57fd912000-03-10 22:53:23 +000015313void
Thomas Wouters78890102000-07-22 19:25:51 +000015314_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015315{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015316 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015317
Serhiy Storchaka05997252013-01-26 12:14:02 +020015318 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015319
Serhiy Storchaka05997252013-01-26 12:14:02 +020015320 for (i = 0; i < 256; i++)
15321 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015322 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015323 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015324}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015325
Walter Dörwald16807132007-05-25 13:52:07 +000015326void
15327PyUnicode_InternInPlace(PyObject **p)
15328{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015329 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015331#ifdef Py_DEBUG
15332 assert(s != NULL);
15333 assert(_PyUnicode_CHECK(s));
15334#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015335 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015336 return;
15337#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015338 /* If it's a subclass, we don't really know what putting
15339 it in the interned dict might do. */
15340 if (!PyUnicode_CheckExact(s))
15341 return;
15342 if (PyUnicode_CHECK_INTERNED(s))
15343 return;
15344 if (interned == NULL) {
15345 interned = PyDict_New();
15346 if (interned == NULL) {
15347 PyErr_Clear(); /* Don't leave an exception */
15348 return;
15349 }
15350 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015351 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015352 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015353 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015354 if (t == NULL) {
15355 PyErr_Clear();
15356 return;
15357 }
15358 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015359 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015360 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015361 return;
15362 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015363 /* The two references in interned are not counted by refcnt.
15364 The deallocator will take care of this */
15365 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015366 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015367}
15368
15369void
15370PyUnicode_InternImmortal(PyObject **p)
15371{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015372 PyUnicode_InternInPlace(p);
15373 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015374 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015375 Py_INCREF(*p);
15376 }
Walter Dörwald16807132007-05-25 13:52:07 +000015377}
15378
15379PyObject *
15380PyUnicode_InternFromString(const char *cp)
15381{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 PyObject *s = PyUnicode_FromString(cp);
15383 if (s == NULL)
15384 return NULL;
15385 PyUnicode_InternInPlace(&s);
15386 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015387}
15388
Alexander Belopolsky40018472011-02-26 01:02:56 +000015389void
15390_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015391{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015392 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015393 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015394 Py_ssize_t i, n;
15395 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015396
Benjamin Peterson14339b62009-01-31 16:36:08 +000015397 if (interned == NULL || !PyDict_Check(interned))
15398 return;
15399 keys = PyDict_Keys(interned);
15400 if (keys == NULL || !PyList_Check(keys)) {
15401 PyErr_Clear();
15402 return;
15403 }
Walter Dörwald16807132007-05-25 13:52:07 +000015404
Benjamin Peterson14339b62009-01-31 16:36:08 +000015405 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15406 detector, interned unicode strings are not forcibly deallocated;
15407 rather, we give them their stolen references back, and then clear
15408 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015409
Benjamin Peterson14339b62009-01-31 16:36:08 +000015410 n = PyList_GET_SIZE(keys);
15411 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015412 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015413 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015414 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015415 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015416 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015417 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015418 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015419 case SSTATE_NOT_INTERNED:
15420 /* XXX Shouldn't happen */
15421 break;
15422 case SSTATE_INTERNED_IMMORTAL:
15423 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015424 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015425 break;
15426 case SSTATE_INTERNED_MORTAL:
15427 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015428 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015429 break;
15430 default:
15431 Py_FatalError("Inconsistent interned string state.");
15432 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015433 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015434 }
15435 fprintf(stderr, "total size of all interned strings: "
15436 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15437 "mortal/immortal\n", mortal_size, immortal_size);
15438 Py_DECREF(keys);
15439 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015440 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015441}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015442
15443
15444/********************* Unicode Iterator **************************/
15445
15446typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015447 PyObject_HEAD
15448 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015449 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015450} unicodeiterobject;
15451
15452static void
15453unicodeiter_dealloc(unicodeiterobject *it)
15454{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015455 _PyObject_GC_UNTRACK(it);
15456 Py_XDECREF(it->it_seq);
15457 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015458}
15459
15460static int
15461unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15462{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015463 Py_VISIT(it->it_seq);
15464 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015465}
15466
15467static PyObject *
15468unicodeiter_next(unicodeiterobject *it)
15469{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015470 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015471
Benjamin Peterson14339b62009-01-31 16:36:08 +000015472 assert(it != NULL);
15473 seq = it->it_seq;
15474 if (seq == NULL)
15475 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015476 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015478 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15479 int kind = PyUnicode_KIND(seq);
15480 void *data = PyUnicode_DATA(seq);
15481 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15482 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015483 if (item != NULL)
15484 ++it->it_index;
15485 return item;
15486 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015487
Benjamin Peterson14339b62009-01-31 16:36:08 +000015488 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015489 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015490 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015491}
15492
15493static PyObject *
15494unicodeiter_len(unicodeiterobject *it)
15495{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015496 Py_ssize_t len = 0;
15497 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015498 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015499 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015500}
15501
15502PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15503
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015504static PyObject *
15505unicodeiter_reduce(unicodeiterobject *it)
15506{
15507 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015508 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015509 it->it_seq, it->it_index);
15510 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015511 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015512 if (u == NULL)
15513 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015514 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015515 }
15516}
15517
15518PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15519
15520static PyObject *
15521unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15522{
15523 Py_ssize_t index = PyLong_AsSsize_t(state);
15524 if (index == -1 && PyErr_Occurred())
15525 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015526 if (it->it_seq != NULL) {
15527 if (index < 0)
15528 index = 0;
15529 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15530 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15531 it->it_index = index;
15532 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015533 Py_RETURN_NONE;
15534}
15535
15536PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15537
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015538static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015539 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015540 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015541 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15542 reduce_doc},
15543 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15544 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015545 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015546};
15547
15548PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015549 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15550 "str_iterator", /* tp_name */
15551 sizeof(unicodeiterobject), /* tp_basicsize */
15552 0, /* tp_itemsize */
15553 /* methods */
15554 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15555 0, /* tp_print */
15556 0, /* tp_getattr */
15557 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015558 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015559 0, /* tp_repr */
15560 0, /* tp_as_number */
15561 0, /* tp_as_sequence */
15562 0, /* tp_as_mapping */
15563 0, /* tp_hash */
15564 0, /* tp_call */
15565 0, /* tp_str */
15566 PyObject_GenericGetAttr, /* tp_getattro */
15567 0, /* tp_setattro */
15568 0, /* tp_as_buffer */
15569 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15570 0, /* tp_doc */
15571 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15572 0, /* tp_clear */
15573 0, /* tp_richcompare */
15574 0, /* tp_weaklistoffset */
15575 PyObject_SelfIter, /* tp_iter */
15576 (iternextfunc)unicodeiter_next, /* tp_iternext */
15577 unicodeiter_methods, /* tp_methods */
15578 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015579};
15580
15581static PyObject *
15582unicode_iter(PyObject *seq)
15583{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015584 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015585
Benjamin Peterson14339b62009-01-31 16:36:08 +000015586 if (!PyUnicode_Check(seq)) {
15587 PyErr_BadInternalCall();
15588 return NULL;
15589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015590 if (PyUnicode_READY(seq) == -1)
15591 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015592 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15593 if (it == NULL)
15594 return NULL;
15595 it->it_index = 0;
15596 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015597 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015598 _PyObject_GC_TRACK(it);
15599 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015600}
15601
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015602
15603size_t
15604Py_UNICODE_strlen(const Py_UNICODE *u)
15605{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015606 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015607}
15608
15609Py_UNICODE*
15610Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15611{
15612 Py_UNICODE *u = s1;
15613 while ((*u++ = *s2++));
15614 return s1;
15615}
15616
15617Py_UNICODE*
15618Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15619{
15620 Py_UNICODE *u = s1;
15621 while ((*u++ = *s2++))
15622 if (n-- == 0)
15623 break;
15624 return s1;
15625}
15626
15627Py_UNICODE*
15628Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15629{
15630 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015631 u1 += wcslen(u1);
15632 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015633 return s1;
15634}
15635
15636int
15637Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15638{
15639 while (*s1 && *s2 && *s1 == *s2)
15640 s1++, s2++;
15641 if (*s1 && *s2)
15642 return (*s1 < *s2) ? -1 : +1;
15643 if (*s1)
15644 return 1;
15645 if (*s2)
15646 return -1;
15647 return 0;
15648}
15649
15650int
15651Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15652{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015653 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015654 for (; n != 0; n--) {
15655 u1 = *s1;
15656 u2 = *s2;
15657 if (u1 != u2)
15658 return (u1 < u2) ? -1 : +1;
15659 if (u1 == '\0')
15660 return 0;
15661 s1++;
15662 s2++;
15663 }
15664 return 0;
15665}
15666
15667Py_UNICODE*
15668Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15669{
15670 const Py_UNICODE *p;
15671 for (p = s; *p; p++)
15672 if (*p == c)
15673 return (Py_UNICODE*)p;
15674 return NULL;
15675}
15676
15677Py_UNICODE*
15678Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15679{
15680 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015681 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015682 while (p != s) {
15683 p--;
15684 if (*p == c)
15685 return (Py_UNICODE*)p;
15686 }
15687 return NULL;
15688}
Victor Stinner331ea922010-08-10 16:37:20 +000015689
Victor Stinner71133ff2010-09-01 23:43:53 +000015690Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015691PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015692{
Victor Stinner577db2c2011-10-11 22:12:48 +020015693 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015694 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015696 if (!PyUnicode_Check(unicode)) {
15697 PyErr_BadArgument();
15698 return NULL;
15699 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015700 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015701 if (u == NULL)
15702 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015703 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015704 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015705 PyErr_NoMemory();
15706 return NULL;
15707 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015708 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015709 size *= sizeof(Py_UNICODE);
15710 copy = PyMem_Malloc(size);
15711 if (copy == NULL) {
15712 PyErr_NoMemory();
15713 return NULL;
15714 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015715 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015716 return copy;
15717}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015718
Georg Brandl66c221e2010-10-14 07:04:07 +000015719/* A _string module, to export formatter_parser and formatter_field_name_split
15720 to the string.Formatter class implemented in Python. */
15721
15722static PyMethodDef _string_methods[] = {
15723 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15724 METH_O, PyDoc_STR("split the argument as a field name")},
15725 {"formatter_parser", (PyCFunction) formatter_parser,
15726 METH_O, PyDoc_STR("parse the argument as a format string")},
15727 {NULL, NULL}
15728};
15729
15730static struct PyModuleDef _string_module = {
15731 PyModuleDef_HEAD_INIT,
15732 "_string",
15733 PyDoc_STR("string helper module"),
15734 0,
15735 _string_methods,
15736 NULL,
15737 NULL,
15738 NULL,
15739 NULL
15740};
15741
15742PyMODINIT_FUNC
15743PyInit__string(void)
15744{
15745 return PyModule_Create(&_string_module);
15746}
15747
15748
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015749#ifdef __cplusplus
15750}
15751#endif