blob: 1a230e03e639c9e0bfaad63e6a3e30efcd089b08 [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 Stinner1b579672011-12-17 05:47:23 +01003840PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003841{
3842 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003843 return unicode_decode_locale(str, size, errors, 0);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003844}
3845
3846
3847PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003848PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003849 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003850 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3851}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003852
Christian Heimes5894ba72007-11-04 11:43:14 +00003853PyObject*
3854PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3855{
Steve Dowercc16be82016-09-08 10:35:16 -07003856#if defined(__APPLE__)
3857 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003858#else
Victor Stinner793b5312011-04-27 00:24:21 +02003859 PyInterpreterState *interp = PyThreadState_GET()->interp;
3860 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3861 cannot use it to encode and decode filenames before it is loaded. Load
3862 the Python codec requires to encode at least its own filename. Use the C
3863 version of the locale codec until the codec registry is initialized and
3864 the Python codec is loaded.
3865
3866 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3867 cannot only rely on it: check also interp->fscodec_initialized for
3868 subinterpreters. */
3869 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003870 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003871 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003872 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003873 }
3874 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003875 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003876 }
Victor Stinnerad158722010-10-27 00:25:46 +00003877#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003878}
3879
Martin v. Löwis011e8422009-05-05 04:43:17 +00003880
3881int
3882PyUnicode_FSConverter(PyObject* arg, void* addr)
3883{
Brett Cannonec6ce872016-09-06 15:50:29 -07003884 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003885 PyObject *output = NULL;
3886 Py_ssize_t size;
3887 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003888 if (arg == NULL) {
3889 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003890 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003891 return 1;
3892 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003893 path = PyOS_FSPath(arg);
3894 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003895 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003896 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003897 if (PyBytes_Check(path)) {
3898 output = path;
3899 }
3900 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3901 output = PyUnicode_EncodeFSDefault(path);
3902 Py_DECREF(path);
3903 if (!output) {
3904 return 0;
3905 }
3906 assert(PyBytes_Check(output));
3907 }
3908
Victor Stinner0ea2a462010-04-30 00:22:08 +00003909 size = PyBytes_GET_SIZE(output);
3910 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003911 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003912 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003913 Py_DECREF(output);
3914 return 0;
3915 }
3916 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003917 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003918}
3919
3920
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003921int
3922PyUnicode_FSDecoder(PyObject* arg, void* addr)
3923{
Brett Cannona5711202016-09-06 19:36:01 -07003924 int is_buffer = 0;
3925 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003926 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003927 if (arg == NULL) {
3928 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003929 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003930 return 1;
3931 }
Brett Cannona5711202016-09-06 19:36:01 -07003932
3933 is_buffer = PyObject_CheckBuffer(arg);
3934 if (!is_buffer) {
3935 path = PyOS_FSPath(arg);
3936 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003937 return 0;
3938 }
Brett Cannona5711202016-09-06 19:36:01 -07003939 }
3940 else {
3941 path = arg;
3942 Py_INCREF(arg);
3943 }
3944
3945 if (PyUnicode_Check(path)) {
3946 if (PyUnicode_READY(path) == -1) {
3947 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003948 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003949 }
3950 output = path;
3951 }
3952 else if (PyBytes_Check(path) || is_buffer) {
3953 PyObject *path_bytes = NULL;
3954
3955 if (!PyBytes_Check(path) &&
3956 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3957 "path should be string, bytes, or os.PathLike, not %.200s",
3958 Py_TYPE(arg)->tp_name)) {
3959 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003960 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003961 }
3962 path_bytes = PyBytes_FromObject(path);
3963 Py_DECREF(path);
3964 if (!path_bytes) {
3965 return 0;
3966 }
3967 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3968 PyBytes_GET_SIZE(path_bytes));
3969 Py_DECREF(path_bytes);
3970 if (!output) {
3971 return 0;
3972 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003973 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003974 else {
3975 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003976 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003977 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003978 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003979 return 0;
3980 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003981 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003982 Py_DECREF(output);
3983 return 0;
3984 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003986 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003987 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003988 Py_DECREF(output);
3989 return 0;
3990 }
3991 *(PyObject**)addr = output;
3992 return Py_CLEANUP_SUPPORTED;
3993}
3994
3995
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003996const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003997PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003998{
Christian Heimesf3863112007-11-22 07:46:41 +00003999 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004000
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00004001 if (!PyUnicode_Check(unicode)) {
4002 PyErr_BadArgument();
4003 return NULL;
4004 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004005 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004006 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004008 if (PyUnicode_UTF8(unicode) == NULL) {
4009 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03004010 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 if (bytes == NULL)
4012 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004013 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
4014 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01004015 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004016 Py_DECREF(bytes);
4017 return NULL;
4018 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004019 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02004020 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004021 PyBytes_AS_STRING(bytes),
4022 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004023 Py_DECREF(bytes);
4024 }
4025
4026 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004027 *psize = PyUnicode_UTF8_LENGTH(unicode);
4028 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004029}
4030
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02004031const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004033{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4035}
4036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004037Py_UNICODE *
4038PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004040 const unsigned char *one_byte;
4041#if SIZEOF_WCHAR_T == 4
4042 const Py_UCS2 *two_bytes;
4043#else
4044 const Py_UCS4 *four_bytes;
4045 const Py_UCS4 *ucs4_end;
4046 Py_ssize_t num_surrogates;
4047#endif
4048 wchar_t *w;
4049 wchar_t *wchar_end;
4050
4051 if (!PyUnicode_Check(unicode)) {
4052 PyErr_BadArgument();
4053 return NULL;
4054 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004055 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004056 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004057 assert(_PyUnicode_KIND(unicode) != 0);
4058 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004059
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004060 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004061#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004062 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4063 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004064 num_surrogates = 0;
4065
4066 for (; four_bytes < ucs4_end; ++four_bytes) {
4067 if (*four_bytes > 0xFFFF)
4068 ++num_surrogates;
4069 }
4070
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004071 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4072 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4073 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004074 PyErr_NoMemory();
4075 return NULL;
4076 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004077 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004078
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004079 w = _PyUnicode_WSTR(unicode);
4080 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4081 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004082 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4083 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004084 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004085 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004086 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4087 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004088 }
4089 else
4090 *w = *four_bytes;
4091
4092 if (w > wchar_end) {
Barry Warsawb2e57942017-09-14 18:13:16 -07004093 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004094 }
4095 }
4096 *w = 0;
4097#else
4098 /* sizeof(wchar_t) == 4 */
4099 Py_FatalError("Impossible unicode object state, wstr and str "
4100 "should share memory already.");
4101 return NULL;
4102#endif
4103 }
4104 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004105 if ((size_t)_PyUnicode_LENGTH(unicode) >
4106 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4107 PyErr_NoMemory();
4108 return NULL;
4109 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004110 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4111 (_PyUnicode_LENGTH(unicode) + 1));
4112 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004113 PyErr_NoMemory();
4114 return NULL;
4115 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004116 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4117 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4118 w = _PyUnicode_WSTR(unicode);
4119 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004120
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004121 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4122 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004123 for (; w < wchar_end; ++one_byte, ++w)
4124 *w = *one_byte;
4125 /* null-terminate the wstr */
4126 *w = 0;
4127 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004128 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004129#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004130 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004131 for (; w < wchar_end; ++two_bytes, ++w)
4132 *w = *two_bytes;
4133 /* null-terminate the wstr */
4134 *w = 0;
4135#else
4136 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004137 PyObject_FREE(_PyUnicode_WSTR(unicode));
4138 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004139 Py_FatalError("Impossible unicode object state, wstr "
4140 "and str should share memory already.");
4141 return NULL;
4142#endif
4143 }
4144 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07004145 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004146 }
4147 }
4148 }
4149 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004150 *size = PyUnicode_WSTR_LENGTH(unicode);
4151 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004152}
4153
Alexander Belopolsky40018472011-02-26 01:02:56 +00004154Py_UNICODE *
4155PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004157 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004158}
4159
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004160const Py_UNICODE *
4161_PyUnicode_AsUnicode(PyObject *unicode)
4162{
4163 Py_ssize_t size;
4164 const Py_UNICODE *wstr;
4165
4166 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4167 if (wstr && wcslen(wstr) != (size_t)size) {
4168 PyErr_SetString(PyExc_ValueError, "embedded null character");
4169 return NULL;
4170 }
4171 return wstr;
4172}
4173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004174
Alexander Belopolsky40018472011-02-26 01:02:56 +00004175Py_ssize_t
4176PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004177{
4178 if (!PyUnicode_Check(unicode)) {
4179 PyErr_BadArgument();
4180 goto onError;
4181 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004182 if (_PyUnicode_WSTR(unicode) == NULL) {
4183 if (PyUnicode_AsUnicode(unicode) == NULL)
4184 goto onError;
4185 }
4186 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004187
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004189 return -1;
4190}
4191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004192Py_ssize_t
4193PyUnicode_GetLength(PyObject *unicode)
4194{
Victor Stinner07621332012-06-16 04:53:46 +02004195 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004196 PyErr_BadArgument();
4197 return -1;
4198 }
Victor Stinner07621332012-06-16 04:53:46 +02004199 if (PyUnicode_READY(unicode) == -1)
4200 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004201 return PyUnicode_GET_LENGTH(unicode);
4202}
4203
4204Py_UCS4
4205PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4206{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004207 void *data;
4208 int kind;
4209
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004210 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004211 PyErr_BadArgument();
4212 return (Py_UCS4)-1;
4213 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004214 if (PyUnicode_READY(unicode) == -1) {
4215 return (Py_UCS4)-1;
4216 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004217 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004218 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004219 return (Py_UCS4)-1;
4220 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004221 data = PyUnicode_DATA(unicode);
4222 kind = PyUnicode_KIND(unicode);
4223 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004224}
4225
4226int
4227PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4228{
4229 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004230 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004231 return -1;
4232 }
Victor Stinner488fa492011-12-12 00:01:39 +01004233 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004234 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004235 PyErr_SetString(PyExc_IndexError, "string index out of range");
4236 return -1;
4237 }
Victor Stinner488fa492011-12-12 00:01:39 +01004238 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004239 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004240 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4241 PyErr_SetString(PyExc_ValueError, "character out of range");
4242 return -1;
4243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004244 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4245 index, ch);
4246 return 0;
4247}
4248
Alexander Belopolsky40018472011-02-26 01:02:56 +00004249const char *
4250PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004251{
Victor Stinner42cb4622010-09-01 19:39:01 +00004252 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004253}
4254
Victor Stinner554f3f02010-06-16 23:33:54 +00004255/* create or adjust a UnicodeDecodeError */
4256static void
4257make_decode_exception(PyObject **exceptionObject,
4258 const char *encoding,
4259 const char *input, Py_ssize_t length,
4260 Py_ssize_t startpos, Py_ssize_t endpos,
4261 const char *reason)
4262{
4263 if (*exceptionObject == NULL) {
4264 *exceptionObject = PyUnicodeDecodeError_Create(
4265 encoding, input, length, startpos, endpos, reason);
4266 }
4267 else {
4268 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4269 goto onError;
4270 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4271 goto onError;
4272 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4273 goto onError;
4274 }
4275 return;
4276
4277onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004278 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004279}
4280
Steve Dowercc16be82016-09-08 10:35:16 -07004281#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004282/* error handling callback helper:
4283 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004284 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285 and adjust various state variables.
4286 return 0 on success, -1 on error
4287*/
4288
Alexander Belopolsky40018472011-02-26 01:02:56 +00004289static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004290unicode_decode_call_errorhandler_wchar(
4291 const char *errors, PyObject **errorHandler,
4292 const char *encoding, const char *reason,
4293 const char **input, const char **inend, Py_ssize_t *startinpos,
4294 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4295 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004296{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004297 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004298
4299 PyObject *restuple = NULL;
4300 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004301 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004302 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004303 Py_ssize_t requiredsize;
4304 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004305 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004306 wchar_t *repwstr;
4307 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004308
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4310 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004311
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004312 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004313 *errorHandler = PyCodec_LookupError(errors);
4314 if (*errorHandler == NULL)
4315 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 }
4317
Victor Stinner554f3f02010-06-16 23:33:54 +00004318 make_decode_exception(exceptionObject,
4319 encoding,
4320 *input, *inend - *input,
4321 *startinpos, *endinpos,
4322 reason);
4323 if (*exceptionObject == NULL)
4324 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004325
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004326 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004327 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004328 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004329 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004330 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004331 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004332 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004333 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004335
4336 /* Copy back the bytes variables, which might have been modified by the
4337 callback */
4338 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4339 if (!inputobj)
4340 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004341 *input = PyBytes_AS_STRING(inputobj);
4342 insize = PyBytes_GET_SIZE(inputobj);
4343 *inend = *input + insize;
4344 /* we can DECREF safely, as the exception has another reference,
4345 so the object won't go away. */
4346 Py_DECREF(inputobj);
4347
4348 if (newpos<0)
4349 newpos = insize+newpos;
4350 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004351 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004352 goto onError;
4353 }
4354
4355 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4356 if (repwstr == NULL)
4357 goto onError;
4358 /* need more space? (at least enough for what we
4359 have+the replacement+the rest of the string (starting
4360 at the new input position), so we won't have to check space
4361 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004362 requiredsize = *outpos;
4363 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4364 goto overflow;
4365 requiredsize += repwlen;
4366 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4367 goto overflow;
4368 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004369 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004370 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004371 requiredsize = 2*outsize;
4372 if (unicode_resize(output, requiredsize) < 0)
4373 goto onError;
4374 }
4375 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4376 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004377 *endinpos = newpos;
4378 *inptr = *input + newpos;
4379
4380 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004381 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004382 return 0;
4383
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004384 overflow:
4385 PyErr_SetString(PyExc_OverflowError,
4386 "decoded result is too long for a Python string");
4387
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388 onError:
4389 Py_XDECREF(restuple);
4390 return -1;
4391}
Steve Dowercc16be82016-09-08 10:35:16 -07004392#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004393
4394static int
4395unicode_decode_call_errorhandler_writer(
4396 const char *errors, PyObject **errorHandler,
4397 const char *encoding, const char *reason,
4398 const char **input, const char **inend, Py_ssize_t *startinpos,
4399 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4400 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4401{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004402 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004403
4404 PyObject *restuple = NULL;
4405 PyObject *repunicode = NULL;
4406 Py_ssize_t insize;
4407 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004408 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004409 PyObject *inputobj = NULL;
4410
4411 if (*errorHandler == NULL) {
4412 *errorHandler = PyCodec_LookupError(errors);
4413 if (*errorHandler == NULL)
4414 goto onError;
4415 }
4416
4417 make_decode_exception(exceptionObject,
4418 encoding,
4419 *input, *inend - *input,
4420 *startinpos, *endinpos,
4421 reason);
4422 if (*exceptionObject == NULL)
4423 goto onError;
4424
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004425 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004426 if (restuple == NULL)
4427 goto onError;
4428 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004429 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004430 goto onError;
4431 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004432 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004433 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004434
4435 /* Copy back the bytes variables, which might have been modified by the
4436 callback */
4437 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4438 if (!inputobj)
4439 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004440 *input = PyBytes_AS_STRING(inputobj);
4441 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004442 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004443 /* we can DECREF safely, as the exception has another reference,
4444 so the object won't go away. */
4445 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004446
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004447 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004449 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004450 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004451 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004452 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004453
Victor Stinner170ca6f2013-04-18 00:25:28 +02004454 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004455 if (replen > 1) {
4456 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004457 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004458 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4459 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4460 goto onError;
4461 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004462 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004463 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004465 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004466 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004467
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004468 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004469 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004471
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004474 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004475}
4476
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477/* --- UTF-7 Codec -------------------------------------------------------- */
4478
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479/* See RFC2152 for details. We encode conservatively and decode liberally. */
4480
4481/* Three simple macros defining base-64. */
4482
4483/* Is c a base-64 character? */
4484
4485#define IS_BASE64(c) \
4486 (((c) >= 'A' && (c) <= 'Z') || \
4487 ((c) >= 'a' && (c) <= 'z') || \
4488 ((c) >= '0' && (c) <= '9') || \
4489 (c) == '+' || (c) == '/')
4490
4491/* given that c is a base-64 character, what is its base-64 value? */
4492
4493#define FROM_BASE64(c) \
4494 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4495 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4496 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4497 (c) == '+' ? 62 : 63)
4498
4499/* What is the base-64 character of the bottom 6 bits of n? */
4500
4501#define TO_BASE64(n) \
4502 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4503
4504/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4505 * decoded as itself. We are permissive on decoding; the only ASCII
4506 * byte not decoding to itself is the + which begins a base64
4507 * string. */
4508
4509#define DECODE_DIRECT(c) \
4510 ((c) <= 127 && (c) != '+')
4511
4512/* The UTF-7 encoder treats ASCII characters differently according to
4513 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4514 * the above). See RFC2152. This array identifies these different
4515 * sets:
4516 * 0 : "Set D"
4517 * alphanumeric and '(),-./:?
4518 * 1 : "Set O"
4519 * !"#$%&*;<=>@[]^_`{|}
4520 * 2 : "whitespace"
4521 * ht nl cr sp
4522 * 3 : special (must be base64 encoded)
4523 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4524 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525
Tim Petersced69f82003-09-16 20:30:58 +00004526static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527char utf7_category[128] = {
4528/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4529 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4530/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4531 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4532/* sp ! " # $ % & ' ( ) * + , - . / */
4533 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4534/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4535 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4536/* @ A B C D E F G H I J K L M N O */
4537 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4538/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4539 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4540/* ` a b c d e f g h i j k l m n o */
4541 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4542/* p q r s t u v w x y z { | } ~ del */
4543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544};
4545
Antoine Pitrou244651a2009-05-04 18:56:13 +00004546/* ENCODE_DIRECT: this character should be encoded as itself. The
4547 * answer depends on whether we are encoding set O as itself, and also
4548 * on whether we are encoding whitespace as itself. RFC2152 makes it
4549 * clear that the answers to these questions vary between
4550 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004551
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552#define ENCODE_DIRECT(c, directO, directWS) \
4553 ((c) < 128 && (c) > 0 && \
4554 ((utf7_category[(c)] == 0) || \
4555 (directWS && (utf7_category[(c)] == 2)) || \
4556 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004557
Alexander Belopolsky40018472011-02-26 01:02:56 +00004558PyObject *
4559PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004560 Py_ssize_t size,
4561 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004563 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4564}
4565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566/* The decoder. The only state we preserve is our read position,
4567 * i.e. how many characters we have consumed. So if we end in the
4568 * middle of a shift sequence we have to back off the read position
4569 * and the output to the beginning of the sequence, otherwise we lose
4570 * all the shift state (seen bits, number of bits seen, high
4571 * surrogate). */
4572
Alexander Belopolsky40018472011-02-26 01:02:56 +00004573PyObject *
4574PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004575 Py_ssize_t size,
4576 const char *errors,
4577 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004578{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004579 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004580 Py_ssize_t startinpos;
4581 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004582 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004583 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584 const char *errmsg = "";
4585 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004586 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 unsigned int base64bits = 0;
4588 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004589 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004590 PyObject *errorHandler = NULL;
4591 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004593 if (size == 0) {
4594 if (consumed)
4595 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004596 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004597 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004599 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004600 _PyUnicodeWriter_Init(&writer);
4601 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004602
4603 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604 e = s + size;
4605
4606 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004607 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004608 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004609 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004610
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 if (inShift) { /* in a base-64 section */
4612 if (IS_BASE64(ch)) { /* consume a base-64 character */
4613 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4614 base64bits += 6;
4615 s++;
4616 if (base64bits >= 16) {
4617 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004618 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619 base64bits -= 16;
4620 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004621 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004622 if (surrogate) {
4623 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004624 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4625 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004626 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004627 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004628 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004629 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 }
4631 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004632 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004633 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004634 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004635 }
4636 }
Victor Stinner551ac952011-11-29 22:58:13 +01004637 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004638 /* first surrogate */
4639 surrogate = outCh;
4640 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004642 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004643 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 }
4645 }
4646 }
4647 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004648 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004649 if (base64bits > 0) { /* left-over bits */
4650 if (base64bits >= 6) {
4651 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004652 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 errmsg = "partial character in shift sequence";
4654 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004655 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004656 else {
4657 /* Some bits remain; they should be zero */
4658 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004659 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660 errmsg = "non-zero padding bits in shift sequence";
4661 goto utf7Error;
4662 }
4663 }
4664 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004665 if (surrogate && DECODE_DIRECT(ch)) {
4666 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4667 goto onError;
4668 }
4669 surrogate = 0;
4670 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004671 /* '-' is absorbed; other terminating
4672 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004673 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004674 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004675 }
4676 }
4677 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004678 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004679 s++; /* consume '+' */
4680 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004681 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004682 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004683 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004684 }
4685 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004686 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004687 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004688 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004689 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004690 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004691 }
4692 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004693 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004694 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004695 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004696 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004697 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004698 else {
4699 startinpos = s-starts;
4700 s++;
4701 errmsg = "unexpected special character";
4702 goto utf7Error;
4703 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004704 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004705utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004706 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004707 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004708 errors, &errorHandler,
4709 "utf7", errmsg,
4710 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004711 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004712 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004713 }
4714
Antoine Pitrou244651a2009-05-04 18:56:13 +00004715 /* end of string */
4716
4717 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4718 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004719 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004720 if (surrogate ||
4721 (base64bits >= 6) ||
4722 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004723 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004724 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004725 errors, &errorHandler,
4726 "utf7", "unterminated shift sequence",
4727 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004729 goto onError;
4730 if (s < e)
4731 goto restart;
4732 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004733 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004734
4735 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004736 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004737 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004738 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004739 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004740 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004741 writer.kind, writer.data, shiftOutStart);
4742 Py_XDECREF(errorHandler);
4743 Py_XDECREF(exc);
4744 _PyUnicodeWriter_Dealloc(&writer);
4745 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004746 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004747 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004748 }
4749 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004750 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004751 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004752 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004753
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004754 Py_XDECREF(errorHandler);
4755 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004756 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004757
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004759 Py_XDECREF(errorHandler);
4760 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004761 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004762 return NULL;
4763}
4764
4765
Alexander Belopolsky40018472011-02-26 01:02:56 +00004766PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004767_PyUnicode_EncodeUTF7(PyObject *str,
4768 int base64SetO,
4769 int base64WhiteSpace,
4770 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004771{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004772 int kind;
4773 void *data;
4774 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004775 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004776 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004777 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004778 unsigned int base64bits = 0;
4779 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004780 char * out;
4781 char * start;
4782
Benjamin Petersonbac79492012-01-14 13:34:47 -05004783 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004784 return NULL;
4785 kind = PyUnicode_KIND(str);
4786 data = PyUnicode_DATA(str);
4787 len = PyUnicode_GET_LENGTH(str);
4788
4789 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004790 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004791
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004792 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004793 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004794 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004795 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004796 if (v == NULL)
4797 return NULL;
4798
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004799 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004800 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004801 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004802
Antoine Pitrou244651a2009-05-04 18:56:13 +00004803 if (inShift) {
4804 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4805 /* shifting out */
4806 if (base64bits) { /* output remaining bits */
4807 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4808 base64buffer = 0;
4809 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004810 }
4811 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004812 /* Characters not in the BASE64 set implicitly unshift the sequence
4813 so no '-' is required, except if the character is itself a '-' */
4814 if (IS_BASE64(ch) || ch == '-') {
4815 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004816 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004817 *out++ = (char) ch;
4818 }
4819 else {
4820 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004821 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004822 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004823 else { /* not in a shift sequence */
4824 if (ch == '+') {
4825 *out++ = '+';
4826 *out++ = '-';
4827 }
4828 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4829 *out++ = (char) ch;
4830 }
4831 else {
4832 *out++ = '+';
4833 inShift = 1;
4834 goto encode_char;
4835 }
4836 }
4837 continue;
4838encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004839 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004840 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004841
Antoine Pitrou244651a2009-05-04 18:56:13 +00004842 /* code first surrogate */
4843 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004844 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004845 while (base64bits >= 6) {
4846 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4847 base64bits -= 6;
4848 }
4849 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004850 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004851 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004852 base64bits += 16;
4853 base64buffer = (base64buffer << 16) | ch;
4854 while (base64bits >= 6) {
4855 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4856 base64bits -= 6;
4857 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004858 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004859 if (base64bits)
4860 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4861 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004862 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004863 if (_PyBytes_Resize(&v, out - start) < 0)
4864 return NULL;
4865 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004866}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004867PyObject *
4868PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4869 Py_ssize_t size,
4870 int base64SetO,
4871 int base64WhiteSpace,
4872 const char *errors)
4873{
4874 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004875 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004876 if (tmp == NULL)
4877 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004878 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004879 base64WhiteSpace, errors);
4880 Py_DECREF(tmp);
4881 return result;
4882}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004883
Antoine Pitrou244651a2009-05-04 18:56:13 +00004884#undef IS_BASE64
4885#undef FROM_BASE64
4886#undef TO_BASE64
4887#undef DECODE_DIRECT
4888#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004889
Guido van Rossumd57fd912000-03-10 22:53:23 +00004890/* --- UTF-8 Codec -------------------------------------------------------- */
4891
Alexander Belopolsky40018472011-02-26 01:02:56 +00004892PyObject *
4893PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004894 Py_ssize_t size,
4895 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004896{
Walter Dörwald69652032004-09-07 20:24:22 +00004897 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4898}
4899
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004900#include "stringlib/asciilib.h"
4901#include "stringlib/codecs.h"
4902#include "stringlib/undef.h"
4903
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004904#include "stringlib/ucs1lib.h"
4905#include "stringlib/codecs.h"
4906#include "stringlib/undef.h"
4907
4908#include "stringlib/ucs2lib.h"
4909#include "stringlib/codecs.h"
4910#include "stringlib/undef.h"
4911
4912#include "stringlib/ucs4lib.h"
4913#include "stringlib/codecs.h"
4914#include "stringlib/undef.h"
4915
Antoine Pitrouab868312009-01-10 15:40:25 +00004916/* Mask to quickly check whether a C 'long' contains a
4917 non-ASCII, UTF8-encoded char. */
4918#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004919# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004920#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004921# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004922#else
4923# error C 'long' size should be either 4 or 8!
4924#endif
4925
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004926static Py_ssize_t
4927ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004928{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004929 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004930 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004931
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004932 /*
4933 * Issue #17237: m68k is a bit different from most architectures in
4934 * that objects do not use "natural alignment" - for example, int and
4935 * long are only aligned at 2-byte boundaries. Therefore the assert()
4936 * won't work; also, tests have shown that skipping the "optimised
4937 * version" will even speed up m68k.
4938 */
4939#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004940#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004941 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4942 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004943 /* Fast path, see in STRINGLIB(utf8_decode) for
4944 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004945 /* Help allocation */
4946 const char *_p = p;
4947 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004948 while (_p < aligned_end) {
4949 unsigned long value = *(const unsigned long *) _p;
4950 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004951 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004952 *((unsigned long *)q) = value;
4953 _p += SIZEOF_LONG;
4954 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004955 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 p = _p;
4957 while (p < end) {
4958 if ((unsigned char)*p & 0x80)
4959 break;
4960 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004961 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004963 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004964#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004965#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004966 while (p < end) {
4967 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4968 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004969 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004970 /* Help allocation */
4971 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972 while (_p < aligned_end) {
4973 unsigned long value = *(unsigned long *) _p;
4974 if (value & ASCII_CHAR_MASK)
4975 break;
4976 _p += SIZEOF_LONG;
4977 }
4978 p = _p;
4979 if (_p == end)
4980 break;
4981 }
4982 if ((unsigned char)*p & 0x80)
4983 break;
4984 ++p;
4985 }
4986 memcpy(dest, start, p - start);
4987 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004988}
Antoine Pitrouab868312009-01-10 15:40:25 +00004989
Victor Stinner785938e2011-12-11 20:09:03 +01004990PyObject *
4991PyUnicode_DecodeUTF8Stateful(const char *s,
4992 Py_ssize_t size,
4993 const char *errors,
4994 Py_ssize_t *consumed)
4995{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004996 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004997 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004998 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999
5000 Py_ssize_t startinpos;
5001 Py_ssize_t endinpos;
5002 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02005003 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02005005 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01005006
5007 if (size == 0) {
5008 if (consumed)
5009 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005010 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01005011 }
5012
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005013 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5014 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01005015 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005016 *consumed = 1;
5017 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01005018 }
5019
Victor Stinner8f674cc2013-04-17 23:02:17 +02005020 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005021 writer.min_length = size;
5022 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005023 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01005024
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005025 writer.pos = ascii_decode(s, end, writer.data);
5026 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005027 while (s < end) {
5028 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005029 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02005030
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005031 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005032 if (PyUnicode_IS_ASCII(writer.buffer))
5033 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005034 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005036 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005037 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005038 } else {
5039 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005040 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005041 }
5042
5043 switch (ch) {
5044 case 0:
5045 if (s == end || consumed)
5046 goto End;
5047 errmsg = "unexpected end of data";
5048 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005049 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005050 break;
5051 case 1:
5052 errmsg = "invalid start byte";
5053 startinpos = s - starts;
5054 endinpos = startinpos + 1;
5055 break;
5056 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005057 case 3:
5058 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005059 errmsg = "invalid continuation byte";
5060 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005061 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005062 break;
5063 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005064 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065 goto onError;
5066 continue;
5067 }
5068
Victor Stinner1d65d912015-10-05 13:43:50 +02005069 if (error_handler == _Py_ERROR_UNKNOWN)
5070 error_handler = get_error_handler(errors);
5071
5072 switch (error_handler) {
5073 case _Py_ERROR_IGNORE:
5074 s += (endinpos - startinpos);
5075 break;
5076
5077 case _Py_ERROR_REPLACE:
5078 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5079 goto onError;
5080 s += (endinpos - startinpos);
5081 break;
5082
5083 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005084 {
5085 Py_ssize_t i;
5086
Victor Stinner1d65d912015-10-05 13:43:50 +02005087 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5088 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005089 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005090 ch = (Py_UCS4)(unsigned char)(starts[i]);
5091 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5092 ch + 0xdc00);
5093 writer.pos++;
5094 }
5095 s += (endinpos - startinpos);
5096 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005097 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005098
5099 default:
5100 if (unicode_decode_call_errorhandler_writer(
5101 errors, &error_handler_obj,
5102 "utf-8", errmsg,
5103 &starts, &end, &startinpos, &endinpos, &exc, &s,
5104 &writer))
5105 goto onError;
5106 }
Victor Stinner785938e2011-12-11 20:09:03 +01005107 }
5108
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005109End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005110 if (consumed)
5111 *consumed = s - starts;
5112
Victor Stinner1d65d912015-10-05 13:43:50 +02005113 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005114 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005115 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005116
5117onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005118 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005119 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005120 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005121 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005122}
5123
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005124
Victor Stinner91106cd2017-12-13 12:29:09 +01005125/* UTF-8 decoder using the surrogateescape error handler .
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005126
Victor Stinner91106cd2017-12-13 12:29:09 +01005127 On success, return a pointer to a newly allocated wide character string (use
5128 PyMem_RawFree() to free the memory) and write the output length (in number
5129 of wchar_t units) into *p_wlen (if p_wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005130
Victor Stinner91106cd2017-12-13 12:29:09 +01005131 On memory allocation failure, return -1 and write (size_t)-1 into *p_wlen
5132 (if p_wlen is set). */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005133wchar_t*
Victor Stinner91106cd2017-12-13 12:29:09 +01005134_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size, size_t *p_wlen)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005135{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005136 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005137 wchar_t *unicode;
5138 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005139
5140 /* Note: size will always be longer than the resulting Unicode
5141 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01005142 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
5143 if (p_wlen) {
5144 *p_wlen = (size_t)-1;
5145 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005146 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005147 }
5148
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005149 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01005150 if (!unicode) {
5151 if (p_wlen) {
5152 *p_wlen = (size_t)-1;
5153 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005154 return NULL;
Victor Stinner91106cd2017-12-13 12:29:09 +01005155 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005156
5157 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005158 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005159 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005160 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005161 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005162#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005163 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005164#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005165 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005166#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005167 if (ch > 0xFF) {
5168#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005169 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005170#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005171 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005172 /* compute and append the two surrogates: */
5173 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5174 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5175#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005176 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005177 else {
5178 if (!ch && s == e)
5179 break;
5180 /* surrogateescape */
5181 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5182 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005183 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005184 unicode[outpos] = L'\0';
Victor Stinner91106cd2017-12-13 12:29:09 +01005185 if (p_wlen) {
5186 *p_wlen = outpos;
5187 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005188 return unicode;
5189}
5190
Antoine Pitrouab868312009-01-10 15:40:25 +00005191
Victor Stinnere47e6982017-12-21 15:45:16 +01005192/* UTF-8 encoder using the surrogateescape error handler .
5193
5194 On success, return a pointer to a newly allocated character string (use
5195 PyMem_Free() to free the memory).
5196
5197 On encoding failure, return NULL and write the position of the invalid
5198 surrogate character into *error_pos (if error_pos is set).
5199
5200 On memory allocation failure, return NULL and write (size_t)-1 into
5201 *error_pos (if error_pos is set). */
5202char*
Victor Stinner9dd76202017-12-21 16:20:32 +01005203_Py_EncodeUTF8_surrogateescape(const wchar_t *text, size_t *error_pos,
5204 int raw_malloc)
Victor Stinnere47e6982017-12-21 15:45:16 +01005205{
5206 const Py_ssize_t max_char_size = 4;
5207 Py_ssize_t len = wcslen(text);
5208
5209 assert(len >= 0);
5210
5211 char *bytes;
5212 if (len <= PY_SSIZE_T_MAX / max_char_size - 1) {
Victor Stinner9dd76202017-12-21 16:20:32 +01005213 if (raw_malloc) {
5214 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
5215 }
5216 else {
5217 bytes = PyMem_Malloc((len + 1) * max_char_size);
5218 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005219 }
5220 else {
5221 bytes = NULL;
5222 }
5223 if (bytes == NULL) {
5224 if (error_pos != NULL) {
5225 *error_pos = (size_t)-1;
5226 }
5227 return NULL;
5228 }
5229
5230 char *p = bytes;
5231 Py_ssize_t i;
5232 for (i = 0; i < len;) {
5233 Py_UCS4 ch = text[i++];
5234
5235 if (ch < 0x80) {
5236 /* Encode ASCII */
5237 *p++ = (char) ch;
5238
5239 }
5240 else if (ch < 0x0800) {
5241 /* Encode Latin-1 */
5242 *p++ = (char)(0xc0 | (ch >> 6));
5243 *p++ = (char)(0x80 | (ch & 0x3f));
5244 }
5245 else if (Py_UNICODE_IS_SURROGATE(ch)) {
5246 /* surrogateescape error handler */
5247 if (!(0xDC80 <= ch && ch <= 0xDCFF)) {
5248 if (error_pos != NULL) {
5249 *error_pos = (size_t)i - 1;
5250 }
5251 goto error;
5252 }
5253 *p++ = (char)(ch & 0xff);
5254 }
5255 else if (ch < 0x10000) {
5256 *p++ = (char)(0xe0 | (ch >> 12));
5257 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5258 *p++ = (char)(0x80 | (ch & 0x3f));
5259 }
5260 else { /* ch >= 0x10000 */
5261 assert(ch <= MAX_UNICODE);
5262 /* Encode UCS4 Unicode ordinals */
5263 *p++ = (char)(0xf0 | (ch >> 18));
5264 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5265 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5266 *p++ = (char)(0x80 | (ch & 0x3f));
5267 }
5268 }
5269 *p++ = '\0';
5270
5271 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005272 char *bytes2;
5273 if (raw_malloc) {
5274 bytes2 = PyMem_RawRealloc(bytes, final_size);
5275 }
5276 else {
5277 bytes2 = PyMem_Realloc(bytes, final_size);
5278 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005279 if (bytes2 == NULL) {
5280 if (error_pos != NULL) {
5281 *error_pos = (size_t)-1;
5282 }
5283 goto error;
5284 }
5285 return bytes2;
5286
5287 error:
Victor Stinner9dd76202017-12-21 16:20:32 +01005288 if (raw_malloc) {
5289 PyMem_RawFree(bytes);
5290 }
5291 else {
5292 PyMem_Free(bytes);
5293 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005294 return NULL;
5295}
5296
5297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005298/* Primary internal function which creates utf8 encoded bytes objects.
5299
5300 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005301 and allocate exactly as much space needed at the end. Else allocate the
5302 maximum possible needed (4 result bytes per Unicode character), and return
5303 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005304*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005305PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005306_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005307{
Victor Stinner6099a032011-12-18 14:22:26 +01005308 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005309 void *data;
5310 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005312 if (!PyUnicode_Check(unicode)) {
5313 PyErr_BadArgument();
5314 return NULL;
5315 }
5316
5317 if (PyUnicode_READY(unicode) == -1)
5318 return NULL;
5319
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005320 if (PyUnicode_UTF8(unicode))
5321 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5322 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005323
5324 kind = PyUnicode_KIND(unicode);
5325 data = PyUnicode_DATA(unicode);
5326 size = PyUnicode_GET_LENGTH(unicode);
5327
Benjamin Petersonead6b532011-12-20 17:23:42 -06005328 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005329 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005330 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005331 case PyUnicode_1BYTE_KIND:
5332 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5333 assert(!PyUnicode_IS_ASCII(unicode));
5334 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5335 case PyUnicode_2BYTE_KIND:
5336 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5337 case PyUnicode_4BYTE_KIND:
5338 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005339 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005340}
5341
Alexander Belopolsky40018472011-02-26 01:02:56 +00005342PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005343PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5344 Py_ssize_t size,
5345 const char *errors)
5346{
5347 PyObject *v, *unicode;
5348
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005349 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005350 if (unicode == NULL)
5351 return NULL;
5352 v = _PyUnicode_AsUTF8String(unicode, errors);
5353 Py_DECREF(unicode);
5354 return v;
5355}
5356
5357PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005358PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005359{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005360 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005361}
5362
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363/* --- UTF-32 Codec ------------------------------------------------------- */
5364
5365PyObject *
5366PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 Py_ssize_t size,
5368 const char *errors,
5369 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005370{
5371 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5372}
5373
5374PyObject *
5375PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005376 Py_ssize_t size,
5377 const char *errors,
5378 int *byteorder,
5379 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005380{
5381 const char *starts = s;
5382 Py_ssize_t startinpos;
5383 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005384 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005385 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005386 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005387 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005388 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005389 PyObject *errorHandler = NULL;
5390 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005391
Walter Dörwald41980ca2007-08-16 21:55:45 +00005392 q = (unsigned char *)s;
5393 e = q + size;
5394
5395 if (byteorder)
5396 bo = *byteorder;
5397
5398 /* Check for BOM marks (U+FEFF) in the input and adjust current
5399 byte order setting accordingly. In native mode, the leading BOM
5400 mark is skipped, in all other modes, it is copied to the output
5401 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005402 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005403 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005404 if (bom == 0x0000FEFF) {
5405 bo = -1;
5406 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005407 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005408 else if (bom == 0xFFFE0000) {
5409 bo = 1;
5410 q += 4;
5411 }
5412 if (byteorder)
5413 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005414 }
5415
Victor Stinnere64322e2012-10-30 23:12:47 +01005416 if (q == e) {
5417 if (consumed)
5418 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005419 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005420 }
5421
Victor Stinnere64322e2012-10-30 23:12:47 +01005422#ifdef WORDS_BIGENDIAN
5423 le = bo < 0;
5424#else
5425 le = bo <= 0;
5426#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005428
Victor Stinner8f674cc2013-04-17 23:02:17 +02005429 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005430 writer.min_length = (e - q + 3) / 4;
5431 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005432 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005433
Victor Stinnere64322e2012-10-30 23:12:47 +01005434 while (1) {
5435 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005436 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005437
Victor Stinnere64322e2012-10-30 23:12:47 +01005438 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005439 enum PyUnicode_Kind kind = writer.kind;
5440 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005441 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005442 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005443 if (le) {
5444 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005445 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005446 if (ch > maxch)
5447 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005448 if (kind != PyUnicode_1BYTE_KIND &&
5449 Py_UNICODE_IS_SURROGATE(ch))
5450 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005451 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005452 q += 4;
5453 } while (q <= last);
5454 }
5455 else {
5456 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005457 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005458 if (ch > maxch)
5459 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005460 if (kind != PyUnicode_1BYTE_KIND &&
5461 Py_UNICODE_IS_SURROGATE(ch))
5462 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005463 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005464 q += 4;
5465 } while (q <= last);
5466 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005467 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005468 }
5469
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005471 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 startinpos = ((const char *)q) - starts;
5473 endinpos = startinpos + 4;
5474 }
5475 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005476 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005477 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005478 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005480 startinpos = ((const char *)q) - starts;
5481 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005482 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005483 else {
5484 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005485 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005486 goto onError;
5487 q += 4;
5488 continue;
5489 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005490 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005491 startinpos = ((const char *)q) - starts;
5492 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005493 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005494
5495 /* The remaining input chars are ignored if the callback
5496 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005497 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005499 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005500 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005501 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005502 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005503 }
5504
Walter Dörwald41980ca2007-08-16 21:55:45 +00005505 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005506 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005507
Walter Dörwald41980ca2007-08-16 21:55:45 +00005508 Py_XDECREF(errorHandler);
5509 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005510 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005511
Benjamin Peterson29060642009-01-31 22:14:21 +00005512 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005513 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005514 Py_XDECREF(errorHandler);
5515 Py_XDECREF(exc);
5516 return NULL;
5517}
5518
5519PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005520_PyUnicode_EncodeUTF32(PyObject *str,
5521 const char *errors,
5522 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005523{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005524 enum PyUnicode_Kind kind;
5525 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005526 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005527 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005528 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005529#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005530 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005531#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005532 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005533#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005534 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005535 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005536 PyObject *errorHandler = NULL;
5537 PyObject *exc = NULL;
5538 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005539
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005540 if (!PyUnicode_Check(str)) {
5541 PyErr_BadArgument();
5542 return NULL;
5543 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005544 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005545 return NULL;
5546 kind = PyUnicode_KIND(str);
5547 data = PyUnicode_DATA(str);
5548 len = PyUnicode_GET_LENGTH(str);
5549
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005550 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005551 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005552 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005553 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005554 if (v == NULL)
5555 return NULL;
5556
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005557 /* output buffer is 4-bytes aligned */
5558 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005559 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005560 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005561 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005562 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005563 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005564
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005565 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005566 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005567 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005568 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005569 else
5570 encoding = "utf-32";
5571
5572 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005573 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5574 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005575 }
5576
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005577 pos = 0;
5578 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005579 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005580
5581 if (kind == PyUnicode_2BYTE_KIND) {
5582 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5583 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005584 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005585 else {
5586 assert(kind == PyUnicode_4BYTE_KIND);
5587 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5588 &out, native_ordering);
5589 }
5590 if (pos == len)
5591 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005592
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005593 rep = unicode_encode_call_errorhandler(
5594 errors, &errorHandler,
5595 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005596 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005597 if (!rep)
5598 goto error;
5599
5600 if (PyBytes_Check(rep)) {
5601 repsize = PyBytes_GET_SIZE(rep);
5602 if (repsize & 3) {
5603 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005604 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005605 "surrogates not allowed");
5606 goto error;
5607 }
5608 moreunits = repsize / 4;
5609 }
5610 else {
5611 assert(PyUnicode_Check(rep));
5612 if (PyUnicode_READY(rep) < 0)
5613 goto error;
5614 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5615 if (!PyUnicode_IS_ASCII(rep)) {
5616 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005617 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005618 "surrogates not allowed");
5619 goto error;
5620 }
5621 }
5622
5623 /* four bytes are reserved for each surrogate */
5624 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005625 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005626 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005627 /* integer overflow */
5628 PyErr_NoMemory();
5629 goto error;
5630 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005631 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005632 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005633 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005634 }
5635
5636 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005637 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005638 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005639 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005640 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005641 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5642 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005643 }
5644
5645 Py_CLEAR(rep);
5646 }
5647
5648 /* Cut back to size actually needed. This is necessary for, for example,
5649 encoding of a string containing isolated surrogates and the 'ignore'
5650 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005651 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005652 if (nsize != PyBytes_GET_SIZE(v))
5653 _PyBytes_Resize(&v, nsize);
5654 Py_XDECREF(errorHandler);
5655 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005656 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005657 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005658 error:
5659 Py_XDECREF(rep);
5660 Py_XDECREF(errorHandler);
5661 Py_XDECREF(exc);
5662 Py_XDECREF(v);
5663 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005664}
5665
Alexander Belopolsky40018472011-02-26 01:02:56 +00005666PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005667PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5668 Py_ssize_t size,
5669 const char *errors,
5670 int byteorder)
5671{
5672 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005673 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005674 if (tmp == NULL)
5675 return NULL;
5676 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5677 Py_DECREF(tmp);
5678 return result;
5679}
5680
5681PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005682PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005683{
Victor Stinnerb960b342011-11-20 19:12:52 +01005684 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005685}
5686
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687/* --- UTF-16 Codec ------------------------------------------------------- */
5688
Tim Peters772747b2001-08-09 22:21:55 +00005689PyObject *
5690PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 Py_ssize_t size,
5692 const char *errors,
5693 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694{
Walter Dörwald69652032004-09-07 20:24:22 +00005695 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5696}
5697
5698PyObject *
5699PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005700 Py_ssize_t size,
5701 const char *errors,
5702 int *byteorder,
5703 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005704{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005705 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005706 Py_ssize_t startinpos;
5707 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005708 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005709 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005710 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005711 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005712 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005713 PyObject *errorHandler = NULL;
5714 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005715 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716
Tim Peters772747b2001-08-09 22:21:55 +00005717 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005718 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719
5720 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005721 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005723 /* Check for BOM marks (U+FEFF) in the input and adjust current
5724 byte order setting accordingly. In native mode, the leading BOM
5725 mark is skipped, in all other modes, it is copied to the output
5726 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005727 if (bo == 0 && size >= 2) {
5728 const Py_UCS4 bom = (q[1] << 8) | q[0];
5729 if (bom == 0xFEFF) {
5730 q += 2;
5731 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005732 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005733 else if (bom == 0xFFFE) {
5734 q += 2;
5735 bo = 1;
5736 }
5737 if (byteorder)
5738 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005739 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Antoine Pitrou63065d72012-05-15 23:48:04 +02005741 if (q == e) {
5742 if (consumed)
5743 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005744 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005745 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005746
Christian Heimes743e0cd2012-10-17 23:52:17 +02005747#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005748 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005749 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005750#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005751 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005752 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005753#endif
Tim Peters772747b2001-08-09 22:21:55 +00005754
Antoine Pitrou63065d72012-05-15 23:48:04 +02005755 /* Note: size will always be longer than the resulting Unicode
5756 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005757 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005758 writer.min_length = (e - q + 1) / 2;
5759 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005760 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005761
Antoine Pitrou63065d72012-05-15 23:48:04 +02005762 while (1) {
5763 Py_UCS4 ch = 0;
5764 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005765 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005766 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005767 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005768 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005769 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005770 native_ordering);
5771 else
5772 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005773 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005774 native_ordering);
5775 } else if (kind == PyUnicode_2BYTE_KIND) {
5776 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005777 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005778 native_ordering);
5779 } else {
5780 assert(kind == PyUnicode_4BYTE_KIND);
5781 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005782 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005783 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005784 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005785 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005786
Antoine Pitrou63065d72012-05-15 23:48:04 +02005787 switch (ch)
5788 {
5789 case 0:
5790 /* remaining byte at the end? (size should be even) */
5791 if (q == e || consumed)
5792 goto End;
5793 errmsg = "truncated data";
5794 startinpos = ((const char *)q) - starts;
5795 endinpos = ((const char *)e) - starts;
5796 break;
5797 /* The remaining input chars are ignored if the callback
5798 chooses to skip the input */
5799 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005800 q -= 2;
5801 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005802 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005803 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005804 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005805 endinpos = ((const char *)e) - starts;
5806 break;
5807 case 2:
5808 errmsg = "illegal encoding";
5809 startinpos = ((const char *)q) - 2 - starts;
5810 endinpos = startinpos + 2;
5811 break;
5812 case 3:
5813 errmsg = "illegal UTF-16 surrogate";
5814 startinpos = ((const char *)q) - 4 - starts;
5815 endinpos = startinpos + 2;
5816 break;
5817 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005818 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005819 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005820 continue;
5821 }
5822
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005823 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005824 errors,
5825 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005826 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005827 &starts,
5828 (const char **)&e,
5829 &startinpos,
5830 &endinpos,
5831 &exc,
5832 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005833 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005834 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005835 }
5836
Antoine Pitrou63065d72012-05-15 23:48:04 +02005837End:
Walter Dörwald69652032004-09-07 20:24:22 +00005838 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005840
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005841 Py_XDECREF(errorHandler);
5842 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005843 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005844
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005846 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005847 Py_XDECREF(errorHandler);
5848 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005849 return NULL;
5850}
5851
Tim Peters772747b2001-08-09 22:21:55 +00005852PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005853_PyUnicode_EncodeUTF16(PyObject *str,
5854 const char *errors,
5855 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005857 enum PyUnicode_Kind kind;
5858 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005859 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005860 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005861 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005862 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005863#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005864 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005865#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005866 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005867#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005868 const char *encoding;
5869 Py_ssize_t nsize, pos;
5870 PyObject *errorHandler = NULL;
5871 PyObject *exc = NULL;
5872 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005873
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005874 if (!PyUnicode_Check(str)) {
5875 PyErr_BadArgument();
5876 return NULL;
5877 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005878 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005879 return NULL;
5880 kind = PyUnicode_KIND(str);
5881 data = PyUnicode_DATA(str);
5882 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005883
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005884 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005885 if (kind == PyUnicode_4BYTE_KIND) {
5886 const Py_UCS4 *in = (const Py_UCS4 *)data;
5887 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005888 while (in < end) {
5889 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005890 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005891 }
5892 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005893 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005894 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005895 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005896 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005897 nsize = len + pairs + (byteorder == 0);
5898 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005899 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005901 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005903 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005904 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005905 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005906 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005907 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005908 }
5909 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005910 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005911 }
Tim Peters772747b2001-08-09 22:21:55 +00005912
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005913 if (kind == PyUnicode_1BYTE_KIND) {
5914 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5915 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005916 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005917
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005918 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005919 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005920 }
5921 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005922 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005923 }
5924 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005925 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005926 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005927
5928 pos = 0;
5929 while (pos < len) {
5930 Py_ssize_t repsize, moreunits;
5931
5932 if (kind == PyUnicode_2BYTE_KIND) {
5933 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5934 &out, native_ordering);
5935 }
5936 else {
5937 assert(kind == PyUnicode_4BYTE_KIND);
5938 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5939 &out, native_ordering);
5940 }
5941 if (pos == len)
5942 break;
5943
5944 rep = unicode_encode_call_errorhandler(
5945 errors, &errorHandler,
5946 encoding, "surrogates not allowed",
5947 str, &exc, pos, pos + 1, &pos);
5948 if (!rep)
5949 goto error;
5950
5951 if (PyBytes_Check(rep)) {
5952 repsize = PyBytes_GET_SIZE(rep);
5953 if (repsize & 1) {
5954 raise_encode_exception(&exc, encoding,
5955 str, pos - 1, pos,
5956 "surrogates not allowed");
5957 goto error;
5958 }
5959 moreunits = repsize / 2;
5960 }
5961 else {
5962 assert(PyUnicode_Check(rep));
5963 if (PyUnicode_READY(rep) < 0)
5964 goto error;
5965 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5966 if (!PyUnicode_IS_ASCII(rep)) {
5967 raise_encode_exception(&exc, encoding,
5968 str, pos - 1, pos,
5969 "surrogates not allowed");
5970 goto error;
5971 }
5972 }
5973
5974 /* two bytes are reserved for each surrogate */
5975 if (moreunits > 1) {
5976 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005977 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005978 /* integer overflow */
5979 PyErr_NoMemory();
5980 goto error;
5981 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005982 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005983 goto error;
5984 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5985 }
5986
5987 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005988 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005989 out += moreunits;
5990 } else /* rep is unicode */ {
5991 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5992 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5993 &out, native_ordering);
5994 }
5995
5996 Py_CLEAR(rep);
5997 }
5998
5999 /* Cut back to size actually needed. This is necessary for, for example,
6000 encoding of a string containing isolated surrogates and the 'ignore' handler
6001 is used. */
6002 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
6003 if (nsize != PyBytes_GET_SIZE(v))
6004 _PyBytes_Resize(&v, nsize);
6005 Py_XDECREF(errorHandler);
6006 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00006007 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006008 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006009 error:
6010 Py_XDECREF(rep);
6011 Py_XDECREF(errorHandler);
6012 Py_XDECREF(exc);
6013 Py_XDECREF(v);
6014 return NULL;
6015#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016}
6017
Alexander Belopolsky40018472011-02-26 01:02:56 +00006018PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006019PyUnicode_EncodeUTF16(const Py_UNICODE *s,
6020 Py_ssize_t size,
6021 const char *errors,
6022 int byteorder)
6023{
6024 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006025 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006026 if (tmp == NULL)
6027 return NULL;
6028 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
6029 Py_DECREF(tmp);
6030 return result;
6031}
6032
6033PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006034PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006036 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037}
6038
6039/* --- Unicode Escape Codec ----------------------------------------------- */
6040
Fredrik Lundh06d12682001-01-24 07:59:11 +00006041static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00006042
Alexander Belopolsky40018472011-02-26 01:02:56 +00006043PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04006044_PyUnicode_DecodeUnicodeEscape(const char *s,
6045 Py_ssize_t size,
6046 const char *errors,
6047 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006049 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006050 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006052 PyObject *errorHandler = NULL;
6053 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054
Eric V. Smith42454af2016-10-31 09:22:08 -04006055 // so we can remember if we've seen an invalid escape char or not
6056 *first_invalid_escape = NULL;
6057
Victor Stinner62ec3312016-09-06 17:04:34 -07006058 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006059 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006060 }
6061 /* Escaped strings will always be longer than the resulting
6062 Unicode string, so we start with size here and then reduce the
6063 length after conversion to the true value.
6064 (but if the error callback returns a long replacement string
6065 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006066 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006067 writer.min_length = size;
6068 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6069 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006070 }
6071
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 end = s + size;
6073 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006074 unsigned char c = (unsigned char) *s++;
6075 Py_UCS4 ch;
6076 int count;
6077 Py_ssize_t startinpos;
6078 Py_ssize_t endinpos;
6079 const char *message;
6080
6081#define WRITE_ASCII_CHAR(ch) \
6082 do { \
6083 assert(ch <= 127); \
6084 assert(writer.pos < writer.size); \
6085 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6086 } while(0)
6087
6088#define WRITE_CHAR(ch) \
6089 do { \
6090 if (ch <= writer.maxchar) { \
6091 assert(writer.pos < writer.size); \
6092 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6093 } \
6094 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6095 goto onError; \
6096 } \
6097 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098
6099 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006100 if (c != '\\') {
6101 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102 continue;
6103 }
6104
Victor Stinner62ec3312016-09-06 17:04:34 -07006105 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006106 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006107 if (s >= end) {
6108 message = "\\ at end of string";
6109 goto error;
6110 }
6111 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006112
Victor Stinner62ec3312016-09-06 17:04:34 -07006113 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006114 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006117 case '\n': continue;
6118 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6119 case '\'': WRITE_ASCII_CHAR('\''); continue;
6120 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6121 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006122 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006123 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6124 case 't': WRITE_ASCII_CHAR('\t'); continue;
6125 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6126 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006127 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006128 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006129 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006130 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006133 case '0': case '1': case '2': case '3':
6134 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006135 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006136 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006137 ch = (ch<<3) + *s++ - '0';
6138 if (s < end && '0' <= *s && *s <= '7') {
6139 ch = (ch<<3) + *s++ - '0';
6140 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006141 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006142 WRITE_CHAR(ch);
6143 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 /* hex escapes */
6146 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006148 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006149 message = "truncated \\xXX escape";
6150 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151
Benjamin Peterson29060642009-01-31 22:14:21 +00006152 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006154 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006155 message = "truncated \\uXXXX escape";
6156 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006159 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006160 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006161 message = "truncated \\UXXXXXXXX escape";
6162 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006163 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006164 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006165 ch <<= 4;
6166 if (c >= '0' && c <= '9') {
6167 ch += c - '0';
6168 }
6169 else if (c >= 'a' && c <= 'f') {
6170 ch += c - ('a' - 10);
6171 }
6172 else if (c >= 'A' && c <= 'F') {
6173 ch += c - ('A' - 10);
6174 }
6175 else {
6176 break;
6177 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006178 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006179 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006180 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006181 }
6182
6183 /* when we get here, ch is a 32-bit unicode character */
6184 if (ch > MAX_UNICODE) {
6185 message = "illegal Unicode character";
6186 goto error;
6187 }
6188
6189 WRITE_CHAR(ch);
6190 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006191
Benjamin Peterson29060642009-01-31 22:14:21 +00006192 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006193 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006194 if (ucnhash_CAPI == NULL) {
6195 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006196 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6197 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006198 if (ucnhash_CAPI == NULL) {
6199 PyErr_SetString(
6200 PyExc_UnicodeError,
6201 "\\N escapes not supported (can't load unicodedata module)"
6202 );
6203 goto onError;
6204 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006205 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006206
6207 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006208 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006209 const char *start = ++s;
6210 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006211 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006213 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006214 namelen = s - start;
6215 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006216 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006217 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006218 ch = 0xffffffff; /* in case 'getcode' messes up */
6219 if (namelen <= INT_MAX &&
6220 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6221 &ch, 0)) {
6222 assert(ch <= MAX_UNICODE);
6223 WRITE_CHAR(ch);
6224 continue;
6225 }
6226 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006227 }
6228 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006229 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006230
6231 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006232 if (*first_invalid_escape == NULL) {
6233 *first_invalid_escape = s-1; /* Back up one char, since we've
6234 already incremented s. */
6235 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006236 WRITE_ASCII_CHAR('\\');
6237 WRITE_CHAR(c);
6238 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006240
6241 error:
6242 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006243 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006244 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006245 errors, &errorHandler,
6246 "unicodeescape", message,
6247 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006248 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006249 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006250 }
6251 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6252 goto onError;
6253 }
6254
6255#undef WRITE_ASCII_CHAR
6256#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006257 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006258
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006259 Py_XDECREF(errorHandler);
6260 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006261 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006262
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006264 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006265 Py_XDECREF(errorHandler);
6266 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267 return NULL;
6268}
6269
Eric V. Smith42454af2016-10-31 09:22:08 -04006270PyObject *
6271PyUnicode_DecodeUnicodeEscape(const char *s,
6272 Py_ssize_t size,
6273 const char *errors)
6274{
6275 const char *first_invalid_escape;
6276 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6277 &first_invalid_escape);
6278 if (result == NULL)
6279 return NULL;
6280 if (first_invalid_escape != NULL) {
6281 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6282 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006283 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006284 Py_DECREF(result);
6285 return NULL;
6286 }
6287 }
6288 return result;
6289}
6290
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006291/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006292
Alexander Belopolsky40018472011-02-26 01:02:56 +00006293PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006294PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006296 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006297 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006298 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006299 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006300 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006301 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302
Ezio Melottie7f90372012-10-05 03:33:31 +03006303 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006304 escape.
6305
Ezio Melottie7f90372012-10-05 03:33:31 +03006306 For UCS1 strings it's '\xxx', 4 bytes per source character.
6307 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6308 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006309 */
6310
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006311 if (!PyUnicode_Check(unicode)) {
6312 PyErr_BadArgument();
6313 return NULL;
6314 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006315 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006316 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006317 }
Victor Stinner358af132015-10-12 22:36:57 +02006318
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006319 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006320 if (len == 0) {
6321 return PyBytes_FromStringAndSize(NULL, 0);
6322 }
6323
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006324 kind = PyUnicode_KIND(unicode);
6325 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6327 bytes, and 1 byte characters 4. */
6328 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006329 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006330 return PyErr_NoMemory();
6331 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006332 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006333 if (repr == NULL) {
6334 return NULL;
6335 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006336
Victor Stinner62ec3312016-09-06 17:04:34 -07006337 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006338 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006339 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006340
Victor Stinner62ec3312016-09-06 17:04:34 -07006341 /* U+0000-U+00ff range */
6342 if (ch < 0x100) {
6343 if (ch >= ' ' && ch < 127) {
6344 if (ch != '\\') {
6345 /* Copy printable US ASCII as-is */
6346 *p++ = (char) ch;
6347 }
6348 /* Escape backslashes */
6349 else {
6350 *p++ = '\\';
6351 *p++ = '\\';
6352 }
6353 }
Victor Stinner358af132015-10-12 22:36:57 +02006354
Victor Stinner62ec3312016-09-06 17:04:34 -07006355 /* Map special whitespace to '\t', \n', '\r' */
6356 else if (ch == '\t') {
6357 *p++ = '\\';
6358 *p++ = 't';
6359 }
6360 else if (ch == '\n') {
6361 *p++ = '\\';
6362 *p++ = 'n';
6363 }
6364 else if (ch == '\r') {
6365 *p++ = '\\';
6366 *p++ = 'r';
6367 }
6368
6369 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6370 else {
6371 *p++ = '\\';
6372 *p++ = 'x';
6373 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6374 *p++ = Py_hexdigits[ch & 0x000F];
6375 }
Tim Petersced69f82003-09-16 20:30:58 +00006376 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006377 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006378 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379 *p++ = '\\';
6380 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006381 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6382 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6383 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6384 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006385 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006386 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6387 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006388
Victor Stinner62ec3312016-09-06 17:04:34 -07006389 /* Make sure that the first two digits are zero */
6390 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006391 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006392 *p++ = 'U';
6393 *p++ = '0';
6394 *p++ = '0';
6395 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6396 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6397 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6398 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6399 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6400 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006402 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403
Victor Stinner62ec3312016-09-06 17:04:34 -07006404 assert(p - PyBytes_AS_STRING(repr) > 0);
6405 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6406 return NULL;
6407 }
6408 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409}
6410
Alexander Belopolsky40018472011-02-26 01:02:56 +00006411PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006412PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6413 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006415 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006416 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006417 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006418 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006419 }
6420
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006421 result = PyUnicode_AsUnicodeEscapeString(tmp);
6422 Py_DECREF(tmp);
6423 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424}
6425
6426/* --- Raw Unicode Escape Codec ------------------------------------------- */
6427
Alexander Belopolsky40018472011-02-26 01:02:56 +00006428PyObject *
6429PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006430 Py_ssize_t size,
6431 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006432{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006434 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006435 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436 PyObject *errorHandler = NULL;
6437 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006438
Victor Stinner62ec3312016-09-06 17:04:34 -07006439 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006440 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006441 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006442
Guido van Rossumd57fd912000-03-10 22:53:23 +00006443 /* Escaped strings will always be longer than the resulting
6444 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 length after conversion to the true value. (But decoding error
6446 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006447 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006448 writer.min_length = size;
6449 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6450 goto onError;
6451 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006452
Guido van Rossumd57fd912000-03-10 22:53:23 +00006453 end = s + size;
6454 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006455 unsigned char c = (unsigned char) *s++;
6456 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006457 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006458 Py_ssize_t startinpos;
6459 Py_ssize_t endinpos;
6460 const char *message;
6461
6462#define WRITE_CHAR(ch) \
6463 do { \
6464 if (ch <= writer.maxchar) { \
6465 assert(writer.pos < writer.size); \
6466 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6467 } \
6468 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6469 goto onError; \
6470 } \
6471 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006472
Benjamin Peterson29060642009-01-31 22:14:21 +00006473 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006474 if (c != '\\' || s >= end) {
6475 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006477 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006478
Victor Stinner62ec3312016-09-06 17:04:34 -07006479 c = (unsigned char) *s++;
6480 if (c == 'u') {
6481 count = 4;
6482 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006483 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006484 else if (c == 'U') {
6485 count = 8;
6486 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006487 }
6488 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006489 assert(writer.pos < writer.size);
6490 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6491 WRITE_CHAR(c);
6492 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006493 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006494 startinpos = s - starts - 2;
6495
6496 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6497 for (ch = 0; count && s < end; ++s, --count) {
6498 c = (unsigned char)*s;
6499 ch <<= 4;
6500 if (c >= '0' && c <= '9') {
6501 ch += c - '0';
6502 }
6503 else if (c >= 'a' && c <= 'f') {
6504 ch += c - ('a' - 10);
6505 }
6506 else if (c >= 'A' && c <= 'F') {
6507 ch += c - ('A' - 10);
6508 }
6509 else {
6510 break;
6511 }
6512 }
6513 if (!count) {
6514 if (ch <= MAX_UNICODE) {
6515 WRITE_CHAR(ch);
6516 continue;
6517 }
6518 message = "\\Uxxxxxxxx out of range";
6519 }
6520
6521 endinpos = s-starts;
6522 writer.min_length = end - s + writer.pos;
6523 if (unicode_decode_call_errorhandler_writer(
6524 errors, &errorHandler,
6525 "rawunicodeescape", message,
6526 &starts, &end, &startinpos, &endinpos, &exc, &s,
6527 &writer)) {
6528 goto onError;
6529 }
6530 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6531 goto onError;
6532 }
6533
6534#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006535 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006536 Py_XDECREF(errorHandler);
6537 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006538 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006539
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006541 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542 Py_XDECREF(errorHandler);
6543 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006544 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006545
Guido van Rossumd57fd912000-03-10 22:53:23 +00006546}
6547
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006548
Alexander Belopolsky40018472011-02-26 01:02:56 +00006549PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006550PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006551{
Victor Stinner62ec3312016-09-06 17:04:34 -07006552 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006553 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006554 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006555 int kind;
6556 void *data;
6557 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006558
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006559 if (!PyUnicode_Check(unicode)) {
6560 PyErr_BadArgument();
6561 return NULL;
6562 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006563 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006564 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006565 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006566 kind = PyUnicode_KIND(unicode);
6567 data = PyUnicode_DATA(unicode);
6568 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006569 if (kind == PyUnicode_1BYTE_KIND) {
6570 return PyBytes_FromStringAndSize(data, len);
6571 }
Victor Stinner0e368262011-11-10 20:12:49 +01006572
Victor Stinner62ec3312016-09-06 17:04:34 -07006573 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6574 bytes, and 1 byte characters 4. */
6575 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006576
Victor Stinner62ec3312016-09-06 17:04:34 -07006577 if (len > PY_SSIZE_T_MAX / expandsize) {
6578 return PyErr_NoMemory();
6579 }
6580 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6581 if (repr == NULL) {
6582 return NULL;
6583 }
6584 if (len == 0) {
6585 return repr;
6586 }
6587
6588 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006589 for (pos = 0; pos < len; pos++) {
6590 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006591
Victor Stinner62ec3312016-09-06 17:04:34 -07006592 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6593 if (ch < 0x100) {
6594 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006595 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006596 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6597 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006598 *p++ = '\\';
6599 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006600 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6601 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6602 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6603 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006605 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6606 else {
6607 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6608 *p++ = '\\';
6609 *p++ = 'U';
6610 *p++ = '0';
6611 *p++ = '0';
6612 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6613 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6614 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6615 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6616 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6617 *p++ = Py_hexdigits[ch & 15];
6618 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006619 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006620
Victor Stinner62ec3312016-09-06 17:04:34 -07006621 assert(p > PyBytes_AS_STRING(repr));
6622 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6623 return NULL;
6624 }
6625 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006626}
6627
Alexander Belopolsky40018472011-02-26 01:02:56 +00006628PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006629PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6630 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006632 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006633 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006634 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006635 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006636 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6637 Py_DECREF(tmp);
6638 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006639}
6640
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006641/* --- Unicode Internal Codec ------------------------------------------- */
6642
Alexander Belopolsky40018472011-02-26 01:02:56 +00006643PyObject *
6644_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006645 Py_ssize_t size,
6646 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006647{
6648 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006649 Py_ssize_t startinpos;
6650 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006651 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006652 const char *end;
6653 const char *reason;
6654 PyObject *errorHandler = NULL;
6655 PyObject *exc = NULL;
6656
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006657 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006658 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006659 1))
6660 return NULL;
6661
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006662 if (size < 0) {
6663 PyErr_BadInternalCall();
6664 return NULL;
6665 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006666 if (size == 0)
6667 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006668
Victor Stinner8f674cc2013-04-17 23:02:17 +02006669 _PyUnicodeWriter_Init(&writer);
6670 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6671 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006672 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006673 }
6674 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006675
Victor Stinner8f674cc2013-04-17 23:02:17 +02006676 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006677 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006678 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006679 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006680 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006681 endinpos = end-starts;
6682 reason = "truncated input";
6683 goto error;
6684 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006685 /* We copy the raw representation one byte at a time because the
6686 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006687 ((char *) &uch)[0] = s[0];
6688 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006689#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006690 ((char *) &uch)[2] = s[2];
6691 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006692#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006693 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006694#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006695 /* We have to sanity check the raw data, otherwise doom looms for
6696 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006697 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006698 endinpos = s - starts + Py_UNICODE_SIZE;
6699 reason = "illegal code point (> 0x10FFFF)";
6700 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006701 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006702#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006703 s += Py_UNICODE_SIZE;
6704#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006705 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006706 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006707 Py_UNICODE uch2;
6708 ((char *) &uch2)[0] = s[0];
6709 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006710 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006711 {
Victor Stinner551ac952011-11-29 22:58:13 +01006712 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006713 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006714 }
6715 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006716#endif
6717
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006718 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006719 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006720 continue;
6721
6722 error:
6723 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006724 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006725 errors, &errorHandler,
6726 "unicode_internal", reason,
6727 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006728 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006729 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006730 }
6731
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006732 Py_XDECREF(errorHandler);
6733 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006734 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006735
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006737 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006738 Py_XDECREF(errorHandler);
6739 Py_XDECREF(exc);
6740 return NULL;
6741}
6742
Guido van Rossumd57fd912000-03-10 22:53:23 +00006743/* --- Latin-1 Codec ------------------------------------------------------ */
6744
Alexander Belopolsky40018472011-02-26 01:02:56 +00006745PyObject *
6746PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006747 Py_ssize_t size,
6748 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006750 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006751 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752}
6753
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006755static void
6756make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006757 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006758 PyObject *unicode,
6759 Py_ssize_t startpos, Py_ssize_t endpos,
6760 const char *reason)
6761{
6762 if (*exceptionObject == NULL) {
6763 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006764 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006765 encoding, unicode, startpos, endpos, reason);
6766 }
6767 else {
6768 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6769 goto onError;
6770 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6771 goto onError;
6772 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6773 goto onError;
6774 return;
6775 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006776 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006777 }
6778}
6779
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006780/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006781static void
6782raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006783 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006784 PyObject *unicode,
6785 Py_ssize_t startpos, Py_ssize_t endpos,
6786 const char *reason)
6787{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006788 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006789 encoding, unicode, startpos, endpos, reason);
6790 if (*exceptionObject != NULL)
6791 PyCodec_StrictErrors(*exceptionObject);
6792}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006793
6794/* error handling callback helper:
6795 build arguments, call the callback and check the arguments,
6796 put the result into newpos and return the replacement string, which
6797 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006798static PyObject *
6799unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006800 PyObject **errorHandler,
6801 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006802 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006803 Py_ssize_t startpos, Py_ssize_t endpos,
6804 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006805{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006806 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006807 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006808 PyObject *restuple;
6809 PyObject *resunicode;
6810
6811 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006812 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006813 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006814 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006815 }
6816
Benjamin Petersonbac79492012-01-14 13:34:47 -05006817 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006818 return NULL;
6819 len = PyUnicode_GET_LENGTH(unicode);
6820
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006821 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006822 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006823 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006824 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006825
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006826 restuple = PyObject_CallFunctionObjArgs(
6827 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006828 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006829 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006830 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006831 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006832 Py_DECREF(restuple);
6833 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006834 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006835 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006836 &resunicode, newpos)) {
6837 Py_DECREF(restuple);
6838 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006839 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006840 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6841 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6842 Py_DECREF(restuple);
6843 return NULL;
6844 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006846 *newpos = len + *newpos;
6847 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006848 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006849 Py_DECREF(restuple);
6850 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006851 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006852 Py_INCREF(resunicode);
6853 Py_DECREF(restuple);
6854 return resunicode;
6855}
6856
Alexander Belopolsky40018472011-02-26 01:02:56 +00006857static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006858unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006859 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006860 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006861{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006862 /* input state */
6863 Py_ssize_t pos=0, size;
6864 int kind;
6865 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006866 /* pointer into the output */
6867 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006868 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6869 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006870 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006871 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006872 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006873 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006874 /* output object */
6875 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006876
Benjamin Petersonbac79492012-01-14 13:34:47 -05006877 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006878 return NULL;
6879 size = PyUnicode_GET_LENGTH(unicode);
6880 kind = PyUnicode_KIND(unicode);
6881 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882 /* allocate enough for a simple encoding without
6883 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006884 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006885 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006886
6887 _PyBytesWriter_Init(&writer);
6888 str = _PyBytesWriter_Alloc(&writer, size);
6889 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006890 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006891
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006892 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006893 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006894
Benjamin Peterson29060642009-01-31 22:14:21 +00006895 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006896 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006897 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006898 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006899 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006900 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006901 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006902 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006903 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006904 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006905 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006906 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006907
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006908 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006909 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006910
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006911 /* Only overallocate the buffer if it's not the last write */
6912 writer.overallocate = (collend < size);
6913
Benjamin Peterson29060642009-01-31 22:14:21 +00006914 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006915 if (error_handler == _Py_ERROR_UNKNOWN)
6916 error_handler = get_error_handler(errors);
6917
6918 switch (error_handler) {
6919 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006920 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006921 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006922
6923 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006924 memset(str, '?', collend - collstart);
6925 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006926 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006927 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006928 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006929 break;
Victor Stinner50149202015-09-22 00:26:54 +02006930
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006931 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006932 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006933 writer.min_size -= (collend - collstart);
6934 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006935 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006936 if (str == NULL)
6937 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006938 pos = collend;
6939 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006940
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006941 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006942 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006943 writer.min_size -= (collend - collstart);
6944 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006945 unicode, collstart, collend);
6946 if (str == NULL)
6947 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006948 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006949 break;
Victor Stinner50149202015-09-22 00:26:54 +02006950
Victor Stinnerc3713e92015-09-29 12:32:13 +02006951 case _Py_ERROR_SURROGATEESCAPE:
6952 for (i = collstart; i < collend; ++i) {
6953 ch = PyUnicode_READ(kind, data, i);
6954 if (ch < 0xdc80 || 0xdcff < ch) {
6955 /* Not a UTF-8b surrogate */
6956 break;
6957 }
6958 *str++ = (char)(ch - 0xdc00);
6959 ++pos;
6960 }
6961 if (i >= collend)
6962 break;
6963 collstart = pos;
6964 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006965 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006966
Benjamin Peterson29060642009-01-31 22:14:21 +00006967 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006968 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6969 encoding, reason, unicode, &exc,
6970 collstart, collend, &newpos);
6971 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006972 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006973
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006974 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006975 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006976
Victor Stinner6bd525b2015-10-09 13:10:05 +02006977 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006978 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006979 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006980 PyBytes_AS_STRING(rep),
6981 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006982 if (str == NULL)
6983 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006984 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006985 else {
6986 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006987
Victor Stinner6bd525b2015-10-09 13:10:05 +02006988 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006989 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006990
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006991 if (limit == 256 ?
6992 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6993 !PyUnicode_IS_ASCII(rep))
6994 {
6995 /* Not all characters are smaller than limit */
6996 raise_encode_exception(&exc, encoding, unicode,
6997 collstart, collend, reason);
6998 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006999 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02007000 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
7001 str = _PyBytesWriter_WriteBytes(&writer, str,
7002 PyUnicode_DATA(rep),
7003 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00007004 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007005 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02007006 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007007 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007008
7009 /* If overallocation was disabled, ensure that it was the last
7010 write. Otherwise, we missed an optimization */
7011 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007012 }
7013 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007014
Victor Stinner50149202015-09-22 00:26:54 +02007015 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007016 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007017 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007018
7019 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02007020 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007021 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02007022 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007023 Py_XDECREF(exc);
7024 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007025}
7026
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007027/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007028PyObject *
7029PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03007030 Py_ssize_t size,
7031 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007032{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007033 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007034 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007035 if (unicode == NULL)
7036 return NULL;
7037 result = unicode_encode_ucs1(unicode, errors, 256);
7038 Py_DECREF(unicode);
7039 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007040}
7041
Alexander Belopolsky40018472011-02-26 01:02:56 +00007042PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007043_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007044{
7045 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007046 PyErr_BadArgument();
7047 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007049 if (PyUnicode_READY(unicode) == -1)
7050 return NULL;
7051 /* Fast path: if it is a one-byte string, construct
7052 bytes object directly. */
7053 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7054 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7055 PyUnicode_GET_LENGTH(unicode));
7056 /* Non-Latin-1 characters present. Defer to above function to
7057 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007058 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007059}
7060
7061PyObject*
7062PyUnicode_AsLatin1String(PyObject *unicode)
7063{
7064 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007065}
7066
7067/* --- 7-bit ASCII Codec -------------------------------------------------- */
7068
Alexander Belopolsky40018472011-02-26 01:02:56 +00007069PyObject *
7070PyUnicode_DecodeASCII(const char *s,
7071 Py_ssize_t size,
7072 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007073{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007074 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007075 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007076 int kind;
7077 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007078 Py_ssize_t startinpos;
7079 Py_ssize_t endinpos;
7080 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007081 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007082 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007083 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007084 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00007085
Guido van Rossumd57fd912000-03-10 22:53:23 +00007086 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02007087 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007088
Guido van Rossumd57fd912000-03-10 22:53:23 +00007089 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02007090 if (size == 1 && (unsigned char)s[0] < 128)
7091 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007092
Victor Stinner8f674cc2013-04-17 23:02:17 +02007093 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007094 writer.min_length = size;
7095 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02007096 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007097
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007098 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007099 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007100 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007101 writer.pos = outpos;
7102 if (writer.pos == size)
7103 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007104
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007105 s += writer.pos;
7106 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007107 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007108 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007109 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007110 PyUnicode_WRITE(kind, data, writer.pos, c);
7111 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007112 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007113 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007114 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007115
7116 /* byte outsize range 0x00..0x7f: call the error handler */
7117
7118 if (error_handler == _Py_ERROR_UNKNOWN)
7119 error_handler = get_error_handler(errors);
7120
7121 switch (error_handler)
7122 {
7123 case _Py_ERROR_REPLACE:
7124 case _Py_ERROR_SURROGATEESCAPE:
7125 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007126 but we may switch to UCS2 at the first write */
7127 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7128 goto onError;
7129 kind = writer.kind;
7130 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007131
7132 if (error_handler == _Py_ERROR_REPLACE)
7133 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7134 else
7135 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7136 writer.pos++;
7137 ++s;
7138 break;
7139
7140 case _Py_ERROR_IGNORE:
7141 ++s;
7142 break;
7143
7144 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007145 startinpos = s-starts;
7146 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007147 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007148 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007149 "ascii", "ordinal not in range(128)",
7150 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007151 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007152 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007153 kind = writer.kind;
7154 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007155 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007156 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007157 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007158 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007159 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007160
Benjamin Peterson29060642009-01-31 22:14:21 +00007161 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007162 _PyUnicodeWriter_Dealloc(&writer);
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);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007165 return NULL;
7166}
7167
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007168/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007169PyObject *
7170PyUnicode_EncodeASCII(const Py_UNICODE *p,
7171 Py_ssize_t size,
7172 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007173{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007174 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007175 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007176 if (unicode == NULL)
7177 return NULL;
7178 result = unicode_encode_ucs1(unicode, errors, 128);
7179 Py_DECREF(unicode);
7180 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007181}
7182
Alexander Belopolsky40018472011-02-26 01:02:56 +00007183PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007184_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007185{
7186 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007187 PyErr_BadArgument();
7188 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007190 if (PyUnicode_READY(unicode) == -1)
7191 return NULL;
7192 /* Fast path: if it is an ASCII-only string, construct bytes object
7193 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007194 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007195 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7196 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007197 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007198}
7199
7200PyObject *
7201PyUnicode_AsASCIIString(PyObject *unicode)
7202{
7203 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007204}
7205
Steve Dowercc16be82016-09-08 10:35:16 -07007206#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007207
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007208/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007209
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007210#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211#define NEED_RETRY
7212#endif
7213
Victor Stinner3a50e702011-10-18 21:21:00 +02007214#ifndef WC_ERR_INVALID_CHARS
7215# define WC_ERR_INVALID_CHARS 0x0080
7216#endif
7217
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007218static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007219code_page_name(UINT code_page, PyObject **obj)
7220{
7221 *obj = NULL;
7222 if (code_page == CP_ACP)
7223 return "mbcs";
7224 if (code_page == CP_UTF7)
7225 return "CP_UTF7";
7226 if (code_page == CP_UTF8)
7227 return "CP_UTF8";
7228
7229 *obj = PyBytes_FromFormat("cp%u", code_page);
7230 if (*obj == NULL)
7231 return NULL;
7232 return PyBytes_AS_STRING(*obj);
7233}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007234
Victor Stinner3a50e702011-10-18 21:21:00 +02007235static DWORD
7236decode_code_page_flags(UINT code_page)
7237{
7238 if (code_page == CP_UTF7) {
7239 /* The CP_UTF7 decoder only supports flags=0 */
7240 return 0;
7241 }
7242 else
7243 return MB_ERR_INVALID_CHARS;
7244}
7245
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007246/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 * Decode a byte string from a Windows code page into unicode object in strict
7248 * mode.
7249 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007250 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7251 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007252 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007253static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007254decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007255 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 const char *in,
7257 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007258{
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007260 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007262
7263 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 assert(insize > 0);
7265 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7266 if (outsize <= 0)
7267 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007268
7269 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007270 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007271 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007273 if (*v == NULL)
7274 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007276 }
7277 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007278 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007279 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007280 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007281 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007282 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283 }
7284
7285 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7287 if (outsize <= 0)
7288 goto error;
7289 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007290
Victor Stinner3a50e702011-10-18 21:21:00 +02007291error:
7292 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7293 return -2;
7294 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007295 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007296}
7297
Victor Stinner3a50e702011-10-18 21:21:00 +02007298/*
7299 * Decode a byte string from a code page into unicode object with an error
7300 * handler.
7301 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007302 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007303 * UnicodeDecodeError exception and returns -1 on error.
7304 */
7305static int
7306decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007307 PyObject **v,
7308 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007309 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007310{
7311 const char *startin = in;
7312 const char *endin = in + size;
7313 const DWORD flags = decode_code_page_flags(code_page);
7314 /* Ideally, we should get reason from FormatMessage. This is the Windows
7315 2000 English version of the message. */
7316 const char *reason = "No mapping for the Unicode character exists "
7317 "in the target code page.";
7318 /* each step cannot decode more than 1 character, but a character can be
7319 represented as a surrogate pair */
7320 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007321 int insize;
7322 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007323 PyObject *errorHandler = NULL;
7324 PyObject *exc = NULL;
7325 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007326 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 DWORD err;
7328 int ret = -1;
7329
7330 assert(size > 0);
7331
7332 encoding = code_page_name(code_page, &encoding_obj);
7333 if (encoding == NULL)
7334 return -1;
7335
Victor Stinner7d00cc12014-03-17 23:08:06 +01007336 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7338 UnicodeDecodeError. */
7339 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7340 if (exc != NULL) {
7341 PyCodec_StrictErrors(exc);
7342 Py_CLEAR(exc);
7343 }
7344 goto error;
7345 }
7346
7347 if (*v == NULL) {
7348 /* Create unicode object */
7349 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7350 PyErr_NoMemory();
7351 goto error;
7352 }
Victor Stinnerab595942011-12-17 04:59:06 +01007353 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007354 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 if (*v == NULL)
7356 goto error;
7357 startout = PyUnicode_AS_UNICODE(*v);
7358 }
7359 else {
7360 /* Extend unicode object */
7361 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7362 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7363 PyErr_NoMemory();
7364 goto error;
7365 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007366 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 goto error;
7368 startout = PyUnicode_AS_UNICODE(*v) + n;
7369 }
7370
7371 /* Decode the byte string character per character */
7372 out = startout;
7373 while (in < endin)
7374 {
7375 /* Decode a character */
7376 insize = 1;
7377 do
7378 {
7379 outsize = MultiByteToWideChar(code_page, flags,
7380 in, insize,
7381 buffer, Py_ARRAY_LENGTH(buffer));
7382 if (outsize > 0)
7383 break;
7384 err = GetLastError();
7385 if (err != ERROR_NO_UNICODE_TRANSLATION
7386 && err != ERROR_INSUFFICIENT_BUFFER)
7387 {
7388 PyErr_SetFromWindowsErr(0);
7389 goto error;
7390 }
7391 insize++;
7392 }
7393 /* 4=maximum length of a UTF-8 sequence */
7394 while (insize <= 4 && (in + insize) <= endin);
7395
7396 if (outsize <= 0) {
7397 Py_ssize_t startinpos, endinpos, outpos;
7398
Victor Stinner7d00cc12014-03-17 23:08:06 +01007399 /* last character in partial decode? */
7400 if (in + insize >= endin && !final)
7401 break;
7402
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 startinpos = in - startin;
7404 endinpos = startinpos + 1;
7405 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007406 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 errors, &errorHandler,
7408 encoding, reason,
7409 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007410 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 {
7412 goto error;
7413 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007414 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 }
7416 else {
7417 in += insize;
7418 memcpy(out, buffer, outsize * sizeof(wchar_t));
7419 out += outsize;
7420 }
7421 }
7422
7423 /* write a NUL character at the end */
7424 *out = 0;
7425
7426 /* Extend unicode object */
7427 outsize = out - startout;
7428 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007429 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007431 /* (in - startin) <= size and size is an int */
7432 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007433
7434error:
7435 Py_XDECREF(encoding_obj);
7436 Py_XDECREF(errorHandler);
7437 Py_XDECREF(exc);
7438 return ret;
7439}
7440
Victor Stinner3a50e702011-10-18 21:21:00 +02007441static PyObject *
7442decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007443 const char *s, Py_ssize_t size,
7444 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445{
Victor Stinner76a31a62011-11-04 00:05:13 +01007446 PyObject *v = NULL;
7447 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007448
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 if (code_page < 0) {
7450 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7451 return NULL;
7452 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007453 if (size < 0) {
7454 PyErr_BadInternalCall();
7455 return NULL;
7456 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007457
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007458 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007459 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007460
Victor Stinner76a31a62011-11-04 00:05:13 +01007461 do
7462 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007463#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007464 if (size > INT_MAX) {
7465 chunk_size = INT_MAX;
7466 final = 0;
7467 done = 0;
7468 }
7469 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007470#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007471 {
7472 chunk_size = (int)size;
7473 final = (consumed == NULL);
7474 done = 1;
7475 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007476
Victor Stinner76a31a62011-11-04 00:05:13 +01007477 if (chunk_size == 0 && done) {
7478 if (v != NULL)
7479 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007480 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007481 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007482
Victor Stinner76a31a62011-11-04 00:05:13 +01007483 converted = decode_code_page_strict(code_page, &v,
7484 s, chunk_size);
7485 if (converted == -2)
7486 converted = decode_code_page_errors(code_page, &v,
7487 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007488 errors, final);
7489 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007490
7491 if (converted < 0) {
7492 Py_XDECREF(v);
7493 return NULL;
7494 }
7495
7496 if (consumed)
7497 *consumed += converted;
7498
7499 s += converted;
7500 size -= converted;
7501 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007502
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007503 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007504}
7505
Alexander Belopolsky40018472011-02-26 01:02:56 +00007506PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007507PyUnicode_DecodeCodePageStateful(int code_page,
7508 const char *s,
7509 Py_ssize_t size,
7510 const char *errors,
7511 Py_ssize_t *consumed)
7512{
7513 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7514}
7515
7516PyObject *
7517PyUnicode_DecodeMBCSStateful(const char *s,
7518 Py_ssize_t size,
7519 const char *errors,
7520 Py_ssize_t *consumed)
7521{
7522 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7523}
7524
7525PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007526PyUnicode_DecodeMBCS(const char *s,
7527 Py_ssize_t size,
7528 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007529{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007530 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7531}
7532
Victor Stinner3a50e702011-10-18 21:21:00 +02007533static DWORD
7534encode_code_page_flags(UINT code_page, const char *errors)
7535{
7536 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007537 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 }
7539 else if (code_page == CP_UTF7) {
7540 /* CP_UTF7 only supports flags=0 */
7541 return 0;
7542 }
7543 else {
7544 if (errors != NULL && strcmp(errors, "replace") == 0)
7545 return 0;
7546 else
7547 return WC_NO_BEST_FIT_CHARS;
7548 }
7549}
7550
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007551/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007552 * Encode a Unicode string to a Windows code page into a byte string in strict
7553 * mode.
7554 *
7555 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007556 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007557 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007558static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007559encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007560 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007562{
Victor Stinner554f3f02010-06-16 23:33:54 +00007563 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 BOOL *pusedDefaultChar = &usedDefaultChar;
7565 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007566 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007567 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 const DWORD flags = encode_code_page_flags(code_page, NULL);
7569 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007570 /* Create a substring so that we can get the UTF-16 representation
7571 of just the slice under consideration. */
7572 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007573
Martin v. Löwis3d325192011-11-04 18:23:06 +01007574 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007575
Victor Stinner3a50e702011-10-18 21:21:00 +02007576 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007577 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007578 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007579 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007580
Victor Stinner2fc507f2011-11-04 20:06:39 +01007581 substring = PyUnicode_Substring(unicode, offset, offset+len);
7582 if (substring == NULL)
7583 return -1;
7584 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7585 if (p == NULL) {
7586 Py_DECREF(substring);
7587 return -1;
7588 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007589 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007590
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007591 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007592 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007593 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007594 NULL, 0,
7595 NULL, pusedDefaultChar);
7596 if (outsize <= 0)
7597 goto error;
7598 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007599 if (pusedDefaultChar && *pusedDefaultChar) {
7600 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007601 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007602 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007603
Victor Stinner3a50e702011-10-18 21:21:00 +02007604 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007606 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007607 if (*outbytes == NULL) {
7608 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007609 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007610 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007611 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007612 }
7613 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007615 const Py_ssize_t n = PyBytes_Size(*outbytes);
7616 if (outsize > PY_SSIZE_T_MAX - n) {
7617 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007618 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007619 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007620 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007621 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7622 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007624 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007625 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007626 }
7627
7628 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007629 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007630 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007631 out, outsize,
7632 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007633 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007634 if (outsize <= 0)
7635 goto error;
7636 if (pusedDefaultChar && *pusedDefaultChar)
7637 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007638 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007639
Victor Stinner3a50e702011-10-18 21:21:00 +02007640error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007641 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007642 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7643 return -2;
7644 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007645 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007646}
7647
Victor Stinner3a50e702011-10-18 21:21:00 +02007648/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007649 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007650 * error handler.
7651 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007652 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007653 * -1 on other error.
7654 */
7655static int
7656encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007657 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007658 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007659{
Victor Stinner3a50e702011-10-18 21:21:00 +02007660 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007661 Py_ssize_t pos = unicode_offset;
7662 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007663 /* Ideally, we should get reason from FormatMessage. This is the Windows
7664 2000 English version of the message. */
7665 const char *reason = "invalid character";
7666 /* 4=maximum length of a UTF-8 sequence */
7667 char buffer[4];
7668 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7669 Py_ssize_t outsize;
7670 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007671 PyObject *errorHandler = NULL;
7672 PyObject *exc = NULL;
7673 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007674 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007675 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007676 PyObject *rep;
7677 int ret = -1;
7678
7679 assert(insize > 0);
7680
7681 encoding = code_page_name(code_page, &encoding_obj);
7682 if (encoding == NULL)
7683 return -1;
7684
7685 if (errors == NULL || strcmp(errors, "strict") == 0) {
7686 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7687 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007688 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007689 if (exc != NULL) {
7690 PyCodec_StrictErrors(exc);
7691 Py_DECREF(exc);
7692 }
7693 Py_XDECREF(encoding_obj);
7694 return -1;
7695 }
7696
7697 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7698 pusedDefaultChar = &usedDefaultChar;
7699 else
7700 pusedDefaultChar = NULL;
7701
7702 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7703 PyErr_NoMemory();
7704 goto error;
7705 }
7706 outsize = insize * Py_ARRAY_LENGTH(buffer);
7707
7708 if (*outbytes == NULL) {
7709 /* Create string object */
7710 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7711 if (*outbytes == NULL)
7712 goto error;
7713 out = PyBytes_AS_STRING(*outbytes);
7714 }
7715 else {
7716 /* Extend string object */
7717 Py_ssize_t n = PyBytes_Size(*outbytes);
7718 if (n > PY_SSIZE_T_MAX - outsize) {
7719 PyErr_NoMemory();
7720 goto error;
7721 }
7722 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7723 goto error;
7724 out = PyBytes_AS_STRING(*outbytes) + n;
7725 }
7726
7727 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007728 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007729 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007730 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7731 wchar_t chars[2];
7732 int charsize;
7733 if (ch < 0x10000) {
7734 chars[0] = (wchar_t)ch;
7735 charsize = 1;
7736 }
7737 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007738 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7739 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007740 charsize = 2;
7741 }
7742
Victor Stinner3a50e702011-10-18 21:21:00 +02007743 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007744 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007745 buffer, Py_ARRAY_LENGTH(buffer),
7746 NULL, pusedDefaultChar);
7747 if (outsize > 0) {
7748 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7749 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007750 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007751 memcpy(out, buffer, outsize);
7752 out += outsize;
7753 continue;
7754 }
7755 }
7756 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7757 PyErr_SetFromWindowsErr(0);
7758 goto error;
7759 }
7760
Victor Stinner3a50e702011-10-18 21:21:00 +02007761 rep = unicode_encode_call_errorhandler(
7762 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007763 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007764 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007765 if (rep == NULL)
7766 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007767 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007768
7769 if (PyBytes_Check(rep)) {
7770 outsize = PyBytes_GET_SIZE(rep);
7771 if (outsize != 1) {
7772 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7773 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7774 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7775 Py_DECREF(rep);
7776 goto error;
7777 }
7778 out = PyBytes_AS_STRING(*outbytes) + offset;
7779 }
7780 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7781 out += outsize;
7782 }
7783 else {
7784 Py_ssize_t i;
7785 enum PyUnicode_Kind kind;
7786 void *data;
7787
Benjamin Petersonbac79492012-01-14 13:34:47 -05007788 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007789 Py_DECREF(rep);
7790 goto error;
7791 }
7792
7793 outsize = PyUnicode_GET_LENGTH(rep);
7794 if (outsize != 1) {
7795 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7796 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7797 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7798 Py_DECREF(rep);
7799 goto error;
7800 }
7801 out = PyBytes_AS_STRING(*outbytes) + offset;
7802 }
7803 kind = PyUnicode_KIND(rep);
7804 data = PyUnicode_DATA(rep);
7805 for (i=0; i < outsize; i++) {
7806 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7807 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007808 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007809 encoding, unicode,
7810 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007811 "unable to encode error handler result to ASCII");
7812 Py_DECREF(rep);
7813 goto error;
7814 }
7815 *out = (unsigned char)ch;
7816 out++;
7817 }
7818 }
7819 Py_DECREF(rep);
7820 }
7821 /* write a NUL byte */
7822 *out = 0;
7823 outsize = out - PyBytes_AS_STRING(*outbytes);
7824 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7825 if (_PyBytes_Resize(outbytes, outsize) < 0)
7826 goto error;
7827 ret = 0;
7828
7829error:
7830 Py_XDECREF(encoding_obj);
7831 Py_XDECREF(errorHandler);
7832 Py_XDECREF(exc);
7833 return ret;
7834}
7835
Victor Stinner3a50e702011-10-18 21:21:00 +02007836static PyObject *
7837encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007838 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007839 const char *errors)
7840{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007841 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007842 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007843 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007844 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007845
Victor Stinner29dacf22015-01-26 16:41:32 +01007846 if (!PyUnicode_Check(unicode)) {
7847 PyErr_BadArgument();
7848 return NULL;
7849 }
7850
Benjamin Petersonbac79492012-01-14 13:34:47 -05007851 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007852 return NULL;
7853 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007854
Victor Stinner3a50e702011-10-18 21:21:00 +02007855 if (code_page < 0) {
7856 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7857 return NULL;
7858 }
7859
Martin v. Löwis3d325192011-11-04 18:23:06 +01007860 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007861 return PyBytes_FromStringAndSize(NULL, 0);
7862
Victor Stinner7581cef2011-11-03 22:32:33 +01007863 offset = 0;
7864 do
7865 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007866#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007867 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007868 chunks. */
7869 if (len > INT_MAX/2) {
7870 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007871 done = 0;
7872 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007873 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007874#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007875 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007876 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007877 done = 1;
7878 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007879
Victor Stinner76a31a62011-11-04 00:05:13 +01007880 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007881 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007882 errors);
7883 if (ret == -2)
7884 ret = encode_code_page_errors(code_page, &outbytes,
7885 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007886 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007887 if (ret < 0) {
7888 Py_XDECREF(outbytes);
7889 return NULL;
7890 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007891
Victor Stinner7581cef2011-11-03 22:32:33 +01007892 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007893 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007894 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007895
Victor Stinner3a50e702011-10-18 21:21:00 +02007896 return outbytes;
7897}
7898
7899PyObject *
7900PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7901 Py_ssize_t size,
7902 const char *errors)
7903{
Victor Stinner7581cef2011-11-03 22:32:33 +01007904 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007905 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007906 if (unicode == NULL)
7907 return NULL;
7908 res = encode_code_page(CP_ACP, unicode, errors);
7909 Py_DECREF(unicode);
7910 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007911}
7912
7913PyObject *
7914PyUnicode_EncodeCodePage(int code_page,
7915 PyObject *unicode,
7916 const char *errors)
7917{
Victor Stinner7581cef2011-11-03 22:32:33 +01007918 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007919}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007920
Alexander Belopolsky40018472011-02-26 01:02:56 +00007921PyObject *
7922PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007923{
Victor Stinner7581cef2011-11-03 22:32:33 +01007924 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007925}
7926
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007927#undef NEED_RETRY
7928
Steve Dowercc16be82016-09-08 10:35:16 -07007929#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007930
Guido van Rossumd57fd912000-03-10 22:53:23 +00007931/* --- Character Mapping Codec -------------------------------------------- */
7932
Victor Stinnerfb161b12013-04-18 01:44:27 +02007933static int
7934charmap_decode_string(const char *s,
7935 Py_ssize_t size,
7936 PyObject *mapping,
7937 const char *errors,
7938 _PyUnicodeWriter *writer)
7939{
7940 const char *starts = s;
7941 const char *e;
7942 Py_ssize_t startinpos, endinpos;
7943 PyObject *errorHandler = NULL, *exc = NULL;
7944 Py_ssize_t maplen;
7945 enum PyUnicode_Kind mapkind;
7946 void *mapdata;
7947 Py_UCS4 x;
7948 unsigned char ch;
7949
7950 if (PyUnicode_READY(mapping) == -1)
7951 return -1;
7952
7953 maplen = PyUnicode_GET_LENGTH(mapping);
7954 mapdata = PyUnicode_DATA(mapping);
7955 mapkind = PyUnicode_KIND(mapping);
7956
7957 e = s + size;
7958
7959 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7960 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7961 * is disabled in encoding aliases, latin1 is preferred because
7962 * its implementation is faster. */
7963 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7964 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7965 Py_UCS4 maxchar = writer->maxchar;
7966
7967 assert (writer->kind == PyUnicode_1BYTE_KIND);
7968 while (s < e) {
7969 ch = *s;
7970 x = mapdata_ucs1[ch];
7971 if (x > maxchar) {
7972 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7973 goto onError;
7974 maxchar = writer->maxchar;
7975 outdata = (Py_UCS1 *)writer->data;
7976 }
7977 outdata[writer->pos] = x;
7978 writer->pos++;
7979 ++s;
7980 }
7981 return 0;
7982 }
7983
7984 while (s < e) {
7985 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7986 enum PyUnicode_Kind outkind = writer->kind;
7987 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7988 if (outkind == PyUnicode_1BYTE_KIND) {
7989 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7990 Py_UCS4 maxchar = writer->maxchar;
7991 while (s < e) {
7992 ch = *s;
7993 x = mapdata_ucs2[ch];
7994 if (x > maxchar)
7995 goto Error;
7996 outdata[writer->pos] = x;
7997 writer->pos++;
7998 ++s;
7999 }
8000 break;
8001 }
8002 else if (outkind == PyUnicode_2BYTE_KIND) {
8003 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8004 while (s < e) {
8005 ch = *s;
8006 x = mapdata_ucs2[ch];
8007 if (x == 0xFFFE)
8008 goto Error;
8009 outdata[writer->pos] = x;
8010 writer->pos++;
8011 ++s;
8012 }
8013 break;
8014 }
8015 }
8016 ch = *s;
8017
8018 if (ch < maplen)
8019 x = PyUnicode_READ(mapkind, mapdata, ch);
8020 else
8021 x = 0xfffe; /* invalid value */
8022Error:
8023 if (x == 0xfffe)
8024 {
8025 /* undefined mapping */
8026 startinpos = s-starts;
8027 endinpos = startinpos+1;
8028 if (unicode_decode_call_errorhandler_writer(
8029 errors, &errorHandler,
8030 "charmap", "character maps to <undefined>",
8031 &starts, &e, &startinpos, &endinpos, &exc, &s,
8032 writer)) {
8033 goto onError;
8034 }
8035 continue;
8036 }
8037
8038 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8039 goto onError;
8040 ++s;
8041 }
8042 Py_XDECREF(errorHandler);
8043 Py_XDECREF(exc);
8044 return 0;
8045
8046onError:
8047 Py_XDECREF(errorHandler);
8048 Py_XDECREF(exc);
8049 return -1;
8050}
8051
8052static int
8053charmap_decode_mapping(const char *s,
8054 Py_ssize_t size,
8055 PyObject *mapping,
8056 const char *errors,
8057 _PyUnicodeWriter *writer)
8058{
8059 const char *starts = s;
8060 const char *e;
8061 Py_ssize_t startinpos, endinpos;
8062 PyObject *errorHandler = NULL, *exc = NULL;
8063 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02008064 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008065
8066 e = s + size;
8067
8068 while (s < e) {
8069 ch = *s;
8070
8071 /* Get mapping (char ordinal -> integer, Unicode char or None) */
8072 key = PyLong_FromLong((long)ch);
8073 if (key == NULL)
8074 goto onError;
8075
8076 item = PyObject_GetItem(mapping, key);
8077 Py_DECREF(key);
8078 if (item == NULL) {
8079 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8080 /* No mapping found means: mapping is undefined. */
8081 PyErr_Clear();
8082 goto Undefined;
8083 } else
8084 goto onError;
8085 }
8086
8087 /* Apply mapping */
8088 if (item == Py_None)
8089 goto Undefined;
8090 if (PyLong_Check(item)) {
8091 long value = PyLong_AS_LONG(item);
8092 if (value == 0xFFFE)
8093 goto Undefined;
8094 if (value < 0 || value > MAX_UNICODE) {
8095 PyErr_Format(PyExc_TypeError,
8096 "character mapping must be in range(0x%lx)",
8097 (unsigned long)MAX_UNICODE + 1);
8098 goto onError;
8099 }
8100
8101 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8102 goto onError;
8103 }
8104 else if (PyUnicode_Check(item)) {
8105 if (PyUnicode_READY(item) == -1)
8106 goto onError;
8107 if (PyUnicode_GET_LENGTH(item) == 1) {
8108 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8109 if (value == 0xFFFE)
8110 goto Undefined;
8111 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8112 goto onError;
8113 }
8114 else {
8115 writer->overallocate = 1;
8116 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8117 goto onError;
8118 }
8119 }
8120 else {
8121 /* wrong return value */
8122 PyErr_SetString(PyExc_TypeError,
8123 "character mapping must return integer, None or str");
8124 goto onError;
8125 }
8126 Py_CLEAR(item);
8127 ++s;
8128 continue;
8129
8130Undefined:
8131 /* undefined mapping */
8132 Py_CLEAR(item);
8133 startinpos = s-starts;
8134 endinpos = startinpos+1;
8135 if (unicode_decode_call_errorhandler_writer(
8136 errors, &errorHandler,
8137 "charmap", "character maps to <undefined>",
8138 &starts, &e, &startinpos, &endinpos, &exc, &s,
8139 writer)) {
8140 goto onError;
8141 }
8142 }
8143 Py_XDECREF(errorHandler);
8144 Py_XDECREF(exc);
8145 return 0;
8146
8147onError:
8148 Py_XDECREF(item);
8149 Py_XDECREF(errorHandler);
8150 Py_XDECREF(exc);
8151 return -1;
8152}
8153
Alexander Belopolsky40018472011-02-26 01:02:56 +00008154PyObject *
8155PyUnicode_DecodeCharmap(const char *s,
8156 Py_ssize_t size,
8157 PyObject *mapping,
8158 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008159{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008160 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008161
Guido van Rossumd57fd912000-03-10 22:53:23 +00008162 /* Default to Latin-1 */
8163 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008165
Guido van Rossumd57fd912000-03-10 22:53:23 +00008166 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008167 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008168 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008169 writer.min_length = size;
8170 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008171 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008172
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008173 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008174 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8175 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008176 }
8177 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008178 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8179 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008180 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008181 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008182
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008184 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008185 return NULL;
8186}
8187
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008188/* Charmap encoding: the lookup table */
8189
Alexander Belopolsky40018472011-02-26 01:02:56 +00008190struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 PyObject_HEAD
8192 unsigned char level1[32];
8193 int count2, count3;
8194 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008195};
8196
8197static PyObject*
8198encoding_map_size(PyObject *obj, PyObject* args)
8199{
8200 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008201 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008203}
8204
8205static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 PyDoc_STR("Return the size (in bytes) of this object") },
8208 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008209};
8210
8211static void
8212encoding_map_dealloc(PyObject* o)
8213{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008214 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008215}
8216
8217static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008218 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 "EncodingMap", /*tp_name*/
8220 sizeof(struct encoding_map), /*tp_basicsize*/
8221 0, /*tp_itemsize*/
8222 /* methods */
8223 encoding_map_dealloc, /*tp_dealloc*/
8224 0, /*tp_print*/
8225 0, /*tp_getattr*/
8226 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008227 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 0, /*tp_repr*/
8229 0, /*tp_as_number*/
8230 0, /*tp_as_sequence*/
8231 0, /*tp_as_mapping*/
8232 0, /*tp_hash*/
8233 0, /*tp_call*/
8234 0, /*tp_str*/
8235 0, /*tp_getattro*/
8236 0, /*tp_setattro*/
8237 0, /*tp_as_buffer*/
8238 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8239 0, /*tp_doc*/
8240 0, /*tp_traverse*/
8241 0, /*tp_clear*/
8242 0, /*tp_richcompare*/
8243 0, /*tp_weaklistoffset*/
8244 0, /*tp_iter*/
8245 0, /*tp_iternext*/
8246 encoding_map_methods, /*tp_methods*/
8247 0, /*tp_members*/
8248 0, /*tp_getset*/
8249 0, /*tp_base*/
8250 0, /*tp_dict*/
8251 0, /*tp_descr_get*/
8252 0, /*tp_descr_set*/
8253 0, /*tp_dictoffset*/
8254 0, /*tp_init*/
8255 0, /*tp_alloc*/
8256 0, /*tp_new*/
8257 0, /*tp_free*/
8258 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008259};
8260
8261PyObject*
8262PyUnicode_BuildEncodingMap(PyObject* string)
8263{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008264 PyObject *result;
8265 struct encoding_map *mresult;
8266 int i;
8267 int need_dict = 0;
8268 unsigned char level1[32];
8269 unsigned char level2[512];
8270 unsigned char *mlevel1, *mlevel2, *mlevel3;
8271 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008272 int kind;
8273 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008274 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008275 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008276
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008277 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008278 PyErr_BadArgument();
8279 return NULL;
8280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281 kind = PyUnicode_KIND(string);
8282 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008283 length = PyUnicode_GET_LENGTH(string);
8284 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008285 memset(level1, 0xFF, sizeof level1);
8286 memset(level2, 0xFF, sizeof level2);
8287
8288 /* If there isn't a one-to-one mapping of NULL to \0,
8289 or if there are non-BMP characters, we need to use
8290 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008291 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008292 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008293 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008294 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008295 ch = PyUnicode_READ(kind, data, i);
8296 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008297 need_dict = 1;
8298 break;
8299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008300 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008301 /* unmapped character */
8302 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008303 l1 = ch >> 11;
8304 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305 if (level1[l1] == 0xFF)
8306 level1[l1] = count2++;
8307 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008308 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008309 }
8310
8311 if (count2 >= 0xFF || count3 >= 0xFF)
8312 need_dict = 1;
8313
8314 if (need_dict) {
8315 PyObject *result = PyDict_New();
8316 PyObject *key, *value;
8317 if (!result)
8318 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008319 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008320 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008321 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008322 if (!key || !value)
8323 goto failed1;
8324 if (PyDict_SetItem(result, key, value) == -1)
8325 goto failed1;
8326 Py_DECREF(key);
8327 Py_DECREF(value);
8328 }
8329 return result;
8330 failed1:
8331 Py_XDECREF(key);
8332 Py_XDECREF(value);
8333 Py_DECREF(result);
8334 return NULL;
8335 }
8336
8337 /* Create a three-level trie */
8338 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8339 16*count2 + 128*count3 - 1);
8340 if (!result)
8341 return PyErr_NoMemory();
8342 PyObject_Init(result, &EncodingMapType);
8343 mresult = (struct encoding_map*)result;
8344 mresult->count2 = count2;
8345 mresult->count3 = count3;
8346 mlevel1 = mresult->level1;
8347 mlevel2 = mresult->level23;
8348 mlevel3 = mresult->level23 + 16*count2;
8349 memcpy(mlevel1, level1, 32);
8350 memset(mlevel2, 0xFF, 16*count2);
8351 memset(mlevel3, 0, 128*count3);
8352 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008353 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008354 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008355 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8356 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008357 /* unmapped character */
8358 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008359 o1 = ch>>11;
8360 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008361 i2 = 16*mlevel1[o1] + o2;
8362 if (mlevel2[i2] == 0xFF)
8363 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008364 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008365 i3 = 128*mlevel2[i2] + o3;
8366 mlevel3[i3] = i;
8367 }
8368 return result;
8369}
8370
8371static int
Victor Stinner22168992011-11-20 17:09:18 +01008372encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008373{
8374 struct encoding_map *map = (struct encoding_map*)mapping;
8375 int l1 = c>>11;
8376 int l2 = (c>>7) & 0xF;
8377 int l3 = c & 0x7F;
8378 int i;
8379
Victor Stinner22168992011-11-20 17:09:18 +01008380 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008382 if (c == 0)
8383 return 0;
8384 /* level 1*/
8385 i = map->level1[l1];
8386 if (i == 0xFF) {
8387 return -1;
8388 }
8389 /* level 2*/
8390 i = map->level23[16*i+l2];
8391 if (i == 0xFF) {
8392 return -1;
8393 }
8394 /* level 3 */
8395 i = map->level23[16*map->count2 + 128*i + l3];
8396 if (i == 0) {
8397 return -1;
8398 }
8399 return i;
8400}
8401
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402/* Lookup the character ch in the mapping. If the character
8403 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008404 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008405static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008406charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008407{
Christian Heimes217cfd12007-12-02 14:31:20 +00008408 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409 PyObject *x;
8410
8411 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008413 x = PyObject_GetItem(mapping, w);
8414 Py_DECREF(w);
8415 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8417 /* No mapping found means: mapping is undefined. */
8418 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008419 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 } else
8421 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008422 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008423 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008425 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 long value = PyLong_AS_LONG(x);
8427 if (value < 0 || value > 255) {
8428 PyErr_SetString(PyExc_TypeError,
8429 "character mapping must be in range(256)");
8430 Py_DECREF(x);
8431 return NULL;
8432 }
8433 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008434 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008435 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 /* wrong return value */
8439 PyErr_Format(PyExc_TypeError,
8440 "character mapping must return integer, bytes or None, not %.400s",
8441 x->ob_type->tp_name);
8442 Py_DECREF(x);
8443 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008444 }
8445}
8446
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008447static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008448charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008449{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008450 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8451 /* exponentially overallocate to minimize reallocations */
8452 if (requiredsize < 2*outsize)
8453 requiredsize = 2*outsize;
8454 if (_PyBytes_Resize(outobj, requiredsize))
8455 return -1;
8456 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008457}
8458
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008461} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008463 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008464 space is available. Return a new reference to the object that
8465 was put in the output buffer, or Py_None, if the mapping was undefined
8466 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008467 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008468static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008469charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008470 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008472 PyObject *rep;
8473 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008474 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475
Christian Heimes90aa7642007-12-19 02:45:37 +00008476 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008477 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008479 if (res == -1)
8480 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 if (outsize<requiredsize)
8482 if (charmapencode_resize(outobj, outpos, requiredsize))
8483 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008484 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 outstart[(*outpos)++] = (char)res;
8486 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008487 }
8488
8489 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008490 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008492 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 Py_DECREF(rep);
8494 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008495 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 if (PyLong_Check(rep)) {
8497 Py_ssize_t requiredsize = *outpos+1;
8498 if (outsize<requiredsize)
8499 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8500 Py_DECREF(rep);
8501 return enc_EXCEPTION;
8502 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008503 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 else {
8507 const char *repchars = PyBytes_AS_STRING(rep);
8508 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8509 Py_ssize_t requiredsize = *outpos+repsize;
8510 if (outsize<requiredsize)
8511 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8512 Py_DECREF(rep);
8513 return enc_EXCEPTION;
8514 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008515 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 memcpy(outstart + *outpos, repchars, repsize);
8517 *outpos += repsize;
8518 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008520 Py_DECREF(rep);
8521 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522}
8523
8524/* handle an error in PyUnicode_EncodeCharmap
8525 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008526static int
8527charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008530 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008531 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532{
8533 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008534 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008535 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008536 enum PyUnicode_Kind kind;
8537 void *data;
8538 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008540 Py_ssize_t collstartpos = *inpos;
8541 Py_ssize_t collendpos = *inpos+1;
8542 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008543 const char *encoding = "charmap";
8544 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008545 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008546 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008547 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548
Benjamin Petersonbac79492012-01-14 13:34:47 -05008549 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008550 return -1;
8551 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 /* find all unencodable characters */
8553 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008554 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008555 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008556 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008557 val = encoding_map_lookup(ch, mapping);
8558 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008559 break;
8560 ++collendpos;
8561 continue;
8562 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008563
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008564 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8565 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 if (rep==NULL)
8567 return -1;
8568 else if (rep!=Py_None) {
8569 Py_DECREF(rep);
8570 break;
8571 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008572 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 }
8575 /* cache callback name lookup
8576 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008577 if (*error_handler == _Py_ERROR_UNKNOWN)
8578 *error_handler = get_error_handler(errors);
8579
8580 switch (*error_handler) {
8581 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008582 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008583 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008584
8585 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008586 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 x = charmapencode_output('?', mapping, res, respos);
8588 if (x==enc_EXCEPTION) {
8589 return -1;
8590 }
8591 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008592 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 return -1;
8594 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008595 }
8596 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008597 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008598 *inpos = collendpos;
8599 break;
Victor Stinner50149202015-09-22 00:26:54 +02008600
8601 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008602 /* generate replacement (temporarily (mis)uses p) */
8603 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 char buffer[2+29+1+1];
8605 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008606 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008607 for (cp = buffer; *cp; ++cp) {
8608 x = charmapencode_output(*cp, mapping, res, respos);
8609 if (x==enc_EXCEPTION)
8610 return -1;
8611 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008612 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 return -1;
8614 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008615 }
8616 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008617 *inpos = collendpos;
8618 break;
Victor Stinner50149202015-09-22 00:26:54 +02008619
Benjamin Peterson14339b62009-01-31 16:36:08 +00008620 default:
Victor Stinner50149202015-09-22 00:26:54 +02008621 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008622 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008624 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008626 if (PyBytes_Check(repunicode)) {
8627 /* Directly copy bytes result to output. */
8628 Py_ssize_t outsize = PyBytes_Size(*res);
8629 Py_ssize_t requiredsize;
8630 repsize = PyBytes_Size(repunicode);
8631 requiredsize = *respos + repsize;
8632 if (requiredsize > outsize)
8633 /* Make room for all additional bytes. */
8634 if (charmapencode_resize(res, respos, requiredsize)) {
8635 Py_DECREF(repunicode);
8636 return -1;
8637 }
8638 memcpy(PyBytes_AsString(*res) + *respos,
8639 PyBytes_AsString(repunicode), repsize);
8640 *respos += repsize;
8641 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008642 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008643 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008644 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008645 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008646 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008647 Py_DECREF(repunicode);
8648 return -1;
8649 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008650 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008651 data = PyUnicode_DATA(repunicode);
8652 kind = PyUnicode_KIND(repunicode);
8653 for (index = 0; index < repsize; index++) {
8654 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8655 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008657 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 return -1;
8659 }
8660 else if (x==enc_FAILED) {
8661 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008662 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 return -1;
8664 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008665 }
8666 *inpos = newpos;
8667 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008668 }
8669 return 0;
8670}
8671
Alexander Belopolsky40018472011-02-26 01:02:56 +00008672PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008673_PyUnicode_EncodeCharmap(PyObject *unicode,
8674 PyObject *mapping,
8675 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008676{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 /* output object */
8678 PyObject *res = NULL;
8679 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008680 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008681 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008682 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008683 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008684 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008686 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008687 void *data;
8688 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689
Benjamin Petersonbac79492012-01-14 13:34:47 -05008690 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008691 return NULL;
8692 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008693 data = PyUnicode_DATA(unicode);
8694 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008695
Guido van Rossumd57fd912000-03-10 22:53:23 +00008696 /* Default to Latin-1 */
8697 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008698 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008699
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008700 /* allocate enough for a simple encoding without
8701 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008702 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008703 if (res == NULL)
8704 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008705 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008708 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008709 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008711 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 if (x==enc_EXCEPTION) /* error */
8713 goto onError;
8714 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008715 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008717 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 &res, &respos)) {
8719 goto onError;
8720 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008721 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 else
8723 /* done with this character => adjust input position */
8724 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008725 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008726
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008727 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008728 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008729 if (_PyBytes_Resize(&res, respos) < 0)
8730 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008731
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008732 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008733 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008734 return res;
8735
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008737 Py_XDECREF(res);
8738 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008739 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008740 return NULL;
8741}
8742
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008743/* Deprecated */
8744PyObject *
8745PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8746 Py_ssize_t size,
8747 PyObject *mapping,
8748 const char *errors)
8749{
8750 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008751 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008752 if (unicode == NULL)
8753 return NULL;
8754 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8755 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008756 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008757}
8758
Alexander Belopolsky40018472011-02-26 01:02:56 +00008759PyObject *
8760PyUnicode_AsCharmapString(PyObject *unicode,
8761 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008762{
8763 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 PyErr_BadArgument();
8765 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008766 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008767 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008768}
8769
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008771static void
8772make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008774 Py_ssize_t startpos, Py_ssize_t endpos,
8775 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008776{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008777 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 *exceptionObject = _PyUnicodeTranslateError_Create(
8779 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008780 }
8781 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8783 goto onError;
8784 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8785 goto onError;
8786 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8787 goto onError;
8788 return;
8789 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008790 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008791 }
8792}
8793
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008794/* error handling callback helper:
8795 build arguments, call the callback and check the arguments,
8796 put the result into newpos and return the replacement string, which
8797 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008798static PyObject *
8799unicode_translate_call_errorhandler(const char *errors,
8800 PyObject **errorHandler,
8801 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008803 Py_ssize_t startpos, Py_ssize_t endpos,
8804 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008805{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008806 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008807
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008808 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008809 PyObject *restuple;
8810 PyObject *resunicode;
8811
8812 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008813 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008814 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008815 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008816 }
8817
8818 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008820 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008822
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008823 restuple = PyObject_CallFunctionObjArgs(
8824 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008825 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008827 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008828 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 Py_DECREF(restuple);
8830 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008831 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008832 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 &resunicode, &i_newpos)) {
8834 Py_DECREF(restuple);
8835 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008836 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008837 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008839 else
8840 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008842 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 Py_DECREF(restuple);
8844 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008845 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008846 Py_INCREF(resunicode);
8847 Py_DECREF(restuple);
8848 return resunicode;
8849}
8850
8851/* Lookup the character ch in the mapping and put the result in result,
8852 which must be decrefed by the caller.
8853 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008854static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008856{
Christian Heimes217cfd12007-12-02 14:31:20 +00008857 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008858 PyObject *x;
8859
8860 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008861 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008862 x = PyObject_GetItem(mapping, w);
8863 Py_DECREF(w);
8864 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008865 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8866 /* No mapping found means: use 1:1 mapping. */
8867 PyErr_Clear();
8868 *result = NULL;
8869 return 0;
8870 } else
8871 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008872 }
8873 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008874 *result = x;
8875 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008876 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008877 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008878 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008879 if (value < 0 || value > MAX_UNICODE) {
8880 PyErr_Format(PyExc_ValueError,
8881 "character mapping must be in range(0x%x)",
8882 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008883 Py_DECREF(x);
8884 return -1;
8885 }
8886 *result = x;
8887 return 0;
8888 }
8889 else if (PyUnicode_Check(x)) {
8890 *result = x;
8891 return 0;
8892 }
8893 else {
8894 /* wrong return value */
8895 PyErr_SetString(PyExc_TypeError,
8896 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008897 Py_DECREF(x);
8898 return -1;
8899 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008900}
Victor Stinner1194ea02014-04-04 19:37:40 +02008901
8902/* lookup the character, write the result into the writer.
8903 Return 1 if the result was written into the writer, return 0 if the mapping
8904 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008905static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008906charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8907 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008908{
Victor Stinner1194ea02014-04-04 19:37:40 +02008909 PyObject *item;
8910
8911 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008912 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008913
8914 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008916 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008919 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008920 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008921
8922 if (item == Py_None) {
8923 Py_DECREF(item);
8924 return 0;
8925 }
8926
8927 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008928 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8929 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8930 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008931 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8932 Py_DECREF(item);
8933 return -1;
8934 }
8935 Py_DECREF(item);
8936 return 1;
8937 }
8938
8939 if (!PyUnicode_Check(item)) {
8940 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008942 }
8943
8944 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8945 Py_DECREF(item);
8946 return -1;
8947 }
8948
8949 Py_DECREF(item);
8950 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008951}
8952
Victor Stinner89a76ab2014-04-05 11:44:04 +02008953static int
8954unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8955 Py_UCS1 *translate)
8956{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008957 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008958 int ret = 0;
8959
Victor Stinner89a76ab2014-04-05 11:44:04 +02008960 if (charmaptranslate_lookup(ch, mapping, &item)) {
8961 return -1;
8962 }
8963
8964 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008965 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008966 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008967 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008968 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008969 /* not found => default to 1:1 mapping */
8970 translate[ch] = ch;
8971 return 1;
8972 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008973 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008974 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008975 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8976 used it */
8977 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008978 /* invalid character or character outside ASCII:
8979 skip the fast translate */
8980 goto exit;
8981 }
8982 translate[ch] = (Py_UCS1)replace;
8983 }
8984 else if (PyUnicode_Check(item)) {
8985 Py_UCS4 replace;
8986
8987 if (PyUnicode_READY(item) == -1) {
8988 Py_DECREF(item);
8989 return -1;
8990 }
8991 if (PyUnicode_GET_LENGTH(item) != 1)
8992 goto exit;
8993
8994 replace = PyUnicode_READ_CHAR(item, 0);
8995 if (replace > 127)
8996 goto exit;
8997 translate[ch] = (Py_UCS1)replace;
8998 }
8999 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04009000 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02009001 goto exit;
9002 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009003 ret = 1;
9004
Benjamin Peterson1365de72014-04-07 20:15:41 -04009005 exit:
9006 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009007 return ret;
9008}
9009
9010/* Fast path for ascii => ascii translation. Return 1 if the whole string
9011 was translated into writer, return 0 if the input string was partially
9012 translated into writer, raise an exception and return -1 on error. */
9013static int
9014unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009015 _PyUnicodeWriter *writer, int ignore,
9016 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009017{
Victor Stinner872b2912014-04-05 14:27:07 +02009018 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009019 Py_ssize_t len;
9020 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02009021 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009022
Victor Stinner89a76ab2014-04-05 11:44:04 +02009023 len = PyUnicode_GET_LENGTH(input);
9024
Victor Stinner872b2912014-04-05 14:27:07 +02009025 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009026
9027 in = PyUnicode_1BYTE_DATA(input);
9028 end = in + len;
9029
9030 assert(PyUnicode_IS_ASCII(writer->buffer));
9031 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9032 out = PyUnicode_1BYTE_DATA(writer->buffer);
9033
Victor Stinner872b2912014-04-05 14:27:07 +02009034 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02009035 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02009036 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02009037 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02009038 int translate = unicode_fast_translate_lookup(mapping, ch,
9039 ascii_table);
9040 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009041 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02009042 if (translate == 0)
9043 goto exit;
9044 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02009045 }
Victor Stinner872b2912014-04-05 14:27:07 +02009046 if (ch2 == 0xfe) {
9047 if (ignore)
9048 continue;
9049 goto exit;
9050 }
9051 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009052 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02009053 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009054 }
Victor Stinner872b2912014-04-05 14:27:07 +02009055 res = 1;
9056
9057exit:
9058 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009059 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02009060 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009061}
9062
Victor Stinner3222da22015-10-01 22:07:32 +02009063static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064_PyUnicode_TranslateCharmap(PyObject *input,
9065 PyObject *mapping,
9066 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02009069 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070 Py_ssize_t size, i;
9071 int kind;
9072 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02009073 _PyUnicodeWriter writer;
9074 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02009075 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009076 PyObject *errorHandler = NULL;
9077 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009078 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009079 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009080
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009082 PyErr_BadArgument();
9083 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009084 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 if (PyUnicode_READY(input) == -1)
9087 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009088 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 kind = PyUnicode_KIND(input);
9090 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009092 if (size == 0)
9093 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009094
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009095 /* allocate enough for a simple 1:1 translation without
9096 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009097 _PyUnicodeWriter_Init(&writer);
9098 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009099 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009100
Victor Stinner872b2912014-04-05 14:27:07 +02009101 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9102
Victor Stinner33798672016-03-01 21:59:58 +01009103 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009104 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009105 if (PyUnicode_IS_ASCII(input)) {
9106 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9107 if (res < 0) {
9108 _PyUnicodeWriter_Dealloc(&writer);
9109 return NULL;
9110 }
9111 if (res == 1)
9112 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009113 }
Victor Stinner33798672016-03-01 21:59:58 +01009114 else {
9115 i = 0;
9116 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009119 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009120 int translate;
9121 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9122 Py_ssize_t newpos;
9123 /* startpos for collecting untranslatable chars */
9124 Py_ssize_t collstart;
9125 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009126 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127
Victor Stinner1194ea02014-04-04 19:37:40 +02009128 ch = PyUnicode_READ(kind, data, i);
9129 translate = charmaptranslate_output(ch, mapping, &writer);
9130 if (translate < 0)
9131 goto onError;
9132
9133 if (translate != 0) {
9134 /* it worked => adjust input pointer */
9135 ++i;
9136 continue;
9137 }
9138
9139 /* untranslatable character */
9140 collstart = i;
9141 collend = i+1;
9142
9143 /* find all untranslatable characters */
9144 while (collend < size) {
9145 PyObject *x;
9146 ch = PyUnicode_READ(kind, data, collend);
9147 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009148 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009149 Py_XDECREF(x);
9150 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009151 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009152 ++collend;
9153 }
9154
9155 if (ignore) {
9156 i = collend;
9157 }
9158 else {
9159 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9160 reason, input, &exc,
9161 collstart, collend, &newpos);
9162 if (repunicode == NULL)
9163 goto onError;
9164 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009166 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009167 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009168 Py_DECREF(repunicode);
9169 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009170 }
9171 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009172 Py_XDECREF(exc);
9173 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009174 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009175
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009177 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009178 Py_XDECREF(exc);
9179 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009180 return NULL;
9181}
9182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009183/* Deprecated. Use PyUnicode_Translate instead. */
9184PyObject *
9185PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9186 Py_ssize_t size,
9187 PyObject *mapping,
9188 const char *errors)
9189{
Christian Heimes5f520f42012-09-11 14:03:25 +02009190 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009191 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 if (!unicode)
9193 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009194 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9195 Py_DECREF(unicode);
9196 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197}
9198
Alexander Belopolsky40018472011-02-26 01:02:56 +00009199PyObject *
9200PyUnicode_Translate(PyObject *str,
9201 PyObject *mapping,
9202 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009204 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009205 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009206 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207}
Tim Petersced69f82003-09-16 20:30:58 +00009208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209PyObject *
9210_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9211{
9212 if (!PyUnicode_Check(unicode)) {
9213 PyErr_BadInternalCall();
9214 return NULL;
9215 }
9216 if (PyUnicode_READY(unicode) == -1)
9217 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009218 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 /* If the string is already ASCII, just return the same string */
9220 Py_INCREF(unicode);
9221 return unicode;
9222 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009223
9224 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9225 PyObject *result = PyUnicode_New(len, 127);
9226 if (result == NULL) {
9227 return NULL;
9228 }
9229
9230 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9231 int kind = PyUnicode_KIND(unicode);
9232 const void *data = PyUnicode_DATA(unicode);
9233 Py_ssize_t i;
9234 for (i = 0; i < len; ++i) {
9235 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9236 if (ch < 127) {
9237 out[i] = ch;
9238 }
9239 else if (Py_UNICODE_ISSPACE(ch)) {
9240 out[i] = ' ';
9241 }
9242 else {
9243 int decimal = Py_UNICODE_TODECIMAL(ch);
9244 if (decimal < 0) {
9245 out[i] = '?';
9246 _PyUnicode_LENGTH(result) = i + 1;
9247 break;
9248 }
9249 out[i] = '0' + decimal;
9250 }
9251 }
9252
9253 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254}
9255
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009256PyObject *
9257PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9258 Py_ssize_t length)
9259{
Victor Stinnerf0124502011-11-21 23:12:56 +01009260 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009261 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009262 Py_UCS4 maxchar;
9263 enum PyUnicode_Kind kind;
9264 void *data;
9265
Victor Stinner99d7ad02012-02-22 13:37:39 +01009266 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009267 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009268 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009269 if (ch > 127) {
9270 int decimal = Py_UNICODE_TODECIMAL(ch);
9271 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009272 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009273 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009274 }
9275 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009276
9277 /* Copy to a new string */
9278 decimal = PyUnicode_New(length, maxchar);
9279 if (decimal == NULL)
9280 return decimal;
9281 kind = PyUnicode_KIND(decimal);
9282 data = PyUnicode_DATA(decimal);
9283 /* Iterate over code points */
9284 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009285 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009286 if (ch > 127) {
9287 int decimal = Py_UNICODE_TODECIMAL(ch);
9288 if (decimal >= 0)
9289 ch = '0' + decimal;
9290 }
9291 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009293 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009294}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009295/* --- Decimal Encoder ---------------------------------------------------- */
9296
Alexander Belopolsky40018472011-02-26 01:02:56 +00009297int
9298PyUnicode_EncodeDecimal(Py_UNICODE *s,
9299 Py_ssize_t length,
9300 char *output,
9301 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009302{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009303 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009304 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009305 enum PyUnicode_Kind kind;
9306 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009307
9308 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009309 PyErr_BadArgument();
9310 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009311 }
9312
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009313 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009314 if (unicode == NULL)
9315 return -1;
9316
Victor Stinner42bf7752011-11-21 22:52:58 +01009317 kind = PyUnicode_KIND(unicode);
9318 data = PyUnicode_DATA(unicode);
9319
Victor Stinnerb84d7232011-11-22 01:50:07 +01009320 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009321 PyObject *exc;
9322 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009323 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009324 Py_ssize_t startpos;
9325
9326 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009327
Benjamin Peterson29060642009-01-31 22:14:21 +00009328 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009329 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009330 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009331 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009332 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009333 decimal = Py_UNICODE_TODECIMAL(ch);
9334 if (decimal >= 0) {
9335 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009336 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009337 continue;
9338 }
9339 if (0 < ch && ch < 256) {
9340 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009341 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009342 continue;
9343 }
Victor Stinner6345be92011-11-25 20:09:01 +01009344
Victor Stinner42bf7752011-11-21 22:52:58 +01009345 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009346 exc = NULL;
9347 raise_encode_exception(&exc, "decimal", unicode,
9348 startpos, startpos+1,
9349 "invalid decimal Unicode string");
9350 Py_XDECREF(exc);
9351 Py_DECREF(unicode);
9352 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009353 }
9354 /* 0-terminate the output string */
9355 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009356 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009357 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009358}
9359
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360/* --- Helpers ------------------------------------------------------------ */
9361
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009362/* helper macro to fixup start/end slice values */
9363#define ADJUST_INDICES(start, end, len) \
9364 if (end > len) \
9365 end = len; \
9366 else if (end < 0) { \
9367 end += len; \
9368 if (end < 0) \
9369 end = 0; \
9370 } \
9371 if (start < 0) { \
9372 start += len; \
9373 if (start < 0) \
9374 start = 0; \
9375 }
9376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009378any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009380 Py_ssize_t end,
9381 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009383 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009384 void *buf1, *buf2;
9385 Py_ssize_t len1, len2, result;
9386
9387 kind1 = PyUnicode_KIND(s1);
9388 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009389 if (kind1 < kind2)
9390 return -1;
9391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 len1 = PyUnicode_GET_LENGTH(s1);
9393 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009394 ADJUST_INDICES(start, end, len1);
9395 if (end - start < len2)
9396 return -1;
9397
9398 buf1 = PyUnicode_DATA(s1);
9399 buf2 = PyUnicode_DATA(s2);
9400 if (len2 == 1) {
9401 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9402 result = findchar((const char *)buf1 + kind1*start,
9403 kind1, end - start, ch, direction);
9404 if (result == -1)
9405 return -1;
9406 else
9407 return start + result;
9408 }
9409
9410 if (kind2 != kind1) {
9411 buf2 = _PyUnicode_AsKind(s2, kind1);
9412 if (!buf2)
9413 return -2;
9414 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415
Victor Stinner794d5672011-10-10 03:21:36 +02009416 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009417 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009418 case PyUnicode_1BYTE_KIND:
9419 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9420 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9421 else
9422 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9423 break;
9424 case PyUnicode_2BYTE_KIND:
9425 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9426 break;
9427 case PyUnicode_4BYTE_KIND:
9428 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9429 break;
9430 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009431 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009432 }
9433 }
9434 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009435 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009436 case PyUnicode_1BYTE_KIND:
9437 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9438 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9439 else
9440 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9441 break;
9442 case PyUnicode_2BYTE_KIND:
9443 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9444 break;
9445 case PyUnicode_4BYTE_KIND:
9446 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9447 break;
9448 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009449 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009450 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009451 }
9452
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009453 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009454 PyMem_Free(buf2);
9455
9456 return result;
9457}
9458
9459Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009460_PyUnicode_InsertThousandsGrouping(
9461 PyObject *unicode, Py_ssize_t index,
9462 Py_ssize_t n_buffer,
9463 void *digits, Py_ssize_t n_digits,
9464 Py_ssize_t min_width,
9465 const char *grouping, PyObject *thousands_sep,
9466 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467{
Victor Stinner41a863c2012-02-24 00:37:51 +01009468 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009469 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009470 Py_ssize_t thousands_sep_len;
9471 Py_ssize_t len;
9472
9473 if (unicode != NULL) {
9474 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009475 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009476 }
9477 else {
9478 kind = PyUnicode_1BYTE_KIND;
9479 data = NULL;
9480 }
9481 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9482 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9483 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9484 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009485 if (thousands_sep_kind < kind) {
9486 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9487 if (!thousands_sep_data)
9488 return -1;
9489 }
9490 else {
9491 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9492 if (!data)
9493 return -1;
9494 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009495 }
9496
Benjamin Petersonead6b532011-12-20 17:23:42 -06009497 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009499 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009500 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009501 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009502 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009503 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009504 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009505 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009506 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009507 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009508 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009509 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009511 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009512 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009513 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009514 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009517 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009518 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009519 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009520 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009521 break;
9522 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009523 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009525 if (unicode != NULL && thousands_sep_kind != kind) {
9526 if (thousands_sep_kind < kind)
9527 PyMem_Free(thousands_sep_data);
9528 else
9529 PyMem_Free(data);
9530 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009531 if (unicode == NULL) {
9532 *maxchar = 127;
9533 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009534 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009535 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009536 }
9537 }
9538 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009539}
9540
9541
Alexander Belopolsky40018472011-02-26 01:02:56 +00009542Py_ssize_t
9543PyUnicode_Count(PyObject *str,
9544 PyObject *substr,
9545 Py_ssize_t start,
9546 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009548 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009549 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 void *buf1 = NULL, *buf2 = NULL;
9551 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009552
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009553 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009554 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009555
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009556 kind1 = PyUnicode_KIND(str);
9557 kind2 = PyUnicode_KIND(substr);
9558 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009559 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009560
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009561 len1 = PyUnicode_GET_LENGTH(str);
9562 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009563 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009564 if (end - start < len2)
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 buf1 = PyUnicode_DATA(str);
9568 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009569 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009570 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009571 if (!buf2)
9572 goto onError;
9573 }
9574
9575 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009576 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009577 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009578 result = asciilib_count(
9579 ((Py_UCS1*)buf1) + start, end - start,
9580 buf2, len2, PY_SSIZE_T_MAX
9581 );
9582 else
9583 result = ucs1lib_count(
9584 ((Py_UCS1*)buf1) + start, end - start,
9585 buf2, len2, PY_SSIZE_T_MAX
9586 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 break;
9588 case PyUnicode_2BYTE_KIND:
9589 result = ucs2lib_count(
9590 ((Py_UCS2*)buf1) + start, end - start,
9591 buf2, len2, PY_SSIZE_T_MAX
9592 );
9593 break;
9594 case PyUnicode_4BYTE_KIND:
9595 result = ucs4lib_count(
9596 ((Py_UCS4*)buf1) + start, end - start,
9597 buf2, len2, PY_SSIZE_T_MAX
9598 );
9599 break;
9600 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009601 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009602 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009603
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009604 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605 PyMem_Free(buf2);
9606
Guido van Rossumd57fd912000-03-10 22:53:23 +00009607 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009609 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610 PyMem_Free(buf2);
9611 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612}
9613
Alexander Belopolsky40018472011-02-26 01:02:56 +00009614Py_ssize_t
9615PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009616 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009617 Py_ssize_t start,
9618 Py_ssize_t end,
9619 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009621 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009622 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009623
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009624 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625}
9626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627Py_ssize_t
9628PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9629 Py_ssize_t start, Py_ssize_t end,
9630 int direction)
9631{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009632 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009633 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 if (PyUnicode_READY(str) == -1)
9635 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009636 len = PyUnicode_GET_LENGTH(str);
9637 ADJUST_INDICES(start, end, len);
9638 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009639 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009641 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9642 kind, end-start, ch, direction);
9643 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009645 else
9646 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647}
9648
Alexander Belopolsky40018472011-02-26 01:02:56 +00009649static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009650tailmatch(PyObject *self,
9651 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009652 Py_ssize_t start,
9653 Py_ssize_t end,
9654 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009655{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656 int kind_self;
9657 int kind_sub;
9658 void *data_self;
9659 void *data_sub;
9660 Py_ssize_t offset;
9661 Py_ssize_t i;
9662 Py_ssize_t end_sub;
9663
9664 if (PyUnicode_READY(self) == -1 ||
9665 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009666 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9669 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009671 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009673 if (PyUnicode_GET_LENGTH(substring) == 0)
9674 return 1;
9675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009676 kind_self = PyUnicode_KIND(self);
9677 data_self = PyUnicode_DATA(self);
9678 kind_sub = PyUnicode_KIND(substring);
9679 data_sub = PyUnicode_DATA(substring);
9680 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9681
9682 if (direction > 0)
9683 offset = end;
9684 else
9685 offset = start;
9686
9687 if (PyUnicode_READ(kind_self, data_self, offset) ==
9688 PyUnicode_READ(kind_sub, data_sub, 0) &&
9689 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9690 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9691 /* If both are of the same kind, memcmp is sufficient */
9692 if (kind_self == kind_sub) {
9693 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009694 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009695 data_sub,
9696 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009697 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009699 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009700 else {
9701 /* We do not need to compare 0 and len(substring)-1 because
9702 the if statement above ensured already that they are equal
9703 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009704 for (i = 1; i < end_sub; ++i) {
9705 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9706 PyUnicode_READ(kind_sub, data_sub, i))
9707 return 0;
9708 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009709 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009710 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711 }
9712
9713 return 0;
9714}
9715
Alexander Belopolsky40018472011-02-26 01:02:56 +00009716Py_ssize_t
9717PyUnicode_Tailmatch(PyObject *str,
9718 PyObject *substr,
9719 Py_ssize_t start,
9720 Py_ssize_t end,
9721 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009722{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009723 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009724 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009725
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009726 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009727}
9728
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009729static PyObject *
9730ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009731{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009732 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9733 char *resdata, *data = PyUnicode_DATA(self);
9734 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009735
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009736 res = PyUnicode_New(len, 127);
9737 if (res == NULL)
9738 return NULL;
9739 resdata = PyUnicode_DATA(res);
9740 if (lower)
9741 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009742 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009743 _Py_bytes_upper(resdata, data, len);
9744 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745}
9746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009747static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009748handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009749{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009750 Py_ssize_t j;
9751 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009752 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009753 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009754
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009755 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9756
9757 where ! is a negation and \p{xxx} is a character with property xxx.
9758 */
9759 for (j = i - 1; j >= 0; j--) {
9760 c = PyUnicode_READ(kind, data, j);
9761 if (!_PyUnicode_IsCaseIgnorable(c))
9762 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009763 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009764 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9765 if (final_sigma) {
9766 for (j = i + 1; j < length; j++) {
9767 c = PyUnicode_READ(kind, data, j);
9768 if (!_PyUnicode_IsCaseIgnorable(c))
9769 break;
9770 }
9771 final_sigma = j == length || !_PyUnicode_IsCased(c);
9772 }
9773 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774}
9775
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009776static int
9777lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9778 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009779{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009780 /* Obscure special case. */
9781 if (c == 0x3A3) {
9782 mapped[0] = handle_capital_sigma(kind, data, length, i);
9783 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009784 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009785 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009786}
9787
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009788static Py_ssize_t
9789do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009790{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009791 Py_ssize_t i, k = 0;
9792 int n_res, j;
9793 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009794
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009795 c = PyUnicode_READ(kind, data, 0);
9796 n_res = _PyUnicode_ToUpperFull(c, mapped);
9797 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009798 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009799 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009801 for (i = 1; i < length; i++) {
9802 c = PyUnicode_READ(kind, data, i);
9803 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9804 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009805 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009806 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009807 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009808 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009809 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009810}
9811
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009812static Py_ssize_t
9813do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9814 Py_ssize_t i, k = 0;
9815
9816 for (i = 0; i < length; i++) {
9817 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9818 int n_res, j;
9819 if (Py_UNICODE_ISUPPER(c)) {
9820 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9821 }
9822 else if (Py_UNICODE_ISLOWER(c)) {
9823 n_res = _PyUnicode_ToUpperFull(c, mapped);
9824 }
9825 else {
9826 n_res = 1;
9827 mapped[0] = c;
9828 }
9829 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009830 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009831 res[k++] = mapped[j];
9832 }
9833 }
9834 return k;
9835}
9836
9837static Py_ssize_t
9838do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9839 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009841 Py_ssize_t i, k = 0;
9842
9843 for (i = 0; i < length; i++) {
9844 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9845 int n_res, j;
9846 if (lower)
9847 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9848 else
9849 n_res = _PyUnicode_ToUpperFull(c, mapped);
9850 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009851 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009852 res[k++] = mapped[j];
9853 }
9854 }
9855 return k;
9856}
9857
9858static Py_ssize_t
9859do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9860{
9861 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9862}
9863
9864static Py_ssize_t
9865do_lower(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, 1);
9868}
9869
Benjamin Petersone51757f2012-01-12 21:10:29 -05009870static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009871do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9872{
9873 Py_ssize_t i, k = 0;
9874
9875 for (i = 0; i < length; i++) {
9876 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9877 Py_UCS4 mapped[3];
9878 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9879 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009880 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009881 res[k++] = mapped[j];
9882 }
9883 }
9884 return k;
9885}
9886
9887static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009888do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9889{
9890 Py_ssize_t i, k = 0;
9891 int previous_is_cased;
9892
9893 previous_is_cased = 0;
9894 for (i = 0; i < length; i++) {
9895 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9896 Py_UCS4 mapped[3];
9897 int n_res, j;
9898
9899 if (previous_is_cased)
9900 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9901 else
9902 n_res = _PyUnicode_ToTitleFull(c, mapped);
9903
9904 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009905 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009906 res[k++] = mapped[j];
9907 }
9908
9909 previous_is_cased = _PyUnicode_IsCased(c);
9910 }
9911 return k;
9912}
9913
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009914static PyObject *
9915case_operation(PyObject *self,
9916 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9917{
9918 PyObject *res = NULL;
9919 Py_ssize_t length, newlength = 0;
9920 int kind, outkind;
9921 void *data, *outdata;
9922 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9923
Benjamin Petersoneea48462012-01-16 14:28:50 -05009924 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009925
9926 kind = PyUnicode_KIND(self);
9927 data = PyUnicode_DATA(self);
9928 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009929 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009930 PyErr_SetString(PyExc_OverflowError, "string is too long");
9931 return NULL;
9932 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009933 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009934 if (tmp == NULL)
9935 return PyErr_NoMemory();
9936 newlength = perform(kind, data, length, tmp, &maxchar);
9937 res = PyUnicode_New(newlength, maxchar);
9938 if (res == NULL)
9939 goto leave;
9940 tmpend = tmp + newlength;
9941 outdata = PyUnicode_DATA(res);
9942 outkind = PyUnicode_KIND(res);
9943 switch (outkind) {
9944 case PyUnicode_1BYTE_KIND:
9945 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9946 break;
9947 case PyUnicode_2BYTE_KIND:
9948 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9949 break;
9950 case PyUnicode_4BYTE_KIND:
9951 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9952 break;
9953 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009954 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009955 }
9956 leave:
9957 PyMem_FREE(tmp);
9958 return res;
9959}
9960
Tim Peters8ce9f162004-08-27 01:49:32 +00009961PyObject *
9962PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009963{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009964 PyObject *res;
9965 PyObject *fseq;
9966 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009967 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009968
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009969 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009970 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009971 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009972 }
9973
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009974 /* NOTE: the following code can't call back into Python code,
9975 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009976 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009977
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009978 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009979 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009980 res = _PyUnicode_JoinArray(separator, items, seqlen);
9981 Py_DECREF(fseq);
9982 return res;
9983}
9984
9985PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009986_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009987{
9988 PyObject *res = NULL; /* the result */
9989 PyObject *sep = NULL;
9990 Py_ssize_t seplen;
9991 PyObject *item;
9992 Py_ssize_t sz, i, res_offset;
9993 Py_UCS4 maxchar;
9994 Py_UCS4 item_maxchar;
9995 int use_memcpy;
9996 unsigned char *res_data = NULL, *sep_data = NULL;
9997 PyObject *last_obj;
9998 unsigned int kind = 0;
9999
Tim Peters05eba1f2004-08-27 21:32:02 +000010000 /* If empty sequence, return u"". */
10001 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010002 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +000010003 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010004
Tim Peters05eba1f2004-08-27 21:32:02 +000010005 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010006 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +020010007 if (seqlen == 1) {
10008 if (PyUnicode_CheckExact(items[0])) {
10009 res = items[0];
10010 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +020010011 return res;
10012 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010013 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +020010014 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +000010015 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010016 else {
Victor Stinneracf47b82011-10-06 12:32:37 +020010017 /* Set up sep and seplen */
10018 if (separator == NULL) {
10019 /* fall back to a blank space separator */
10020 sep = PyUnicode_FromOrdinal(' ');
10021 if (!sep)
10022 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010023 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010024 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010025 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010026 else {
10027 if (!PyUnicode_Check(separator)) {
10028 PyErr_Format(PyExc_TypeError,
10029 "separator: expected str instance,"
10030 " %.80s found",
10031 Py_TYPE(separator)->tp_name);
10032 goto onError;
10033 }
10034 if (PyUnicode_READY(separator))
10035 goto onError;
10036 sep = separator;
10037 seplen = PyUnicode_GET_LENGTH(separator);
10038 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10039 /* inc refcount to keep this code path symmetric with the
10040 above case of a blank separator */
10041 Py_INCREF(sep);
10042 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010043 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010044 }
10045
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010046 /* There are at least two things to join, or else we have a subclass
10047 * of str in the sequence.
10048 * Do a pre-pass to figure out the total amount of space we'll
10049 * need (sz), and see whether all argument are strings.
10050 */
10051 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010052#ifdef Py_DEBUG
10053 use_memcpy = 0;
10054#else
10055 use_memcpy = 1;
10056#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010057 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010058 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010059 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010060 if (!PyUnicode_Check(item)) {
10061 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010062 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010063 " %.80s found",
10064 i, Py_TYPE(item)->tp_name);
10065 goto onError;
10066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 if (PyUnicode_READY(item) == -1)
10068 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010069 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010071 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010072 if (i != 0) {
10073 add_sz += seplen;
10074 }
10075 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010076 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010077 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010078 goto onError;
10079 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010080 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010081 if (use_memcpy && last_obj != NULL) {
10082 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10083 use_memcpy = 0;
10084 }
10085 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010086 }
Tim Petersced69f82003-09-16 20:30:58 +000010087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010089 if (res == NULL)
10090 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010091
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010092 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010093#ifdef Py_DEBUG
10094 use_memcpy = 0;
10095#else
10096 if (use_memcpy) {
10097 res_data = PyUnicode_1BYTE_DATA(res);
10098 kind = PyUnicode_KIND(res);
10099 if (seplen != 0)
10100 sep_data = PyUnicode_1BYTE_DATA(sep);
10101 }
10102#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010103 if (use_memcpy) {
10104 for (i = 0; i < seqlen; ++i) {
10105 Py_ssize_t itemlen;
10106 item = items[i];
10107
10108 /* Copy item, and maybe the separator. */
10109 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010110 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010111 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010112 kind * seplen);
10113 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010114 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010115
10116 itemlen = PyUnicode_GET_LENGTH(item);
10117 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010118 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010119 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010120 kind * itemlen);
10121 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010122 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010123 }
10124 assert(res_data == PyUnicode_1BYTE_DATA(res)
10125 + kind * PyUnicode_GET_LENGTH(res));
10126 }
10127 else {
10128 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10129 Py_ssize_t itemlen;
10130 item = items[i];
10131
10132 /* Copy item, and maybe the separator. */
10133 if (i && seplen != 0) {
10134 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10135 res_offset += seplen;
10136 }
10137
10138 itemlen = PyUnicode_GET_LENGTH(item);
10139 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010140 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010141 res_offset += itemlen;
10142 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010143 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010144 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010145 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010148 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010150
Benjamin Peterson29060642009-01-31 22:14:21 +000010151 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010153 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010154 return NULL;
10155}
10156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157#define FILL(kind, data, value, start, length) \
10158 do { \
10159 Py_ssize_t i_ = 0; \
10160 assert(kind != PyUnicode_WCHAR_KIND); \
10161 switch ((kind)) { \
10162 case PyUnicode_1BYTE_KIND: { \
10163 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010164 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 break; \
10166 } \
10167 case PyUnicode_2BYTE_KIND: { \
10168 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10169 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10170 break; \
10171 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010172 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10174 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10175 break; \
10176 } \
Barry Warsawb2e57942017-09-14 18:13:16 -070010177 default: Py_UNREACHABLE(); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 } \
10179 } while (0)
10180
Victor Stinnerd3f08822012-05-29 12:57:52 +020010181void
10182_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10183 Py_UCS4 fill_char)
10184{
10185 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10186 const void *data = PyUnicode_DATA(unicode);
10187 assert(PyUnicode_IS_READY(unicode));
10188 assert(unicode_modifiable(unicode));
10189 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10190 assert(start >= 0);
10191 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10192 FILL(kind, data, fill_char, start, length);
10193}
10194
Victor Stinner3fe55312012-01-04 00:33:50 +010010195Py_ssize_t
10196PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10197 Py_UCS4 fill_char)
10198{
10199 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010200
10201 if (!PyUnicode_Check(unicode)) {
10202 PyErr_BadInternalCall();
10203 return -1;
10204 }
10205 if (PyUnicode_READY(unicode) == -1)
10206 return -1;
10207 if (unicode_check_modifiable(unicode))
10208 return -1;
10209
Victor Stinnerd3f08822012-05-29 12:57:52 +020010210 if (start < 0) {
10211 PyErr_SetString(PyExc_IndexError, "string index out of range");
10212 return -1;
10213 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010214 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10215 PyErr_SetString(PyExc_ValueError,
10216 "fill character is bigger than "
10217 "the string maximum character");
10218 return -1;
10219 }
10220
10221 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10222 length = Py_MIN(maxlen, length);
10223 if (length <= 0)
10224 return 0;
10225
Victor Stinnerd3f08822012-05-29 12:57:52 +020010226 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010227 return length;
10228}
10229
Victor Stinner9310abb2011-10-05 00:59:23 +020010230static PyObject *
10231pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010232 Py_ssize_t left,
10233 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 PyObject *u;
10237 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010238 int kind;
10239 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010240
10241 if (left < 0)
10242 left = 0;
10243 if (right < 0)
10244 right = 0;
10245
Victor Stinnerc4b49542011-12-11 22:44:26 +010010246 if (left == 0 && right == 0)
10247 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10250 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010251 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10252 return NULL;
10253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010255 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010257 if (!u)
10258 return NULL;
10259
10260 kind = PyUnicode_KIND(u);
10261 data = PyUnicode_DATA(u);
10262 if (left)
10263 FILL(kind, data, fill, 0, left);
10264 if (right)
10265 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010266 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010267 assert(_PyUnicode_CheckConsistency(u, 1));
10268 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010269}
10270
Alexander Belopolsky40018472011-02-26 01:02:56 +000010271PyObject *
10272PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010275
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010276 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010277 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010278
Benjamin Petersonead6b532011-12-20 17:23:42 -060010279 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010281 if (PyUnicode_IS_ASCII(string))
10282 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010283 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010284 PyUnicode_GET_LENGTH(string), keepends);
10285 else
10286 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010287 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010288 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 break;
10290 case PyUnicode_2BYTE_KIND:
10291 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010292 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 PyUnicode_GET_LENGTH(string), keepends);
10294 break;
10295 case PyUnicode_4BYTE_KIND:
10296 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010297 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 PyUnicode_GET_LENGTH(string), keepends);
10299 break;
10300 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010301 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304}
10305
Alexander Belopolsky40018472011-02-26 01:02:56 +000010306static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010307split(PyObject *self,
10308 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010309 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010311 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 void *buf1, *buf2;
10313 Py_ssize_t len1, len2;
10314 PyObject* out;
10315
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010317 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 if (PyUnicode_READY(self) == -1)
10320 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010323 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010325 if (PyUnicode_IS_ASCII(self))
10326 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010327 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010328 PyUnicode_GET_LENGTH(self), maxcount
10329 );
10330 else
10331 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010332 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010333 PyUnicode_GET_LENGTH(self), maxcount
10334 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 case PyUnicode_2BYTE_KIND:
10336 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010337 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 PyUnicode_GET_LENGTH(self), maxcount
10339 );
10340 case PyUnicode_4BYTE_KIND:
10341 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010342 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 PyUnicode_GET_LENGTH(self), maxcount
10344 );
10345 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010346 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 }
10348
10349 if (PyUnicode_READY(substring) == -1)
10350 return NULL;
10351
10352 kind1 = PyUnicode_KIND(self);
10353 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 len1 = PyUnicode_GET_LENGTH(self);
10355 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010356 if (kind1 < kind2 || len1 < len2) {
10357 out = PyList_New(1);
10358 if (out == NULL)
10359 return NULL;
10360 Py_INCREF(self);
10361 PyList_SET_ITEM(out, 0, self);
10362 return out;
10363 }
10364 buf1 = PyUnicode_DATA(self);
10365 buf2 = PyUnicode_DATA(substring);
10366 if (kind2 != kind1) {
10367 buf2 = _PyUnicode_AsKind(substring, kind1);
10368 if (!buf2)
10369 return NULL;
10370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010372 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010374 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10375 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010376 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010377 else
10378 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010379 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 break;
10381 case PyUnicode_2BYTE_KIND:
10382 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010383 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 break;
10385 case PyUnicode_4BYTE_KIND:
10386 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010387 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 break;
10389 default:
10390 out = NULL;
10391 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010392 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 PyMem_Free(buf2);
10394 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395}
10396
Alexander Belopolsky40018472011-02-26 01:02:56 +000010397static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010398rsplit(PyObject *self,
10399 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010400 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010401{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010402 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 void *buf1, *buf2;
10404 Py_ssize_t len1, len2;
10405 PyObject* out;
10406
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010407 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010408 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 if (PyUnicode_READY(self) == -1)
10411 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010414 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010416 if (PyUnicode_IS_ASCII(self))
10417 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010418 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010419 PyUnicode_GET_LENGTH(self), maxcount
10420 );
10421 else
10422 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010423 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010424 PyUnicode_GET_LENGTH(self), maxcount
10425 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426 case PyUnicode_2BYTE_KIND:
10427 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010428 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 PyUnicode_GET_LENGTH(self), maxcount
10430 );
10431 case PyUnicode_4BYTE_KIND:
10432 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010433 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 PyUnicode_GET_LENGTH(self), maxcount
10435 );
10436 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010437 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 }
10439
10440 if (PyUnicode_READY(substring) == -1)
10441 return NULL;
10442
10443 kind1 = PyUnicode_KIND(self);
10444 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 len1 = PyUnicode_GET_LENGTH(self);
10446 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010447 if (kind1 < kind2 || len1 < len2) {
10448 out = PyList_New(1);
10449 if (out == NULL)
10450 return NULL;
10451 Py_INCREF(self);
10452 PyList_SET_ITEM(out, 0, self);
10453 return out;
10454 }
10455 buf1 = PyUnicode_DATA(self);
10456 buf2 = PyUnicode_DATA(substring);
10457 if (kind2 != kind1) {
10458 buf2 = _PyUnicode_AsKind(substring, kind1);
10459 if (!buf2)
10460 return NULL;
10461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010463 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010465 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10466 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010467 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010468 else
10469 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010470 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 break;
10472 case PyUnicode_2BYTE_KIND:
10473 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010474 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 break;
10476 case PyUnicode_4BYTE_KIND:
10477 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010478 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 break;
10480 default:
10481 out = NULL;
10482 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010483 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 PyMem_Free(buf2);
10485 return out;
10486}
10487
10488static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010489anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10490 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010492 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010494 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10495 return asciilib_find(buf1, len1, buf2, len2, offset);
10496 else
10497 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 case PyUnicode_2BYTE_KIND:
10499 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10500 case PyUnicode_4BYTE_KIND:
10501 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10502 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010503 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504}
10505
10506static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010507anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10508 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010510 switch (kind) {
10511 case PyUnicode_1BYTE_KIND:
10512 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10513 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10514 else
10515 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10516 case PyUnicode_2BYTE_KIND:
10517 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10518 case PyUnicode_4BYTE_KIND:
10519 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10520 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010521 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010522}
10523
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010524static void
10525replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10526 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10527{
10528 int kind = PyUnicode_KIND(u);
10529 void *data = PyUnicode_DATA(u);
10530 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10531 if (kind == PyUnicode_1BYTE_KIND) {
10532 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10533 (Py_UCS1 *)data + len,
10534 u1, u2, maxcount);
10535 }
10536 else if (kind == PyUnicode_2BYTE_KIND) {
10537 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10538 (Py_UCS2 *)data + len,
10539 u1, u2, maxcount);
10540 }
10541 else {
10542 assert(kind == PyUnicode_4BYTE_KIND);
10543 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10544 (Py_UCS4 *)data + len,
10545 u1, u2, maxcount);
10546 }
10547}
10548
Alexander Belopolsky40018472011-02-26 01:02:56 +000010549static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550replace(PyObject *self, PyObject *str1,
10551 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 PyObject *u;
10554 char *sbuf = PyUnicode_DATA(self);
10555 char *buf1 = PyUnicode_DATA(str1);
10556 char *buf2 = PyUnicode_DATA(str2);
10557 int srelease = 0, release1 = 0, release2 = 0;
10558 int skind = PyUnicode_KIND(self);
10559 int kind1 = PyUnicode_KIND(str1);
10560 int kind2 = PyUnicode_KIND(str2);
10561 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10562 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10563 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010564 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010565 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566
10567 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010568 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010570 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010571
Victor Stinner59de0ee2011-10-07 10:01:28 +020010572 if (str1 == str2)
10573 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574
Victor Stinner49a0a212011-10-12 23:46:10 +020010575 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010576 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10577 if (maxchar < maxchar_str1)
10578 /* substring too wide to be present */
10579 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010580 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10581 /* Replacing str1 with str2 may cause a maxchar reduction in the
10582 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010583 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010584 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010589 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010592 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010593 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010594
Victor Stinner69ed0f42013-04-09 21:48:24 +020010595 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010596 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010597 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010598 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010599 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010601 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010603
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010604 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10605 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010606 }
10607 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 int rkind = skind;
10609 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010610 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 if (kind1 < rkind) {
10613 /* widen substring */
10614 buf1 = _PyUnicode_AsKind(str1, rkind);
10615 if (!buf1) goto error;
10616 release1 = 1;
10617 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010618 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619 if (i < 0)
10620 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 if (rkind > kind2) {
10622 /* widen replacement */
10623 buf2 = _PyUnicode_AsKind(str2, rkind);
10624 if (!buf2) goto error;
10625 release2 = 1;
10626 }
10627 else if (rkind < kind2) {
10628 /* widen self and buf1 */
10629 rkind = kind2;
10630 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010631 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 sbuf = _PyUnicode_AsKind(self, rkind);
10633 if (!sbuf) goto error;
10634 srelease = 1;
10635 buf1 = _PyUnicode_AsKind(str1, rkind);
10636 if (!buf1) goto error;
10637 release1 = 1;
10638 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010639 u = PyUnicode_New(slen, maxchar);
10640 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010642 assert(PyUnicode_KIND(u) == rkind);
10643 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010644
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010645 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010646 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010647 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010649 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010651
10652 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010653 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010654 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010655 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010656 if (i == -1)
10657 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010658 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010660 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010662 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010663 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010664 }
10665 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010667 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 int rkind = skind;
10669 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010672 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 buf1 = _PyUnicode_AsKind(str1, rkind);
10674 if (!buf1) goto error;
10675 release1 = 1;
10676 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010677 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010678 if (n == 0)
10679 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010681 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 buf2 = _PyUnicode_AsKind(str2, rkind);
10683 if (!buf2) goto error;
10684 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010686 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010687 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 rkind = kind2;
10689 sbuf = _PyUnicode_AsKind(self, rkind);
10690 if (!sbuf) goto error;
10691 srelease = 1;
10692 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010693 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 buf1 = _PyUnicode_AsKind(str1, rkind);
10695 if (!buf1) goto error;
10696 release1 = 1;
10697 }
10698 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10699 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010700 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 PyErr_SetString(PyExc_OverflowError,
10702 "replace string is too long");
10703 goto error;
10704 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010705 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010706 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010707 _Py_INCREF_UNICODE_EMPTY();
10708 if (!unicode_empty)
10709 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010710 u = unicode_empty;
10711 goto done;
10712 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010713 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 PyErr_SetString(PyExc_OverflowError,
10715 "replace string is too long");
10716 goto error;
10717 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010718 u = PyUnicode_New(new_size, maxchar);
10719 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010721 assert(PyUnicode_KIND(u) == rkind);
10722 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 ires = i = 0;
10724 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010725 while (n-- > 0) {
10726 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010727 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010728 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010729 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010730 if (j == -1)
10731 break;
10732 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010733 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010734 memcpy(res + rkind * ires,
10735 sbuf + rkind * i,
10736 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010737 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010738 }
10739 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010740 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010741 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010743 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010746 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010747 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010749 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010750 memcpy(res + rkind * ires,
10751 sbuf + rkind * i,
10752 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010753 }
10754 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010755 /* interleave */
10756 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010757 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010759 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010761 if (--n <= 0)
10762 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010763 memcpy(res + rkind * ires,
10764 sbuf + rkind * i,
10765 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 ires++;
10767 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010768 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010769 memcpy(res + rkind * ires,
10770 sbuf + rkind * i,
10771 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010772 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010773 }
10774
10775 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010776 unicode_adjust_maxchar(&u);
10777 if (u == NULL)
10778 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010780
10781 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 if (srelease)
10783 PyMem_FREE(sbuf);
10784 if (release1)
10785 PyMem_FREE(buf1);
10786 if (release2)
10787 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010788 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010790
Benjamin Peterson29060642009-01-31 22:14:21 +000010791 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010792 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 if (srelease)
10794 PyMem_FREE(sbuf);
10795 if (release1)
10796 PyMem_FREE(buf1);
10797 if (release2)
10798 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010799 return unicode_result_unchanged(self);
10800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 error:
10802 if (srelease && sbuf)
10803 PyMem_FREE(sbuf);
10804 if (release1 && buf1)
10805 PyMem_FREE(buf1);
10806 if (release2 && buf2)
10807 PyMem_FREE(buf2);
10808 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809}
10810
10811/* --- Unicode Object Methods --------------------------------------------- */
10812
INADA Naoki3ae20562017-01-16 20:41:20 +090010813/*[clinic input]
10814str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815
INADA Naoki3ae20562017-01-16 20:41:20 +090010816Return a version of the string where each word is titlecased.
10817
10818More specifically, words start with uppercased characters and all remaining
10819cased characters have lower case.
10820[clinic start generated code]*/
10821
10822static PyObject *
10823unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010824/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010826 if (PyUnicode_READY(self) == -1)
10827 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010828 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010829}
10830
INADA Naoki3ae20562017-01-16 20:41:20 +090010831/*[clinic input]
10832str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833
INADA Naoki3ae20562017-01-16 20:41:20 +090010834Return a capitalized version of the string.
10835
10836More specifically, make the first character have upper case and the rest lower
10837case.
10838[clinic start generated code]*/
10839
10840static PyObject *
10841unicode_capitalize_impl(PyObject *self)
10842/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010844 if (PyUnicode_READY(self) == -1)
10845 return NULL;
10846 if (PyUnicode_GET_LENGTH(self) == 0)
10847 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010848 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849}
10850
INADA Naoki3ae20562017-01-16 20:41:20 +090010851/*[clinic input]
10852str.casefold as unicode_casefold
10853
10854Return a version of the string suitable for caseless comparisons.
10855[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010856
10857static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010858unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010859/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010860{
10861 if (PyUnicode_READY(self) == -1)
10862 return NULL;
10863 if (PyUnicode_IS_ASCII(self))
10864 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010865 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010866}
10867
10868
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010869/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010870
10871static int
10872convert_uc(PyObject *obj, void *addr)
10873{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010874 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010875
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010876 if (!PyUnicode_Check(obj)) {
10877 PyErr_Format(PyExc_TypeError,
10878 "The fill character must be a unicode character, "
10879 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010880 return 0;
10881 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010882 if (PyUnicode_READY(obj) < 0)
10883 return 0;
10884 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010885 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010886 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010887 return 0;
10888 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010889 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010890 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010891}
10892
INADA Naoki3ae20562017-01-16 20:41:20 +090010893/*[clinic input]
10894str.center as unicode_center
10895
10896 width: Py_ssize_t
10897 fillchar: Py_UCS4 = ' '
10898 /
10899
10900Return a centered string of length width.
10901
10902Padding is done using the specified fill character (default is a space).
10903[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904
10905static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010906unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10907/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010909 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910
Benjamin Petersonbac79492012-01-14 13:34:47 -050010911 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912 return NULL;
10913
Victor Stinnerc4b49542011-12-11 22:44:26 +010010914 if (PyUnicode_GET_LENGTH(self) >= width)
10915 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
Victor Stinnerc4b49542011-12-11 22:44:26 +010010917 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918 left = marg / 2 + (marg & width & 1);
10919
Victor Stinner9310abb2011-10-05 00:59:23 +020010920 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921}
10922
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010923/* This function assumes that str1 and str2 are readied by the caller. */
10924
Marc-André Lemburge5034372000-08-08 08:04:29 +000010925static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010926unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010927{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010928#define COMPARE(TYPE1, TYPE2) \
10929 do { \
10930 TYPE1* p1 = (TYPE1 *)data1; \
10931 TYPE2* p2 = (TYPE2 *)data2; \
10932 TYPE1* end = p1 + len; \
10933 Py_UCS4 c1, c2; \
10934 for (; p1 != end; p1++, p2++) { \
10935 c1 = *p1; \
10936 c2 = *p2; \
10937 if (c1 != c2) \
10938 return (c1 < c2) ? -1 : 1; \
10939 } \
10940 } \
10941 while (0)
10942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010943 int kind1, kind2;
10944 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010945 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 kind1 = PyUnicode_KIND(str1);
10948 kind2 = PyUnicode_KIND(str2);
10949 data1 = PyUnicode_DATA(str1);
10950 data2 = PyUnicode_DATA(str2);
10951 len1 = PyUnicode_GET_LENGTH(str1);
10952 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010953 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010954
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010955 switch(kind1) {
10956 case PyUnicode_1BYTE_KIND:
10957 {
10958 switch(kind2) {
10959 case PyUnicode_1BYTE_KIND:
10960 {
10961 int cmp = memcmp(data1, data2, len);
10962 /* normalize result of memcmp() into the range [-1; 1] */
10963 if (cmp < 0)
10964 return -1;
10965 if (cmp > 0)
10966 return 1;
10967 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010968 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010969 case PyUnicode_2BYTE_KIND:
10970 COMPARE(Py_UCS1, Py_UCS2);
10971 break;
10972 case PyUnicode_4BYTE_KIND:
10973 COMPARE(Py_UCS1, Py_UCS4);
10974 break;
10975 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010976 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010977 }
10978 break;
10979 }
10980 case PyUnicode_2BYTE_KIND:
10981 {
10982 switch(kind2) {
10983 case PyUnicode_1BYTE_KIND:
10984 COMPARE(Py_UCS2, Py_UCS1);
10985 break;
10986 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010987 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010988 COMPARE(Py_UCS2, Py_UCS2);
10989 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010990 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010991 case PyUnicode_4BYTE_KIND:
10992 COMPARE(Py_UCS2, Py_UCS4);
10993 break;
10994 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010995 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010996 }
10997 break;
10998 }
10999 case PyUnicode_4BYTE_KIND:
11000 {
11001 switch(kind2) {
11002 case PyUnicode_1BYTE_KIND:
11003 COMPARE(Py_UCS4, Py_UCS1);
11004 break;
11005 case PyUnicode_2BYTE_KIND:
11006 COMPARE(Py_UCS4, Py_UCS2);
11007 break;
11008 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020011009 {
11010#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11011 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11012 /* normalize result of wmemcmp() into the range [-1; 1] */
11013 if (cmp < 0)
11014 return -1;
11015 if (cmp > 0)
11016 return 1;
11017#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011018 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020011019#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011020 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020011021 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011022 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011023 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011024 }
11025 break;
11026 }
11027 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011028 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000011029 }
11030
Victor Stinner770e19e2012-10-04 22:59:45 +020011031 if (len1 == len2)
11032 return 0;
11033 if (len1 < len2)
11034 return -1;
11035 else
11036 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011037
11038#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011039}
11040
Benjamin Peterson621b4302016-09-09 13:54:34 -070011041static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011042unicode_compare_eq(PyObject *str1, PyObject *str2)
11043{
11044 int kind;
11045 void *data1, *data2;
11046 Py_ssize_t len;
11047 int cmp;
11048
Victor Stinnere5567ad2012-10-23 02:48:49 +020011049 len = PyUnicode_GET_LENGTH(str1);
11050 if (PyUnicode_GET_LENGTH(str2) != len)
11051 return 0;
11052 kind = PyUnicode_KIND(str1);
11053 if (PyUnicode_KIND(str2) != kind)
11054 return 0;
11055 data1 = PyUnicode_DATA(str1);
11056 data2 = PyUnicode_DATA(str2);
11057
11058 cmp = memcmp(data1, data2, len * kind);
11059 return (cmp == 0);
11060}
11061
11062
Alexander Belopolsky40018472011-02-26 01:02:56 +000011063int
11064PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11067 if (PyUnicode_READY(left) == -1 ||
11068 PyUnicode_READY(right) == -1)
11069 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011070
11071 /* a string is equal to itself */
11072 if (left == right)
11073 return 0;
11074
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011075 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011076 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011077 PyErr_Format(PyExc_TypeError,
11078 "Can't compare %.100s and %.100s",
11079 left->ob_type->tp_name,
11080 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081 return -1;
11082}
11083
Martin v. Löwis5b222132007-06-10 09:51:05 +000011084int
11085PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11086{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011087 Py_ssize_t i;
11088 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011090 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091
Victor Stinner910337b2011-10-03 03:20:16 +020011092 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011093 if (!PyUnicode_IS_READY(uni)) {
11094 const wchar_t *ws = _PyUnicode_WSTR(uni);
11095 /* Compare Unicode string and source character set string */
11096 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11097 if (chr != ustr[i])
11098 return (chr < ustr[i]) ? -1 : 1;
11099 }
11100 /* This check keeps Python strings that end in '\0' from comparing equal
11101 to C strings identical up to that point. */
11102 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11103 return 1; /* uni is longer */
11104 if (ustr[i])
11105 return -1; /* str is longer */
11106 return 0;
11107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011108 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011109 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011110 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011111 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011112 size_t len, len2 = strlen(str);
11113 int cmp;
11114
11115 len = Py_MIN(len1, len2);
11116 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011117 if (cmp != 0) {
11118 if (cmp < 0)
11119 return -1;
11120 else
11121 return 1;
11122 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011123 if (len1 > len2)
11124 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011125 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011126 return -1; /* str is longer */
11127 return 0;
11128 }
11129 else {
11130 void *data = PyUnicode_DATA(uni);
11131 /* Compare Unicode string and source character set string */
11132 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011133 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011134 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11135 /* This check keeps Python strings that end in '\0' from comparing equal
11136 to C strings identical up to that point. */
11137 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11138 return 1; /* uni is longer */
11139 if (str[i])
11140 return -1; /* str is longer */
11141 return 0;
11142 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011143}
11144
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011145static int
11146non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11147{
11148 size_t i, len;
11149 const wchar_t *p;
11150 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11151 if (strlen(str) != len)
11152 return 0;
11153 p = _PyUnicode_WSTR(unicode);
11154 assert(p);
11155 for (i = 0; i < len; i++) {
11156 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011157 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011158 return 0;
11159 }
11160 return 1;
11161}
11162
11163int
11164_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11165{
11166 size_t len;
11167 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011168 assert(str);
11169#ifndef NDEBUG
11170 for (const char *p = str; *p; p++) {
11171 assert((unsigned char)*p < 128);
11172 }
11173#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011174 if (PyUnicode_READY(unicode) == -1) {
11175 /* Memory error or bad data */
11176 PyErr_Clear();
11177 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11178 }
11179 if (!PyUnicode_IS_ASCII(unicode))
11180 return 0;
11181 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11182 return strlen(str) == len &&
11183 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11184}
11185
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011186int
11187_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11188{
11189 PyObject *right_uni;
11190 Py_hash_t hash;
11191
11192 assert(_PyUnicode_CHECK(left));
11193 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011194#ifndef NDEBUG
11195 for (const char *p = right->string; *p; p++) {
11196 assert((unsigned char)*p < 128);
11197 }
11198#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011199
11200 if (PyUnicode_READY(left) == -1) {
11201 /* memory error or bad data */
11202 PyErr_Clear();
11203 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11204 }
11205
11206 if (!PyUnicode_IS_ASCII(left))
11207 return 0;
11208
11209 right_uni = _PyUnicode_FromId(right); /* borrowed */
11210 if (right_uni == NULL) {
11211 /* memory error or bad data */
11212 PyErr_Clear();
11213 return _PyUnicode_EqualToASCIIString(left, right->string);
11214 }
11215
11216 if (left == right_uni)
11217 return 1;
11218
11219 if (PyUnicode_CHECK_INTERNED(left))
11220 return 0;
11221
11222 assert(_PyUnicode_HASH(right_uni) != 1);
11223 hash = _PyUnicode_HASH(left);
11224 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11225 return 0;
11226
11227 return unicode_compare_eq(left, right_uni);
11228}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011229
Alexander Belopolsky40018472011-02-26 01:02:56 +000011230PyObject *
11231PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011232{
11233 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011234
Victor Stinnere5567ad2012-10-23 02:48:49 +020011235 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11236 Py_RETURN_NOTIMPLEMENTED;
11237
11238 if (PyUnicode_READY(left) == -1 ||
11239 PyUnicode_READY(right) == -1)
11240 return NULL;
11241
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011242 if (left == right) {
11243 switch (op) {
11244 case Py_EQ:
11245 case Py_LE:
11246 case Py_GE:
11247 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011248 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011249 case Py_NE:
11250 case Py_LT:
11251 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011252 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011253 default:
11254 PyErr_BadArgument();
11255 return NULL;
11256 }
11257 }
11258 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011259 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011260 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011261 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011262 }
11263 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011264 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011265 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011266 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011267}
11268
Alexander Belopolsky40018472011-02-26 01:02:56 +000011269int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011270_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11271{
11272 return unicode_eq(aa, bb);
11273}
11274
11275int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011276PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011277{
Victor Stinner77282cb2013-04-14 19:22:47 +020011278 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 void *buf1, *buf2;
11280 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011281 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011282
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011283 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011285 "'in <string>' requires string as left operand, not %.100s",
11286 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011287 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011288 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011289 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011290 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011291 if (ensure_unicode(str) < 0)
11292 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011295 kind2 = PyUnicode_KIND(substr);
11296 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011297 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011299 len2 = PyUnicode_GET_LENGTH(substr);
11300 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011301 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011302 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011303 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011304 if (len2 == 1) {
11305 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11306 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011307 return result;
11308 }
11309 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011310 buf2 = _PyUnicode_AsKind(substr, kind1);
11311 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011312 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011313 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314
Victor Stinner77282cb2013-04-14 19:22:47 +020011315 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011316 case PyUnicode_1BYTE_KIND:
11317 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11318 break;
11319 case PyUnicode_2BYTE_KIND:
11320 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11321 break;
11322 case PyUnicode_4BYTE_KIND:
11323 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11324 break;
11325 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011326 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011328
Victor Stinner77282cb2013-04-14 19:22:47 +020011329 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 PyMem_Free(buf2);
11331
Guido van Rossum403d68b2000-03-13 15:55:09 +000011332 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011333}
11334
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335/* Concat to string or Unicode object giving a new Unicode object. */
11336
Alexander Belopolsky40018472011-02-26 01:02:56 +000011337PyObject *
11338PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011340 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011341 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011342 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011344 if (ensure_unicode(left) < 0)
11345 return NULL;
11346
11347 if (!PyUnicode_Check(right)) {
11348 PyErr_Format(PyExc_TypeError,
11349 "can only concatenate str (not \"%.200s\") to str",
11350 right->ob_type->tp_name);
11351 return NULL;
11352 }
11353 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011354 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355
11356 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011357 if (left == unicode_empty)
11358 return PyUnicode_FromObject(right);
11359 if (right == unicode_empty)
11360 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011362 left_len = PyUnicode_GET_LENGTH(left);
11363 right_len = PyUnicode_GET_LENGTH(right);
11364 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011365 PyErr_SetString(PyExc_OverflowError,
11366 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011367 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011368 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011369 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011370
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011371 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11372 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011373 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011376 result = PyUnicode_New(new_len, maxchar);
11377 if (result == NULL)
11378 return NULL;
11379 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11380 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11381 assert(_PyUnicode_CheckConsistency(result, 1));
11382 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383}
11384
Walter Dörwald1ab83302007-05-18 17:15:44 +000011385void
Victor Stinner23e56682011-10-03 03:54:37 +020011386PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011387{
Victor Stinner23e56682011-10-03 03:54:37 +020011388 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011389 Py_UCS4 maxchar, maxchar2;
11390 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011391
11392 if (p_left == NULL) {
11393 if (!PyErr_Occurred())
11394 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011395 return;
11396 }
Victor Stinner23e56682011-10-03 03:54:37 +020011397 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011398 if (right == NULL || left == NULL
11399 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011400 if (!PyErr_Occurred())
11401 PyErr_BadInternalCall();
11402 goto error;
11403 }
11404
Benjamin Petersonbac79492012-01-14 13:34:47 -050011405 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011406 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011407 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011408 goto error;
11409
Victor Stinner488fa492011-12-12 00:01:39 +010011410 /* Shortcuts */
11411 if (left == unicode_empty) {
11412 Py_DECREF(left);
11413 Py_INCREF(right);
11414 *p_left = right;
11415 return;
11416 }
11417 if (right == unicode_empty)
11418 return;
11419
11420 left_len = PyUnicode_GET_LENGTH(left);
11421 right_len = PyUnicode_GET_LENGTH(right);
11422 if (left_len > PY_SSIZE_T_MAX - right_len) {
11423 PyErr_SetString(PyExc_OverflowError,
11424 "strings are too large to concat");
11425 goto error;
11426 }
11427 new_len = left_len + right_len;
11428
11429 if (unicode_modifiable(left)
11430 && PyUnicode_CheckExact(right)
11431 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011432 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11433 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011434 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011435 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011436 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11437 {
11438 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011439 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011440 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011441
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011442 /* copy 'right' into the newly allocated area of 'left' */
11443 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011444 }
Victor Stinner488fa492011-12-12 00:01:39 +010011445 else {
11446 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11447 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011448 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011449
Victor Stinner488fa492011-12-12 00:01:39 +010011450 /* Concat the two Unicode strings */
11451 res = PyUnicode_New(new_len, maxchar);
11452 if (res == NULL)
11453 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011454 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11455 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011456 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011457 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011458 }
11459 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011460 return;
11461
11462error:
Victor Stinner488fa492011-12-12 00:01:39 +010011463 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011464}
11465
11466void
11467PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11468{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011469 PyUnicode_Append(pleft, right);
11470 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011471}
11472
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011473/*
11474Wraps stringlib_parse_args_finds() and additionally ensures that the
11475first argument is a unicode object.
11476*/
11477
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011478static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011479parse_args_finds_unicode(const char * function_name, PyObject *args,
11480 PyObject **substring,
11481 Py_ssize_t *start, Py_ssize_t *end)
11482{
11483 if(stringlib_parse_args_finds(function_name, args, substring,
11484 start, end)) {
11485 if (ensure_unicode(*substring) < 0)
11486 return 0;
11487 return 1;
11488 }
11489 return 0;
11490}
11491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011492PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011495Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011496string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011497interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498
11499static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011500unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011502 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011503 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011504 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011506 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 void *buf1, *buf2;
11508 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011510 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 kind1 = PyUnicode_KIND(self);
11514 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011515 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011516 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 len1 = PyUnicode_GET_LENGTH(self);
11519 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011521 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011522 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011523
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011524 buf1 = PyUnicode_DATA(self);
11525 buf2 = PyUnicode_DATA(substring);
11526 if (kind2 != kind1) {
11527 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011528 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011529 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011530 }
11531 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 case PyUnicode_1BYTE_KIND:
11533 iresult = ucs1lib_count(
11534 ((Py_UCS1*)buf1) + start, end - start,
11535 buf2, len2, PY_SSIZE_T_MAX
11536 );
11537 break;
11538 case PyUnicode_2BYTE_KIND:
11539 iresult = ucs2lib_count(
11540 ((Py_UCS2*)buf1) + start, end - start,
11541 buf2, len2, PY_SSIZE_T_MAX
11542 );
11543 break;
11544 case PyUnicode_4BYTE_KIND:
11545 iresult = ucs4lib_count(
11546 ((Py_UCS4*)buf1) + start, end - start,
11547 buf2, len2, PY_SSIZE_T_MAX
11548 );
11549 break;
11550 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011551 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 }
11553
11554 result = PyLong_FromSsize_t(iresult);
11555
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011556 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 return result;
11560}
11561
INADA Naoki3ae20562017-01-16 20:41:20 +090011562/*[clinic input]
11563str.encode as unicode_encode
11564
11565 encoding: str(c_default="NULL") = 'utf-8'
11566 The encoding in which to encode the string.
11567 errors: str(c_default="NULL") = 'strict'
11568 The error handling scheme to use for encoding errors.
11569 The default is 'strict' meaning that encoding errors raise a
11570 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11571 'xmlcharrefreplace' as well as any other name registered with
11572 codecs.register_error that can handle UnicodeEncodeErrors.
11573
11574Encode the string using the codec registered for encoding.
11575[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
11577static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011578unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011579/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011581 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011582}
11583
INADA Naoki3ae20562017-01-16 20:41:20 +090011584/*[clinic input]
11585str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586
INADA Naoki3ae20562017-01-16 20:41:20 +090011587 tabsize: int = 8
11588
11589Return a copy where all tab characters are expanded using spaces.
11590
11591If tabsize is not given, a tab size of 8 characters is assumed.
11592[clinic start generated code]*/
11593
11594static PyObject *
11595unicode_expandtabs_impl(PyObject *self, int tabsize)
11596/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011598 Py_ssize_t i, j, line_pos, src_len, incr;
11599 Py_UCS4 ch;
11600 PyObject *u;
11601 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011602 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011603 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604
Antoine Pitrou22425222011-10-04 19:10:51 +020011605 if (PyUnicode_READY(self) == -1)
11606 return NULL;
11607
Thomas Wouters7e474022000-07-16 12:04:32 +000011608 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011609 src_len = PyUnicode_GET_LENGTH(self);
11610 i = j = line_pos = 0;
11611 kind = PyUnicode_KIND(self);
11612 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011613 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011614 for (; i < src_len; i++) {
11615 ch = PyUnicode_READ(kind, src_data, i);
11616 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011617 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011619 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011621 goto overflow;
11622 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011624 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011627 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011628 goto overflow;
11629 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011631 if (ch == '\n' || ch == '\r')
11632 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011634 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011635 if (!found)
11636 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011637
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011639 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640 if (!u)
11641 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011642 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
Antoine Pitroue71d5742011-10-04 15:55:09 +020011644 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645
Antoine Pitroue71d5742011-10-04 15:55:09 +020011646 for (; i < src_len; i++) {
11647 ch = PyUnicode_READ(kind, src_data, i);
11648 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011650 incr = tabsize - (line_pos % tabsize);
11651 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011652 FILL(kind, dest_data, ' ', j, incr);
11653 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011655 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011656 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011657 line_pos++;
11658 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011659 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011660 if (ch == '\n' || ch == '\r')
11661 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011663 }
11664 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011665 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011666
Antoine Pitroue71d5742011-10-04 15:55:09 +020011667 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011668 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11669 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670}
11671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011672PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011673 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674\n\
11675Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011676such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677arguments start and end are interpreted as in slice notation.\n\
11678\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011679Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680
11681static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011684 /* initialize variables to prevent gcc warning */
11685 PyObject *substring = NULL;
11686 Py_ssize_t start = 0;
11687 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011688 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011690 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011693 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011696 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 if (result == -2)
11699 return NULL;
11700
Christian Heimes217cfd12007-12-02 14:31:20 +000011701 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702}
11703
11704static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011705unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011707 void *data;
11708 enum PyUnicode_Kind kind;
11709 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011710
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011711 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011712 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011714 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011715 if (PyUnicode_READY(self) == -1) {
11716 return NULL;
11717 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011718 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11719 PyErr_SetString(PyExc_IndexError, "string index out of range");
11720 return NULL;
11721 }
11722 kind = PyUnicode_KIND(self);
11723 data = PyUnicode_DATA(self);
11724 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011725 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726}
11727
Guido van Rossumc2504932007-09-18 19:42:40 +000011728/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011729 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011730static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011731unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732{
Guido van Rossumc2504932007-09-18 19:42:40 +000011733 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011734 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011735
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011736#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011737 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011738#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 if (_PyUnicode_HASH(self) != -1)
11740 return _PyUnicode_HASH(self);
11741 if (PyUnicode_READY(self) == -1)
11742 return -1;
11743 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011744 /*
11745 We make the hash of the empty string be 0, rather than using
11746 (prefix ^ suffix), since this slightly obfuscates the hash secret
11747 */
11748 if (len == 0) {
11749 _PyUnicode_HASH(self) = 0;
11750 return 0;
11751 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011752 x = _Py_HashBytes(PyUnicode_DATA(self),
11753 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011755 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756}
11757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011758PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011759 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011761Return the lowest index in S where substring sub is found, \n\
11762such that sub is contained within S[start:end]. Optional\n\
11763arguments start and end are interpreted as in slice notation.\n\
11764\n\
11765Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766
11767static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011770 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011771 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011772 PyObject *substring = NULL;
11773 Py_ssize_t start = 0;
11774 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011776 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011779 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011782 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 if (result == -2)
11785 return NULL;
11786
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787 if (result < 0) {
11788 PyErr_SetString(PyExc_ValueError, "substring not found");
11789 return NULL;
11790 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011791
Christian Heimes217cfd12007-12-02 14:31:20 +000011792 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793}
11794
INADA Naoki3ae20562017-01-16 20:41:20 +090011795/*[clinic input]
11796str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797
INADA Naoki3ae20562017-01-16 20:41:20 +090011798Return True if the string is a lowercase string, False otherwise.
11799
11800A string is lowercase if all cased characters in the string are lowercase and
11801there is at least one cased character in the string.
11802[clinic start generated code]*/
11803
11804static PyObject *
11805unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011806/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 Py_ssize_t i, length;
11809 int kind;
11810 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811 int cased;
11812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 if (PyUnicode_READY(self) == -1)
11814 return NULL;
11815 length = PyUnicode_GET_LENGTH(self);
11816 kind = PyUnicode_KIND(self);
11817 data = PyUnicode_DATA(self);
11818
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 if (length == 1)
11821 return PyBool_FromLong(
11822 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011824 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011826 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011827
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 for (i = 0; i < length; i++) {
11830 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011831
Benjamin Peterson29060642009-01-31 22:14:21 +000011832 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011833 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011834 else if (!cased && Py_UNICODE_ISLOWER(ch))
11835 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011837 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838}
11839
INADA Naoki3ae20562017-01-16 20:41:20 +090011840/*[clinic input]
11841str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842
INADA Naoki3ae20562017-01-16 20:41:20 +090011843Return True if the string is an uppercase string, False otherwise.
11844
11845A string is uppercase if all cased characters in the string are uppercase and
11846there is at least one cased character in the string.
11847[clinic start generated code]*/
11848
11849static PyObject *
11850unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011851/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011853 Py_ssize_t i, length;
11854 int kind;
11855 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856 int cased;
11857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 if (PyUnicode_READY(self) == -1)
11859 return NULL;
11860 length = PyUnicode_GET_LENGTH(self);
11861 kind = PyUnicode_KIND(self);
11862 data = PyUnicode_DATA(self);
11863
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011865 if (length == 1)
11866 return PyBool_FromLong(
11867 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011869 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011871 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011872
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 for (i = 0; i < length; i++) {
11875 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011876
Benjamin Peterson29060642009-01-31 22:14:21 +000011877 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011878 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 else if (!cased && Py_UNICODE_ISUPPER(ch))
11880 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011882 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883}
11884
INADA Naoki3ae20562017-01-16 20:41:20 +090011885/*[clinic input]
11886str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
INADA Naoki3ae20562017-01-16 20:41:20 +090011888Return True if the string is a title-cased string, False otherwise.
11889
11890In a title-cased string, upper- and title-case characters may only
11891follow uncased characters and lowercase characters only cased ones.
11892[clinic start generated code]*/
11893
11894static PyObject *
11895unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011896/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011898 Py_ssize_t i, length;
11899 int kind;
11900 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901 int cased, previous_is_cased;
11902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 if (PyUnicode_READY(self) == -1)
11904 return NULL;
11905 length = PyUnicode_GET_LENGTH(self);
11906 kind = PyUnicode_KIND(self);
11907 data = PyUnicode_DATA(self);
11908
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 if (length == 1) {
11911 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11912 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11913 (Py_UNICODE_ISUPPER(ch) != 0));
11914 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011916 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011917 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011918 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011919
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920 cased = 0;
11921 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 for (i = 0; i < length; i++) {
11923 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011924
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11926 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011927 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011928 previous_is_cased = 1;
11929 cased = 1;
11930 }
11931 else if (Py_UNICODE_ISLOWER(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
11938 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011940 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941}
11942
INADA Naoki3ae20562017-01-16 20:41:20 +090011943/*[clinic input]
11944str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
INADA Naoki3ae20562017-01-16 20:41:20 +090011946Return True if the string is a whitespace string, False otherwise.
11947
11948A string is whitespace if all characters in the string are whitespace and there
11949is at least one character in the string.
11950[clinic start generated code]*/
11951
11952static PyObject *
11953unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011954/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 Py_ssize_t i, length;
11957 int kind;
11958 void *data;
11959
11960 if (PyUnicode_READY(self) == -1)
11961 return NULL;
11962 length = PyUnicode_GET_LENGTH(self);
11963 kind = PyUnicode_KIND(self);
11964 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 if (length == 1)
11968 return PyBool_FromLong(
11969 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011971 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011973 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 for (i = 0; i < length; i++) {
11976 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011977 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011978 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011980 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981}
11982
INADA Naoki3ae20562017-01-16 20:41:20 +090011983/*[clinic input]
11984str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011985
INADA Naoki3ae20562017-01-16 20:41:20 +090011986Return True if the string is an alphabetic string, False otherwise.
11987
11988A string is alphabetic if all characters in the string are alphabetic and there
11989is at least one character in the string.
11990[clinic start generated code]*/
11991
11992static PyObject *
11993unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011994/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 Py_ssize_t i, length;
11997 int kind;
11998 void *data;
11999
12000 if (PyUnicode_READY(self) == -1)
12001 return NULL;
12002 length = PyUnicode_GET_LENGTH(self);
12003 kind = PyUnicode_KIND(self);
12004 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012005
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012006 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if (length == 1)
12008 return PyBool_FromLong(
12009 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012010
12011 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012013 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 for (i = 0; i < length; i++) {
12016 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012017 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012018 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012019 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012020}
12021
INADA Naoki3ae20562017-01-16 20:41:20 +090012022/*[clinic input]
12023str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012024
INADA Naoki3ae20562017-01-16 20:41:20 +090012025Return True if the string is an alpha-numeric string, False otherwise.
12026
12027A string is alpha-numeric if all characters in the string are alpha-numeric and
12028there is at least one character in the string.
12029[clinic start generated code]*/
12030
12031static PyObject *
12032unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012033/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 int kind;
12036 void *data;
12037 Py_ssize_t len, i;
12038
12039 if (PyUnicode_READY(self) == -1)
12040 return NULL;
12041
12042 kind = PyUnicode_KIND(self);
12043 data = PyUnicode_DATA(self);
12044 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012045
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012046 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 if (len == 1) {
12048 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12049 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12050 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012051
12052 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012054 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056 for (i = 0; i < len; i++) {
12057 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012058 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012059 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012060 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012061 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012062}
12063
INADA Naoki3ae20562017-01-16 20:41:20 +090012064/*[clinic input]
12065str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066
INADA Naoki3ae20562017-01-16 20:41:20 +090012067Return True if the string is a decimal string, False otherwise.
12068
12069A string is a decimal string if all characters in the string are decimal and
12070there is at least one character in the string.
12071[clinic start generated code]*/
12072
12073static PyObject *
12074unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012075/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012076{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 Py_ssize_t i, length;
12078 int kind;
12079 void *data;
12080
12081 if (PyUnicode_READY(self) == -1)
12082 return NULL;
12083 length = PyUnicode_GET_LENGTH(self);
12084 kind = PyUnicode_KIND(self);
12085 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 if (length == 1)
12089 return PyBool_FromLong(
12090 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012092 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012094 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012095
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 for (i = 0; i < length; i++) {
12097 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012098 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012100 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101}
12102
INADA Naoki3ae20562017-01-16 20:41:20 +090012103/*[clinic input]
12104str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105
INADA Naoki3ae20562017-01-16 20:41:20 +090012106Return True if the string is a digit string, False otherwise.
12107
12108A string is a digit string if all characters in the string are digits and there
12109is at least one character in the string.
12110[clinic start generated code]*/
12111
12112static PyObject *
12113unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012114/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 Py_ssize_t i, length;
12117 int kind;
12118 void *data;
12119
12120 if (PyUnicode_READY(self) == -1)
12121 return NULL;
12122 length = PyUnicode_GET_LENGTH(self);
12123 kind = PyUnicode_KIND(self);
12124 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 if (length == 1) {
12128 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12129 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12130 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012132 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012134 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136 for (i = 0; i < length; i++) {
12137 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012138 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012140 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141}
12142
INADA Naoki3ae20562017-01-16 20:41:20 +090012143/*[clinic input]
12144str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
INADA Naoki3ae20562017-01-16 20:41:20 +090012146Return True if the string is a numeric string, False otherwise.
12147
12148A string is numeric if all characters in the string are numeric and there is at
12149least one character in the string.
12150[clinic start generated code]*/
12151
12152static PyObject *
12153unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012154/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 Py_ssize_t i, length;
12157 int kind;
12158 void *data;
12159
12160 if (PyUnicode_READY(self) == -1)
12161 return NULL;
12162 length = PyUnicode_GET_LENGTH(self);
12163 kind = PyUnicode_KIND(self);
12164 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 if (length == 1)
12168 return PyBool_FromLong(
12169 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012171 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012173 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 for (i = 0; i < length; i++) {
12176 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012177 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012179 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180}
12181
Martin v. Löwis47383402007-08-15 07:32:56 +000012182int
12183PyUnicode_IsIdentifier(PyObject *self)
12184{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 int kind;
12186 void *data;
12187 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012188 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 if (PyUnicode_READY(self) == -1) {
12191 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012192 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 }
12194
12195 /* Special case for empty strings */
12196 if (PyUnicode_GET_LENGTH(self) == 0)
12197 return 0;
12198 kind = PyUnicode_KIND(self);
12199 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012200
12201 /* PEP 3131 says that the first character must be in
12202 XID_Start and subsequent characters in XID_Continue,
12203 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012204 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012205 letters, digits, underscore). However, given the current
12206 definition of XID_Start and XID_Continue, it is sufficient
12207 to check just for these, except that _ must be allowed
12208 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012210 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012211 return 0;
12212
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012213 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012215 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012216 return 1;
12217}
12218
INADA Naoki3ae20562017-01-16 20:41:20 +090012219/*[clinic input]
12220str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012221
INADA Naoki3ae20562017-01-16 20:41:20 +090012222Return True if the string is a valid Python identifier, False otherwise.
12223
12224Use keyword.iskeyword() to test for reserved identifiers such as "def" and
12225"class".
12226[clinic start generated code]*/
12227
12228static PyObject *
12229unicode_isidentifier_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012230/*[clinic end generated code: output=fe585a9666572905 input=916b0a3c9f57e919]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012231{
12232 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12233}
12234
INADA Naoki3ae20562017-01-16 20:41:20 +090012235/*[clinic input]
12236str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012237
INADA Naoki3ae20562017-01-16 20:41:20 +090012238Return True if the string is printable, False otherwise.
12239
12240A string is printable if all of its characters are considered printable in
12241repr() or if it is empty.
12242[clinic start generated code]*/
12243
12244static PyObject *
12245unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012246/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 Py_ssize_t i, length;
12249 int kind;
12250 void *data;
12251
12252 if (PyUnicode_READY(self) == -1)
12253 return NULL;
12254 length = PyUnicode_GET_LENGTH(self);
12255 kind = PyUnicode_KIND(self);
12256 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012257
12258 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 if (length == 1)
12260 return PyBool_FromLong(
12261 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 for (i = 0; i < length; i++) {
12264 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012265 Py_RETURN_FALSE;
12266 }
12267 }
12268 Py_RETURN_TRUE;
12269}
12270
INADA Naoki3ae20562017-01-16 20:41:20 +090012271/*[clinic input]
12272str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273
INADA Naoki3ae20562017-01-16 20:41:20 +090012274 iterable: object
12275 /
12276
12277Concatenate any number of strings.
12278
Martin Panter91a88662017-01-24 00:30:06 +000012279The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012280The result is returned as a new string.
12281
12282Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12283[clinic start generated code]*/
12284
12285static PyObject *
12286unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012287/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288{
INADA Naoki3ae20562017-01-16 20:41:20 +090012289 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290}
12291
Martin v. Löwis18e16552006-02-15 17:27:45 +000012292static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012293unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 if (PyUnicode_READY(self) == -1)
12296 return -1;
12297 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298}
12299
INADA Naoki3ae20562017-01-16 20:41:20 +090012300/*[clinic input]
12301str.ljust as unicode_ljust
12302
12303 width: Py_ssize_t
12304 fillchar: Py_UCS4 = ' '
12305 /
12306
12307Return a left-justified string of length width.
12308
12309Padding is done using the specified fill character (default is a space).
12310[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012311
12312static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012313unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12314/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012316 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012317 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318
Victor Stinnerc4b49542011-12-11 22:44:26 +010012319 if (PyUnicode_GET_LENGTH(self) >= width)
12320 return unicode_result_unchanged(self);
12321
12322 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012323}
12324
INADA Naoki3ae20562017-01-16 20:41:20 +090012325/*[clinic input]
12326str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327
INADA Naoki3ae20562017-01-16 20:41:20 +090012328Return a copy of the string converted to lowercase.
12329[clinic start generated code]*/
12330
12331static PyObject *
12332unicode_lower_impl(PyObject *self)
12333/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012335 if (PyUnicode_READY(self) == -1)
12336 return NULL;
12337 if (PyUnicode_IS_ASCII(self))
12338 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012339 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340}
12341
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012342#define LEFTSTRIP 0
12343#define RIGHTSTRIP 1
12344#define BOTHSTRIP 2
12345
12346/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012347static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012348
INADA Naoki3ae20562017-01-16 20:41:20 +090012349#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012350
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012351/* externally visible for str.strip(unicode) */
12352PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012353_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 void *data;
12356 int kind;
12357 Py_ssize_t i, j, len;
12358 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012359 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12362 return NULL;
12363
12364 kind = PyUnicode_KIND(self);
12365 data = PyUnicode_DATA(self);
12366 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012367 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12369 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012370 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012371
Benjamin Peterson14339b62009-01-31 16:36:08 +000012372 i = 0;
12373 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012374 while (i < len) {
12375 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12376 if (!BLOOM(sepmask, ch))
12377 break;
12378 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12379 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012380 i++;
12381 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012382 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012383
Benjamin Peterson14339b62009-01-31 16:36:08 +000012384 j = len;
12385 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012386 j--;
12387 while (j >= i) {
12388 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12389 if (!BLOOM(sepmask, ch))
12390 break;
12391 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12392 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012393 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012394 }
12395
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012397 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012398
Victor Stinner7931d9a2011-11-04 00:22:48 +010012399 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400}
12401
12402PyObject*
12403PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12404{
12405 unsigned char *data;
12406 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012407 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012408
Victor Stinnerde636f32011-10-01 03:55:54 +020012409 if (PyUnicode_READY(self) == -1)
12410 return NULL;
12411
Victor Stinner684d5fd2012-05-03 02:32:34 +020012412 length = PyUnicode_GET_LENGTH(self);
12413 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012414
Victor Stinner684d5fd2012-05-03 02:32:34 +020012415 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012416 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012417
Victor Stinnerde636f32011-10-01 03:55:54 +020012418 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012419 PyErr_SetString(PyExc_IndexError, "string index out of range");
12420 return NULL;
12421 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012422 if (start >= length || end < start)
12423 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012424
Victor Stinner684d5fd2012-05-03 02:32:34 +020012425 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012426 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012427 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012428 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012429 }
12430 else {
12431 kind = PyUnicode_KIND(self);
12432 data = PyUnicode_1BYTE_DATA(self);
12433 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012434 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012435 length);
12436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438
12439static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012440do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 Py_ssize_t len, i, j;
12443
12444 if (PyUnicode_READY(self) == -1)
12445 return NULL;
12446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012447 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012448
Victor Stinnercc7af722013-04-09 22:39:24 +020012449 if (PyUnicode_IS_ASCII(self)) {
12450 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12451
12452 i = 0;
12453 if (striptype != RIGHTSTRIP) {
12454 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012455 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012456 if (!_Py_ascii_whitespace[ch])
12457 break;
12458 i++;
12459 }
12460 }
12461
12462 j = len;
12463 if (striptype != LEFTSTRIP) {
12464 j--;
12465 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012466 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012467 if (!_Py_ascii_whitespace[ch])
12468 break;
12469 j--;
12470 }
12471 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012472 }
12473 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012474 else {
12475 int kind = PyUnicode_KIND(self);
12476 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012477
Victor Stinnercc7af722013-04-09 22:39:24 +020012478 i = 0;
12479 if (striptype != RIGHTSTRIP) {
12480 while (i < len) {
12481 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12482 if (!Py_UNICODE_ISSPACE(ch))
12483 break;
12484 i++;
12485 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012486 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012487
12488 j = len;
12489 if (striptype != LEFTSTRIP) {
12490 j--;
12491 while (j >= i) {
12492 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12493 if (!Py_UNICODE_ISSPACE(ch))
12494 break;
12495 j--;
12496 }
12497 j++;
12498 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012499 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012500
Victor Stinner7931d9a2011-11-04 00:22:48 +010012501 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012502}
12503
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012504
12505static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012506do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012507{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012508 if (sep != NULL && sep != Py_None) {
12509 if (PyUnicode_Check(sep))
12510 return _PyUnicode_XStrip(self, striptype, sep);
12511 else {
12512 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012513 "%s arg must be None or str",
12514 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012515 return NULL;
12516 }
12517 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012518
Benjamin Peterson14339b62009-01-31 16:36:08 +000012519 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012520}
12521
12522
INADA Naoki3ae20562017-01-16 20:41:20 +090012523/*[clinic input]
12524str.strip as unicode_strip
12525
12526 chars: object = None
12527 /
12528
Victor Stinner0c4a8282017-01-17 02:21:47 +010012529Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012530
12531If chars is given and not None, remove characters in chars instead.
12532[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012533
12534static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012535unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012536/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012537{
INADA Naoki3ae20562017-01-16 20:41:20 +090012538 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012539}
12540
12541
INADA Naoki3ae20562017-01-16 20:41:20 +090012542/*[clinic input]
12543str.lstrip as unicode_lstrip
12544
12545 chars: object = NULL
12546 /
12547
12548Return a copy of the string with leading whitespace removed.
12549
12550If chars is given and not None, remove characters in chars instead.
12551[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012552
12553static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012554unicode_lstrip_impl(PyObject *self, PyObject *chars)
12555/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012556{
INADA Naoki3ae20562017-01-16 20:41:20 +090012557 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012558}
12559
12560
INADA Naoki3ae20562017-01-16 20:41:20 +090012561/*[clinic input]
12562str.rstrip as unicode_rstrip
12563
12564 chars: object = NULL
12565 /
12566
12567Return a copy of the string with trailing whitespace removed.
12568
12569If chars is given and not None, remove characters in chars instead.
12570[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012571
12572static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012573unicode_rstrip_impl(PyObject *self, PyObject *chars)
12574/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012575{
INADA Naoki3ae20562017-01-16 20:41:20 +090012576 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012577}
12578
12579
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012581unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012582{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012583 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585
Serhiy Storchaka05997252013-01-26 12:14:02 +020012586 if (len < 1)
12587 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588
Victor Stinnerc4b49542011-12-11 22:44:26 +010012589 /* no repeat, return original string */
12590 if (len == 1)
12591 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012592
Benjamin Petersonbac79492012-01-14 13:34:47 -050012593 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 return NULL;
12595
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012596 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012597 PyErr_SetString(PyExc_OverflowError,
12598 "repeated string is too long");
12599 return NULL;
12600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012602
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012603 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604 if (!u)
12605 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012606 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012608 if (PyUnicode_GET_LENGTH(str) == 1) {
12609 const int kind = PyUnicode_KIND(str);
12610 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012611 if (kind == PyUnicode_1BYTE_KIND) {
12612 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012613 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012614 }
12615 else if (kind == PyUnicode_2BYTE_KIND) {
12616 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012617 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012618 ucs2[n] = fill_char;
12619 } else {
12620 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12621 assert(kind == PyUnicode_4BYTE_KIND);
12622 for (n = 0; n < len; ++n)
12623 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012624 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625 }
12626 else {
12627 /* number of characters copied this far */
12628 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012629 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012631 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012633 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012635 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012636 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012637 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638 }
12639
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012640 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012641 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642}
12643
Alexander Belopolsky40018472011-02-26 01:02:56 +000012644PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012645PyUnicode_Replace(PyObject *str,
12646 PyObject *substr,
12647 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012648 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012650 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12651 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012652 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012653 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654}
12655
INADA Naoki3ae20562017-01-16 20:41:20 +090012656/*[clinic input]
12657str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012658
INADA Naoki3ae20562017-01-16 20:41:20 +090012659 old: unicode
12660 new: unicode
12661 count: Py_ssize_t = -1
12662 Maximum number of occurrences to replace.
12663 -1 (the default value) means replace all occurrences.
12664 /
12665
12666Return a copy with all occurrences of substring old replaced by new.
12667
12668If the optional argument count is given, only the first count occurrences are
12669replaced.
12670[clinic start generated code]*/
12671
12672static PyObject *
12673unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12674 Py_ssize_t count)
12675/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012677 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012678 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012679 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680}
12681
Alexander Belopolsky40018472011-02-26 01:02:56 +000012682static PyObject *
12683unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012685 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 Py_ssize_t isize;
12687 Py_ssize_t osize, squote, dquote, i, o;
12688 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012689 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012691
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012693 return NULL;
12694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 isize = PyUnicode_GET_LENGTH(unicode);
12696 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698 /* Compute length of output, quote characters, and
12699 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012700 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701 max = 127;
12702 squote = dquote = 0;
12703 ikind = PyUnicode_KIND(unicode);
12704 for (i = 0; i < isize; i++) {
12705 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012706 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012708 case '\'': squote++; break;
12709 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012711 incr = 2;
12712 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012713 default:
12714 /* Fast-path ASCII */
12715 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012716 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012718 ;
12719 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012720 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012722 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012724 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012726 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012728 if (osize > PY_SSIZE_T_MAX - incr) {
12729 PyErr_SetString(PyExc_OverflowError,
12730 "string is too long to generate repr");
12731 return NULL;
12732 }
12733 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012734 }
12735
12736 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012737 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012739 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 if (dquote)
12741 /* Both squote and dquote present. Use squote,
12742 and escape them */
12743 osize += squote;
12744 else
12745 quote = '"';
12746 }
Victor Stinner55c08782013-04-14 18:45:39 +020012747 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748
12749 repr = PyUnicode_New(osize, max);
12750 if (repr == NULL)
12751 return NULL;
12752 okind = PyUnicode_KIND(repr);
12753 odata = PyUnicode_DATA(repr);
12754
12755 PyUnicode_WRITE(okind, odata, 0, quote);
12756 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012757 if (unchanged) {
12758 _PyUnicode_FastCopyCharacters(repr, 1,
12759 unicode, 0,
12760 isize);
12761 }
12762 else {
12763 for (i = 0, o = 1; i < isize; i++) {
12764 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765
Victor Stinner55c08782013-04-14 18:45:39 +020012766 /* Escape quotes and backslashes */
12767 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012768 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012769 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012770 continue;
12771 }
12772
12773 /* Map special whitespace to '\t', \n', '\r' */
12774 if (ch == '\t') {
12775 PyUnicode_WRITE(okind, odata, o++, '\\');
12776 PyUnicode_WRITE(okind, odata, o++, 't');
12777 }
12778 else if (ch == '\n') {
12779 PyUnicode_WRITE(okind, odata, o++, '\\');
12780 PyUnicode_WRITE(okind, odata, o++, 'n');
12781 }
12782 else if (ch == '\r') {
12783 PyUnicode_WRITE(okind, odata, o++, '\\');
12784 PyUnicode_WRITE(okind, odata, o++, 'r');
12785 }
12786
12787 /* Map non-printable US ASCII to '\xhh' */
12788 else if (ch < ' ' || ch == 0x7F) {
12789 PyUnicode_WRITE(okind, odata, o++, '\\');
12790 PyUnicode_WRITE(okind, odata, o++, 'x');
12791 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12792 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12793 }
12794
12795 /* Copy ASCII characters as-is */
12796 else if (ch < 0x7F) {
12797 PyUnicode_WRITE(okind, odata, o++, ch);
12798 }
12799
12800 /* Non-ASCII characters */
12801 else {
12802 /* Map Unicode whitespace and control characters
12803 (categories Z* and C* except ASCII space)
12804 */
12805 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12806 PyUnicode_WRITE(okind, odata, o++, '\\');
12807 /* Map 8-bit characters to '\xhh' */
12808 if (ch <= 0xff) {
12809 PyUnicode_WRITE(okind, odata, o++, 'x');
12810 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12811 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12812 }
12813 /* Map 16-bit characters to '\uxxxx' */
12814 else if (ch <= 0xffff) {
12815 PyUnicode_WRITE(okind, odata, o++, 'u');
12816 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12817 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12818 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12819 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12820 }
12821 /* Map 21-bit characters to '\U00xxxxxx' */
12822 else {
12823 PyUnicode_WRITE(okind, odata, o++, 'U');
12824 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12825 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12826 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12827 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12828 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12829 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12830 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12831 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12832 }
12833 }
12834 /* Copy characters as-is */
12835 else {
12836 PyUnicode_WRITE(okind, odata, o++, ch);
12837 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012838 }
12839 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012842 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012843 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844}
12845
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012846PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012847 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012848\n\
12849Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012850such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851arguments start and end are interpreted as in slice notation.\n\
12852\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012853Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012854
12855static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012856unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012857{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012858 /* initialize variables to prevent gcc warning */
12859 PyObject *substring = NULL;
12860 Py_ssize_t start = 0;
12861 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012862 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012864 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012867 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012869
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012870 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012872 if (result == -2)
12873 return NULL;
12874
Christian Heimes217cfd12007-12-02 14:31:20 +000012875 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012876}
12877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012878PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012879 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012881Return the highest index in S where substring sub is found,\n\
12882such that sub is contained within S[start:end]. Optional\n\
12883arguments start and end are interpreted as in slice notation.\n\
12884\n\
12885Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886
12887static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012888unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012889{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012890 /* initialize variables to prevent gcc warning */
12891 PyObject *substring = NULL;
12892 Py_ssize_t start = 0;
12893 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012894 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012896 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012898
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012899 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012900 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012901
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012902 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012904 if (result == -2)
12905 return NULL;
12906
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907 if (result < 0) {
12908 PyErr_SetString(PyExc_ValueError, "substring not found");
12909 return NULL;
12910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012911
Christian Heimes217cfd12007-12-02 14:31:20 +000012912 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913}
12914
INADA Naoki3ae20562017-01-16 20:41:20 +090012915/*[clinic input]
12916str.rjust as unicode_rjust
12917
12918 width: Py_ssize_t
12919 fillchar: Py_UCS4 = ' '
12920 /
12921
12922Return a right-justified string of length width.
12923
12924Padding is done using the specified fill character (default is a space).
12925[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926
12927static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012928unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12929/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012931 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932 return NULL;
12933
Victor Stinnerc4b49542011-12-11 22:44:26 +010012934 if (PyUnicode_GET_LENGTH(self) >= width)
12935 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012936
Victor Stinnerc4b49542011-12-11 22:44:26 +010012937 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938}
12939
Alexander Belopolsky40018472011-02-26 01:02:56 +000012940PyObject *
12941PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012943 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012944 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012946 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012947}
12948
INADA Naoki3ae20562017-01-16 20:41:20 +090012949/*[clinic input]
12950str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012951
INADA Naoki3ae20562017-01-16 20:41:20 +090012952 sep: object = None
12953 The delimiter according which to split the string.
12954 None (the default value) means split according to any whitespace,
12955 and discard empty strings from the result.
12956 maxsplit: Py_ssize_t = -1
12957 Maximum number of splits to do.
12958 -1 (the default value) means no limit.
12959
12960Return a list of the words in the string, using sep as the delimiter string.
12961[clinic start generated code]*/
12962
12963static PyObject *
12964unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12965/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012966{
INADA Naoki3ae20562017-01-16 20:41:20 +090012967 if (sep == Py_None)
12968 return split(self, NULL, maxsplit);
12969 if (PyUnicode_Check(sep))
12970 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012971
12972 PyErr_Format(PyExc_TypeError,
12973 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090012974 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012975 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012976}
12977
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012979PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012980{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012981 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012982 int kind1, kind2;
12983 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012985
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012986 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012987 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012988
Victor Stinner14f8f022011-10-05 20:58:25 +020012989 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 len1 = PyUnicode_GET_LENGTH(str_obj);
12992 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012993 if (kind1 < kind2 || len1 < len2) {
12994 _Py_INCREF_UNICODE_EMPTY();
12995 if (!unicode_empty)
12996 out = NULL;
12997 else {
12998 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12999 Py_DECREF(unicode_empty);
13000 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013001 return out;
13002 }
13003 buf1 = PyUnicode_DATA(str_obj);
13004 buf2 = PyUnicode_DATA(sep_obj);
13005 if (kind2 != kind1) {
13006 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13007 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013008 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013010
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013011 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013013 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13014 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13015 else
13016 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 break;
13018 case PyUnicode_2BYTE_KIND:
13019 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13020 break;
13021 case PyUnicode_4BYTE_KIND:
13022 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13023 break;
13024 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013025 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013027
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013028 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013029 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013030
13031 return out;
13032}
13033
13034
13035PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013036PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013037{
Thomas Wouters477c8d52006-05-27 19:21:47 +000013038 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013039 int kind1, kind2;
13040 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013041 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013042
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013043 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013044 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013045
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013046 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013047 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013048 len1 = PyUnicode_GET_LENGTH(str_obj);
13049 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013050 if (kind1 < kind2 || len1 < len2) {
13051 _Py_INCREF_UNICODE_EMPTY();
13052 if (!unicode_empty)
13053 out = NULL;
13054 else {
13055 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13056 Py_DECREF(unicode_empty);
13057 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013058 return out;
13059 }
13060 buf1 = PyUnicode_DATA(str_obj);
13061 buf2 = PyUnicode_DATA(sep_obj);
13062 if (kind2 != kind1) {
13063 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13064 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013065 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013067
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013068 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013069 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013070 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13071 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13072 else
13073 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013074 break;
13075 case PyUnicode_2BYTE_KIND:
13076 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13077 break;
13078 case PyUnicode_4BYTE_KIND:
13079 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13080 break;
13081 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013082 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013083 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013084
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013085 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013086 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013087
13088 return out;
13089}
13090
INADA Naoki3ae20562017-01-16 20:41:20 +090013091/*[clinic input]
13092str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013093
INADA Naoki3ae20562017-01-16 20:41:20 +090013094 sep: object
13095 /
13096
13097Partition the string into three parts using the given separator.
13098
13099This will search for the separator in the string. If the separator is found,
13100returns a 3-tuple containing the part before the separator, the separator
13101itself, and the part after it.
13102
13103If the separator is not found, returns a 3-tuple containing the original string
13104and two empty strings.
13105[clinic start generated code]*/
13106
13107static PyObject *
13108unicode_partition(PyObject *self, PyObject *sep)
13109/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013110{
INADA Naoki3ae20562017-01-16 20:41:20 +090013111 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013112}
13113
INADA Naoki3ae20562017-01-16 20:41:20 +090013114/*[clinic input]
13115str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013116
INADA Naoki3ae20562017-01-16 20:41:20 +090013117Partition the string into three parts using the given separator.
13118
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013119This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013120the separator is found, returns a 3-tuple containing the part before the
13121separator, the separator itself, and the part after it.
13122
13123If the separator is not found, returns a 3-tuple containing two empty strings
13124and the original string.
13125[clinic start generated code]*/
13126
13127static PyObject *
13128unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013129/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013130{
INADA Naoki3ae20562017-01-16 20:41:20 +090013131 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013132}
13133
Alexander Belopolsky40018472011-02-26 01:02:56 +000013134PyObject *
13135PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013136{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013137 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013138 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013139
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013140 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013141}
13142
INADA Naoki3ae20562017-01-16 20:41:20 +090013143/*[clinic input]
13144str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013145
INADA Naoki3ae20562017-01-16 20:41:20 +090013146Return a list of the words in the string, using sep as the delimiter string.
13147
13148Splits are done starting at the end of the string and working to the front.
13149[clinic start generated code]*/
13150
13151static PyObject *
13152unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13153/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013154{
INADA Naoki3ae20562017-01-16 20:41:20 +090013155 if (sep == Py_None)
13156 return rsplit(self, NULL, maxsplit);
13157 if (PyUnicode_Check(sep))
13158 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013159
13160 PyErr_Format(PyExc_TypeError,
13161 "must be str or None, not %.100s",
INADA Naoki3ae20562017-01-16 20:41:20 +090013162 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013163 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013164}
13165
INADA Naoki3ae20562017-01-16 20:41:20 +090013166/*[clinic input]
13167str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013169 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013170
13171Return a list of the lines in the string, breaking at line boundaries.
13172
13173Line breaks are not included in the resulting list unless keepends is given and
13174true.
13175[clinic start generated code]*/
13176
13177static PyObject *
13178unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013179/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013180{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013181 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182}
13183
13184static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013185PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013187 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188}
13189
INADA Naoki3ae20562017-01-16 20:41:20 +090013190/*[clinic input]
13191str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
INADA Naoki3ae20562017-01-16 20:41:20 +090013193Convert uppercase characters to lowercase and lowercase characters to uppercase.
13194[clinic start generated code]*/
13195
13196static PyObject *
13197unicode_swapcase_impl(PyObject *self)
13198/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013200 if (PyUnicode_READY(self) == -1)
13201 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013202 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203}
13204
Larry Hastings61272b72014-01-07 12:41:53 -080013205/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013206
Larry Hastings31826802013-10-19 00:09:25 -070013207@staticmethod
13208str.maketrans as unicode_maketrans
13209
13210 x: object
13211
13212 y: unicode=NULL
13213
13214 z: unicode=NULL
13215
13216 /
13217
13218Return a translation table usable for str.translate().
13219
13220If there is only one argument, it must be a dictionary mapping Unicode
13221ordinals (integers) or characters to Unicode ordinals, strings or None.
13222Character keys will be then converted to ordinals.
13223If there are two arguments, they must be strings of equal length, and
13224in the resulting dictionary, each character in x will be mapped to the
13225character at the same position in y. If there is a third argument, it
13226must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013227[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013228
Larry Hastings31826802013-10-19 00:09:25 -070013229static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013230unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013231/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013232{
Georg Brandlceee0772007-11-27 23:48:05 +000013233 PyObject *new = NULL, *key, *value;
13234 Py_ssize_t i = 0;
13235 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013236
Georg Brandlceee0772007-11-27 23:48:05 +000013237 new = PyDict_New();
13238 if (!new)
13239 return NULL;
13240 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013241 int x_kind, y_kind, z_kind;
13242 void *x_data, *y_data, *z_data;
13243
Georg Brandlceee0772007-11-27 23:48:05 +000013244 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013245 if (!PyUnicode_Check(x)) {
13246 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13247 "be a string if there is a second argument");
13248 goto err;
13249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013250 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013251 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13252 "arguments must have equal length");
13253 goto err;
13254 }
13255 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013256 x_kind = PyUnicode_KIND(x);
13257 y_kind = PyUnicode_KIND(y);
13258 x_data = PyUnicode_DATA(x);
13259 y_data = PyUnicode_DATA(y);
13260 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13261 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013262 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013263 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013264 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013265 if (!value) {
13266 Py_DECREF(key);
13267 goto err;
13268 }
Georg Brandlceee0772007-11-27 23:48:05 +000013269 res = PyDict_SetItem(new, key, value);
13270 Py_DECREF(key);
13271 Py_DECREF(value);
13272 if (res < 0)
13273 goto err;
13274 }
13275 /* create entries for deleting chars in z */
13276 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013277 z_kind = PyUnicode_KIND(z);
13278 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013279 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013280 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013281 if (!key)
13282 goto err;
13283 res = PyDict_SetItem(new, key, Py_None);
13284 Py_DECREF(key);
13285 if (res < 0)
13286 goto err;
13287 }
13288 }
13289 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013290 int kind;
13291 void *data;
13292
Georg Brandlceee0772007-11-27 23:48:05 +000013293 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013294 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013295 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13296 "to maketrans it must be a dict");
13297 goto err;
13298 }
13299 /* copy entries into the new dict, converting string keys to int keys */
13300 while (PyDict_Next(x, &i, &key, &value)) {
13301 if (PyUnicode_Check(key)) {
13302 /* convert string keys to integer keys */
13303 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013304 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013305 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13306 "table must be of length 1");
13307 goto err;
13308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013309 kind = PyUnicode_KIND(key);
13310 data = PyUnicode_DATA(key);
13311 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013312 if (!newkey)
13313 goto err;
13314 res = PyDict_SetItem(new, newkey, value);
13315 Py_DECREF(newkey);
13316 if (res < 0)
13317 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013318 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013319 /* just keep integer keys */
13320 if (PyDict_SetItem(new, key, value) < 0)
13321 goto err;
13322 } else {
13323 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13324 "be strings or integers");
13325 goto err;
13326 }
13327 }
13328 }
13329 return new;
13330 err:
13331 Py_DECREF(new);
13332 return NULL;
13333}
13334
INADA Naoki3ae20562017-01-16 20:41:20 +090013335/*[clinic input]
13336str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337
INADA Naoki3ae20562017-01-16 20:41:20 +090013338 table: object
13339 Translation table, which must be a mapping of Unicode ordinals to
13340 Unicode ordinals, strings, or None.
13341 /
13342
13343Replace each character in the string using the given translation table.
13344
13345The table must implement lookup/indexing via __getitem__, for instance a
13346dictionary or list. If this operation raises LookupError, the character is
13347left untouched. Characters mapped to None are deleted.
13348[clinic start generated code]*/
13349
13350static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013351unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013352/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013354 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355}
13356
INADA Naoki3ae20562017-01-16 20:41:20 +090013357/*[clinic input]
13358str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013359
INADA Naoki3ae20562017-01-16 20:41:20 +090013360Return a copy of the string converted to uppercase.
13361[clinic start generated code]*/
13362
13363static PyObject *
13364unicode_upper_impl(PyObject *self)
13365/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013367 if (PyUnicode_READY(self) == -1)
13368 return NULL;
13369 if (PyUnicode_IS_ASCII(self))
13370 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013371 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013372}
13373
INADA Naoki3ae20562017-01-16 20:41:20 +090013374/*[clinic input]
13375str.zfill as unicode_zfill
13376
13377 width: Py_ssize_t
13378 /
13379
13380Pad a numeric string with zeros on the left, to fill a field of the given width.
13381
13382The string is never truncated.
13383[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013384
13385static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013386unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013387/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013389 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013390 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013391 int kind;
13392 void *data;
13393 Py_UCS4 chr;
13394
Benjamin Petersonbac79492012-01-14 13:34:47 -050013395 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013396 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013397
Victor Stinnerc4b49542011-12-11 22:44:26 +010013398 if (PyUnicode_GET_LENGTH(self) >= width)
13399 return unicode_result_unchanged(self);
13400
13401 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402
13403 u = pad(self, fill, 0, '0');
13404
Walter Dörwald068325e2002-04-15 13:36:47 +000013405 if (u == NULL)
13406 return NULL;
13407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013408 kind = PyUnicode_KIND(u);
13409 data = PyUnicode_DATA(u);
13410 chr = PyUnicode_READ(kind, data, fill);
13411
13412 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013413 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013414 PyUnicode_WRITE(kind, data, 0, chr);
13415 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013416 }
13417
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013418 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013419 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013420}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421
13422#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013423static PyObject *
13424unicode__decimal2ascii(PyObject *self)
13425{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013426 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013427}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013428#endif
13429
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013430PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013431 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013432\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013433Return True if S starts with the specified prefix, False otherwise.\n\
13434With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013435With optional end, stop comparing S at that position.\n\
13436prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013437
13438static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013439unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013441{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013442 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013443 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013444 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013445 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013446 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013447
Jesus Ceaac451502011-04-20 17:09:23 +020013448 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013449 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013450 if (PyTuple_Check(subobj)) {
13451 Py_ssize_t i;
13452 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013453 substring = PyTuple_GET_ITEM(subobj, i);
13454 if (!PyUnicode_Check(substring)) {
13455 PyErr_Format(PyExc_TypeError,
13456 "tuple for startswith must only contain str, "
13457 "not %.100s",
13458 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013459 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013460 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013461 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013462 if (result == -1)
13463 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013464 if (result) {
13465 Py_RETURN_TRUE;
13466 }
13467 }
13468 /* nothing matched */
13469 Py_RETURN_FALSE;
13470 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013471 if (!PyUnicode_Check(subobj)) {
13472 PyErr_Format(PyExc_TypeError,
13473 "startswith first arg must be str or "
13474 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013475 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013476 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013477 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013478 if (result == -1)
13479 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013480 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013481}
13482
13483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013484PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013486\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013487Return True if S ends with the specified suffix, False otherwise.\n\
13488With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013489With optional end, stop comparing S at that position.\n\
13490suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013491
13492static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013493unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013495{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013496 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013497 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013498 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013499 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013500 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013501
Jesus Ceaac451502011-04-20 17:09:23 +020013502 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013504 if (PyTuple_Check(subobj)) {
13505 Py_ssize_t i;
13506 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013507 substring = PyTuple_GET_ITEM(subobj, i);
13508 if (!PyUnicode_Check(substring)) {
13509 PyErr_Format(PyExc_TypeError,
13510 "tuple for endswith must only contain str, "
13511 "not %.100s",
13512 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013513 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013514 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013515 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013516 if (result == -1)
13517 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013518 if (result) {
13519 Py_RETURN_TRUE;
13520 }
13521 }
13522 Py_RETURN_FALSE;
13523 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013524 if (!PyUnicode_Check(subobj)) {
13525 PyErr_Format(PyExc_TypeError,
13526 "endswith first arg must be str or "
13527 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013529 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013530 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013531 if (result == -1)
13532 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013533 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013534}
13535
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013536static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013537_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013538{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013539 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13540 writer->data = PyUnicode_DATA(writer->buffer);
13541
13542 if (!writer->readonly) {
13543 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013544 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013545 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013546 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013547 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13548 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13549 writer->kind = PyUnicode_WCHAR_KIND;
13550 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13551
Victor Stinner8f674cc2013-04-17 23:02:17 +020013552 /* Copy-on-write mode: set buffer size to 0 so
13553 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13554 * next write. */
13555 writer->size = 0;
13556 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013557}
13558
Victor Stinnerd3f08822012-05-29 12:57:52 +020013559void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013560_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013561{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013562 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013563
13564 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013565 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013566
13567 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13568 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13569 writer->kind = PyUnicode_WCHAR_KIND;
13570 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013571}
13572
Victor Stinnerd3f08822012-05-29 12:57:52 +020013573int
13574_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13575 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013576{
13577 Py_ssize_t newlen;
13578 PyObject *newbuffer;
13579
Victor Stinner2740e462016-09-06 16:58:36 -070013580 assert(maxchar <= MAX_UNICODE);
13581
Victor Stinnerca9381e2015-09-22 00:58:32 +020013582 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013583 assert((maxchar > writer->maxchar && length >= 0)
13584 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013585
Victor Stinner202fdca2012-05-07 12:47:02 +020013586 if (length > PY_SSIZE_T_MAX - writer->pos) {
13587 PyErr_NoMemory();
13588 return -1;
13589 }
13590 newlen = writer->pos + length;
13591
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013592 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013593
Victor Stinnerd3f08822012-05-29 12:57:52 +020013594 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013595 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013596 if (writer->overallocate
13597 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13598 /* overallocate to limit the number of realloc() */
13599 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013600 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013601 if (newlen < writer->min_length)
13602 newlen = writer->min_length;
13603
Victor Stinnerd3f08822012-05-29 12:57:52 +020013604 writer->buffer = PyUnicode_New(newlen, maxchar);
13605 if (writer->buffer == NULL)
13606 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013607 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013608 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013609 if (writer->overallocate
13610 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13611 /* overallocate to limit the number of realloc() */
13612 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013613 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013614 if (newlen < writer->min_length)
13615 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013616
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013617 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013618 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013619 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013620 newbuffer = PyUnicode_New(newlen, maxchar);
13621 if (newbuffer == NULL)
13622 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013623 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13624 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013625 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013626 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013627 }
13628 else {
13629 newbuffer = resize_compact(writer->buffer, newlen);
13630 if (newbuffer == NULL)
13631 return -1;
13632 }
13633 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013634 }
13635 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013636 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013637 newbuffer = PyUnicode_New(writer->size, maxchar);
13638 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013639 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013640 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13641 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013642 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013643 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013644 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013645 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013646
13647#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013648}
13649
Victor Stinnerca9381e2015-09-22 00:58:32 +020013650int
13651_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13652 enum PyUnicode_Kind kind)
13653{
13654 Py_UCS4 maxchar;
13655
13656 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13657 assert(writer->kind < kind);
13658
13659 switch (kind)
13660 {
13661 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13662 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13663 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13664 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013665 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013666 }
13667
13668 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13669}
13670
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013671static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013672_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013673{
Victor Stinner2740e462016-09-06 16:58:36 -070013674 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013675 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13676 return -1;
13677 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13678 writer->pos++;
13679 return 0;
13680}
13681
13682int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013683_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13684{
13685 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13686}
13687
13688int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013689_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13690{
13691 Py_UCS4 maxchar;
13692 Py_ssize_t len;
13693
13694 if (PyUnicode_READY(str) == -1)
13695 return -1;
13696 len = PyUnicode_GET_LENGTH(str);
13697 if (len == 0)
13698 return 0;
13699 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13700 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013701 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013702 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013703 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013704 Py_INCREF(str);
13705 writer->buffer = str;
13706 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013707 writer->pos += len;
13708 return 0;
13709 }
13710 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13711 return -1;
13712 }
13713 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13714 str, 0, len);
13715 writer->pos += len;
13716 return 0;
13717}
13718
Victor Stinnere215d962012-10-06 23:03:36 +020013719int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013720_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13721 Py_ssize_t start, Py_ssize_t end)
13722{
13723 Py_UCS4 maxchar;
13724 Py_ssize_t len;
13725
13726 if (PyUnicode_READY(str) == -1)
13727 return -1;
13728
13729 assert(0 <= start);
13730 assert(end <= PyUnicode_GET_LENGTH(str));
13731 assert(start <= end);
13732
13733 if (end == 0)
13734 return 0;
13735
13736 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13737 return _PyUnicodeWriter_WriteStr(writer, str);
13738
13739 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13740 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13741 else
13742 maxchar = writer->maxchar;
13743 len = end - start;
13744
13745 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13746 return -1;
13747
13748 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13749 str, start, len);
13750 writer->pos += len;
13751 return 0;
13752}
13753
13754int
Victor Stinner4a587072013-11-19 12:54:53 +010013755_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13756 const char *ascii, Py_ssize_t len)
13757{
13758 if (len == -1)
13759 len = strlen(ascii);
13760
13761 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13762
13763 if (writer->buffer == NULL && !writer->overallocate) {
13764 PyObject *str;
13765
13766 str = _PyUnicode_FromASCII(ascii, len);
13767 if (str == NULL)
13768 return -1;
13769
13770 writer->readonly = 1;
13771 writer->buffer = str;
13772 _PyUnicodeWriter_Update(writer);
13773 writer->pos += len;
13774 return 0;
13775 }
13776
13777 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13778 return -1;
13779
13780 switch (writer->kind)
13781 {
13782 case PyUnicode_1BYTE_KIND:
13783 {
13784 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13785 Py_UCS1 *data = writer->data;
13786
Christian Heimesf051e432016-09-13 20:22:02 +020013787 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013788 break;
13789 }
13790 case PyUnicode_2BYTE_KIND:
13791 {
13792 _PyUnicode_CONVERT_BYTES(
13793 Py_UCS1, Py_UCS2,
13794 ascii, ascii + len,
13795 (Py_UCS2 *)writer->data + writer->pos);
13796 break;
13797 }
13798 case PyUnicode_4BYTE_KIND:
13799 {
13800 _PyUnicode_CONVERT_BYTES(
13801 Py_UCS1, Py_UCS4,
13802 ascii, ascii + len,
13803 (Py_UCS4 *)writer->data + writer->pos);
13804 break;
13805 }
13806 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013807 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013808 }
13809
13810 writer->pos += len;
13811 return 0;
13812}
13813
13814int
13815_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13816 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013817{
13818 Py_UCS4 maxchar;
13819
13820 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13821 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13822 return -1;
13823 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13824 writer->pos += len;
13825 return 0;
13826}
13827
Victor Stinnerd3f08822012-05-29 12:57:52 +020013828PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013829_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013830{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013831 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013832
Victor Stinnerd3f08822012-05-29 12:57:52 +020013833 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013834 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013835 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013836 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013837
13838 str = writer->buffer;
13839 writer->buffer = NULL;
13840
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013841 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013842 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13843 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013844 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013845
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013846 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13847 PyObject *str2;
13848 str2 = resize_compact(str, writer->pos);
13849 if (str2 == NULL) {
13850 Py_DECREF(str);
13851 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013852 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013853 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013854 }
13855
Victor Stinner15a0bd32013-07-08 22:29:55 +020013856 assert(_PyUnicode_CheckConsistency(str, 1));
13857 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013858}
13859
Victor Stinnerd3f08822012-05-29 12:57:52 +020013860void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013861_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013862{
13863 Py_CLEAR(writer->buffer);
13864}
13865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013866#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013867
13868PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013870\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013871Return a formatted version of S, using substitutions from args and kwargs.\n\
13872The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013873
Eric Smith27bbca62010-11-04 17:06:58 +000013874PyDoc_STRVAR(format_map__doc__,
13875 "S.format_map(mapping) -> str\n\
13876\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013877Return a formatted version of S, using substitutions from mapping.\n\
13878The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013879
INADA Naoki3ae20562017-01-16 20:41:20 +090013880/*[clinic input]
13881str.__format__ as unicode___format__
13882
13883 format_spec: unicode
13884 /
13885
13886Return a formatted version of the string as described by format_spec.
13887[clinic start generated code]*/
13888
Eric Smith4a7d76d2008-05-30 18:10:19 +000013889static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013890unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013891/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013892{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013893 _PyUnicodeWriter writer;
13894 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013895
Victor Stinnerd3f08822012-05-29 12:57:52 +020013896 if (PyUnicode_READY(self) == -1)
13897 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013898 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013899 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13900 self, format_spec, 0,
13901 PyUnicode_GET_LENGTH(format_spec));
13902 if (ret == -1) {
13903 _PyUnicodeWriter_Dealloc(&writer);
13904 return NULL;
13905 }
13906 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013907}
13908
INADA Naoki3ae20562017-01-16 20:41:20 +090013909/*[clinic input]
13910str.__sizeof__ as unicode_sizeof
13911
13912Return the size of the string in memory, in bytes.
13913[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013914
13915static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013916unicode_sizeof_impl(PyObject *self)
13917/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013918{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013919 Py_ssize_t size;
13920
13921 /* If it's a compact object, account for base structure +
13922 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013923 if (PyUnicode_IS_COMPACT_ASCII(self))
13924 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13925 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013926 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013927 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013928 else {
13929 /* If it is a two-block object, account for base object, and
13930 for character block if present. */
13931 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013932 if (_PyUnicode_DATA_ANY(self))
13933 size += (PyUnicode_GET_LENGTH(self) + 1) *
13934 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013935 }
13936 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013937 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013938 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13939 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13940 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13941 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013942
13943 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013944}
13945
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013946static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013947unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013948{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013949 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013950 if (!copy)
13951 return NULL;
13952 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013953}
13954
Guido van Rossumd57fd912000-03-10 22:53:23 +000013955static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013956 UNICODE_ENCODE_METHODDEF
13957 UNICODE_REPLACE_METHODDEF
13958 UNICODE_SPLIT_METHODDEF
13959 UNICODE_RSPLIT_METHODDEF
13960 UNICODE_JOIN_METHODDEF
13961 UNICODE_CAPITALIZE_METHODDEF
13962 UNICODE_CASEFOLD_METHODDEF
13963 UNICODE_TITLE_METHODDEF
13964 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013965 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013966 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013967 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013968 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013969 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013970 UNICODE_LJUST_METHODDEF
13971 UNICODE_LOWER_METHODDEF
13972 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013973 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13974 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013975 UNICODE_RJUST_METHODDEF
13976 UNICODE_RSTRIP_METHODDEF
13977 UNICODE_RPARTITION_METHODDEF
13978 UNICODE_SPLITLINES_METHODDEF
13979 UNICODE_STRIP_METHODDEF
13980 UNICODE_SWAPCASE_METHODDEF
13981 UNICODE_TRANSLATE_METHODDEF
13982 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013983 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13984 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013985 UNICODE_ISLOWER_METHODDEF
13986 UNICODE_ISUPPER_METHODDEF
13987 UNICODE_ISTITLE_METHODDEF
13988 UNICODE_ISSPACE_METHODDEF
13989 UNICODE_ISDECIMAL_METHODDEF
13990 UNICODE_ISDIGIT_METHODDEF
13991 UNICODE_ISNUMERIC_METHODDEF
13992 UNICODE_ISALPHA_METHODDEF
13993 UNICODE_ISALNUM_METHODDEF
13994 UNICODE_ISIDENTIFIER_METHODDEF
13995 UNICODE_ISPRINTABLE_METHODDEF
13996 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013997 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013998 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013999 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070014000 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090014001 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000014002#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014003 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014004 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005#endif
14006
Benjamin Peterson14339b62009-01-31 16:36:08 +000014007 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014008 {NULL, NULL}
14009};
14010
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014011static PyObject *
14012unicode_mod(PyObject *v, PyObject *w)
14013{
Brian Curtindfc80e32011-08-10 20:28:54 -050014014 if (!PyUnicode_Check(v))
14015 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000014016 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014017}
14018
14019static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014020 0, /*nb_add*/
14021 0, /*nb_subtract*/
14022 0, /*nb_multiply*/
14023 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014024};
14025
Guido van Rossumd57fd912000-03-10 22:53:23 +000014026static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014027 (lenfunc) unicode_length, /* sq_length */
14028 PyUnicode_Concat, /* sq_concat */
14029 (ssizeargfunc) unicode_repeat, /* sq_repeat */
14030 (ssizeargfunc) unicode_getitem, /* sq_item */
14031 0, /* sq_slice */
14032 0, /* sq_ass_item */
14033 0, /* sq_ass_slice */
14034 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014035};
14036
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014037static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014038unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014040 if (PyUnicode_READY(self) == -1)
14041 return NULL;
14042
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000014043 if (PyIndex_Check(item)) {
14044 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014045 if (i == -1 && PyErr_Occurred())
14046 return NULL;
14047 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014048 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014049 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014050 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000014051 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014052 PyObject *result;
14053 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014054 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014055 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014056
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014057 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014058 return NULL;
14059 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014060 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14061 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014062
14063 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014064 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014065 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014066 slicelength == PyUnicode_GET_LENGTH(self)) {
14067 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014068 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014069 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014070 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014071 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014072 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014073 src_kind = PyUnicode_KIND(self);
14074 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014075 if (!PyUnicode_IS_ASCII(self)) {
14076 kind_limit = kind_maxchar_limit(src_kind);
14077 max_char = 0;
14078 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14079 ch = PyUnicode_READ(src_kind, src_data, cur);
14080 if (ch > max_char) {
14081 max_char = ch;
14082 if (max_char >= kind_limit)
14083 break;
14084 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014085 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014086 }
Victor Stinner55c99112011-10-13 01:17:06 +020014087 else
14088 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014089 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014090 if (result == NULL)
14091 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014092 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014093 dest_data = PyUnicode_DATA(result);
14094
14095 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014096 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14097 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014098 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014099 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014100 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014101 } else {
14102 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14103 return NULL;
14104 }
14105}
14106
14107static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 (lenfunc)unicode_length, /* mp_length */
14109 (binaryfunc)unicode_subscript, /* mp_subscript */
14110 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014111};
14112
Guido van Rossumd57fd912000-03-10 22:53:23 +000014113
Guido van Rossumd57fd912000-03-10 22:53:23 +000014114/* Helpers for PyUnicode_Format() */
14115
Victor Stinnera47082312012-10-04 02:19:54 +020014116struct unicode_formatter_t {
14117 PyObject *args;
14118 int args_owned;
14119 Py_ssize_t arglen, argidx;
14120 PyObject *dict;
14121
14122 enum PyUnicode_Kind fmtkind;
14123 Py_ssize_t fmtcnt, fmtpos;
14124 void *fmtdata;
14125 PyObject *fmtstr;
14126
14127 _PyUnicodeWriter writer;
14128};
14129
14130struct unicode_format_arg_t {
14131 Py_UCS4 ch;
14132 int flags;
14133 Py_ssize_t width;
14134 int prec;
14135 int sign;
14136};
14137
Guido van Rossumd57fd912000-03-10 22:53:23 +000014138static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014139unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014140{
Victor Stinnera47082312012-10-04 02:19:54 +020014141 Py_ssize_t argidx = ctx->argidx;
14142
14143 if (argidx < ctx->arglen) {
14144 ctx->argidx++;
14145 if (ctx->arglen < 0)
14146 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014147 else
Victor Stinnera47082312012-10-04 02:19:54 +020014148 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014149 }
14150 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014151 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014152 return NULL;
14153}
14154
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014155/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014156
Victor Stinnera47082312012-10-04 02:19:54 +020014157/* Format a float into the writer if the writer is not NULL, or into *p_output
14158 otherwise.
14159
14160 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014161static int
Victor Stinnera47082312012-10-04 02:19:54 +020014162formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14163 PyObject **p_output,
14164 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014165{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014166 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014167 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014168 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014169 int prec;
14170 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014171
Guido van Rossumd57fd912000-03-10 22:53:23 +000014172 x = PyFloat_AsDouble(v);
14173 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014174 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014175
Victor Stinnera47082312012-10-04 02:19:54 +020014176 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014177 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014178 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014179
Victor Stinnera47082312012-10-04 02:19:54 +020014180 if (arg->flags & F_ALT)
14181 dtoa_flags = Py_DTSF_ALT;
14182 else
14183 dtoa_flags = 0;
14184 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014185 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014186 return -1;
14187 len = strlen(p);
14188 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014189 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014190 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014191 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014192 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014193 }
14194 else
14195 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014196 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014197 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014198}
14199
Victor Stinnerd0880d52012-04-27 23:40:13 +020014200/* formatlong() emulates the format codes d, u, o, x and X, and
14201 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14202 * Python's regular ints.
14203 * Return value: a new PyUnicodeObject*, or NULL if error.
14204 * The output string is of the form
14205 * "-"? ("0x" | "0X")? digit+
14206 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14207 * set in flags. The case of hex digits will be correct,
14208 * There will be at least prec digits, zero-filled on the left if
14209 * necessary to get that many.
14210 * val object to be converted
14211 * flags bitmask of format flags; only F_ALT is looked at
14212 * prec minimum number of digits; 0-fill on left if needed
14213 * type a character in [duoxX]; u acts the same as d
14214 *
14215 * CAUTION: o, x and X conversions on regular ints can never
14216 * produce a '-' sign, but can for Python's unbounded ints.
14217 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014218PyObject *
14219_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014220{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014221 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014222 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014223 Py_ssize_t i;
14224 int sign; /* 1 if '-', else 0 */
14225 int len; /* number of characters */
14226 Py_ssize_t llen;
14227 int numdigits; /* len == numnondigits + numdigits */
14228 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014229
Victor Stinnerd0880d52012-04-27 23:40:13 +020014230 /* Avoid exceeding SSIZE_T_MAX */
14231 if (prec > INT_MAX-3) {
14232 PyErr_SetString(PyExc_OverflowError,
14233 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014234 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014235 }
14236
14237 assert(PyLong_Check(val));
14238
14239 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014240 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014241 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014242 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014243 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014244 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014245 /* int and int subclasses should print numerically when a numeric */
14246 /* format code is used (see issue18780) */
14247 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014248 break;
14249 case 'o':
14250 numnondigits = 2;
14251 result = PyNumber_ToBase(val, 8);
14252 break;
14253 case 'x':
14254 case 'X':
14255 numnondigits = 2;
14256 result = PyNumber_ToBase(val, 16);
14257 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014258 }
14259 if (!result)
14260 return NULL;
14261
14262 assert(unicode_modifiable(result));
14263 assert(PyUnicode_IS_READY(result));
14264 assert(PyUnicode_IS_ASCII(result));
14265
14266 /* To modify the string in-place, there can only be one reference. */
14267 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014268 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014269 PyErr_BadInternalCall();
14270 return NULL;
14271 }
14272 buf = PyUnicode_DATA(result);
14273 llen = PyUnicode_GET_LENGTH(result);
14274 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014275 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014276 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014277 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014278 return NULL;
14279 }
14280 len = (int)llen;
14281 sign = buf[0] == '-';
14282 numnondigits += sign;
14283 numdigits = len - numnondigits;
14284 assert(numdigits > 0);
14285
14286 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014287 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014288 (type == 'o' || type == 'x' || type == 'X'))) {
14289 assert(buf[sign] == '0');
14290 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14291 buf[sign+1] == 'o');
14292 numnondigits -= 2;
14293 buf += 2;
14294 len -= 2;
14295 if (sign)
14296 buf[0] = '-';
14297 assert(len == numnondigits + numdigits);
14298 assert(numdigits > 0);
14299 }
14300
14301 /* Fill with leading zeroes to meet minimum width. */
14302 if (prec > numdigits) {
14303 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14304 numnondigits + prec);
14305 char *b1;
14306 if (!r1) {
14307 Py_DECREF(result);
14308 return NULL;
14309 }
14310 b1 = PyBytes_AS_STRING(r1);
14311 for (i = 0; i < numnondigits; ++i)
14312 *b1++ = *buf++;
14313 for (i = 0; i < prec - numdigits; i++)
14314 *b1++ = '0';
14315 for (i = 0; i < numdigits; i++)
14316 *b1++ = *buf++;
14317 *b1 = '\0';
14318 Py_DECREF(result);
14319 result = r1;
14320 buf = PyBytes_AS_STRING(result);
14321 len = numnondigits + prec;
14322 }
14323
14324 /* Fix up case for hex conversions. */
14325 if (type == 'X') {
14326 /* Need to convert all lower case letters to upper case.
14327 and need to convert 0x to 0X (and -0x to -0X). */
14328 for (i = 0; i < len; i++)
14329 if (buf[i] >= 'a' && buf[i] <= 'x')
14330 buf[i] -= 'a'-'A';
14331 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014332 if (!PyUnicode_Check(result)
14333 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014334 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014335 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014336 Py_DECREF(result);
14337 result = unicode;
14338 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014339 else if (len != PyUnicode_GET_LENGTH(result)) {
14340 if (PyUnicode_Resize(&result, len) < 0)
14341 Py_CLEAR(result);
14342 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014343 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014344}
14345
Ethan Furmandf3ed242014-01-05 06:50:30 -080014346/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014347 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014348 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014349 * -1 and raise an exception on error */
14350static int
Victor Stinnera47082312012-10-04 02:19:54 +020014351mainformatlong(PyObject *v,
14352 struct unicode_format_arg_t *arg,
14353 PyObject **p_output,
14354 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014355{
14356 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014357 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014358
14359 if (!PyNumber_Check(v))
14360 goto wrongtype;
14361
Ethan Furman9ab74802014-03-21 06:38:46 -070014362 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014363 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014364 if (type == 'o' || type == 'x' || type == 'X') {
14365 iobj = PyNumber_Index(v);
14366 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014367 if (PyErr_ExceptionMatches(PyExc_TypeError))
14368 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014369 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014370 }
14371 }
14372 else {
14373 iobj = PyNumber_Long(v);
14374 if (iobj == NULL ) {
14375 if (PyErr_ExceptionMatches(PyExc_TypeError))
14376 goto wrongtype;
14377 return -1;
14378 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014379 }
14380 assert(PyLong_Check(iobj));
14381 }
14382 else {
14383 iobj = v;
14384 Py_INCREF(iobj);
14385 }
14386
14387 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014388 && arg->width == -1 && arg->prec == -1
14389 && !(arg->flags & (F_SIGN | F_BLANK))
14390 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014391 {
14392 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014393 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014394 int base;
14395
Victor Stinnera47082312012-10-04 02:19:54 +020014396 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014397 {
14398 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014399 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014400 case 'd':
14401 case 'i':
14402 case 'u':
14403 base = 10;
14404 break;
14405 case 'o':
14406 base = 8;
14407 break;
14408 case 'x':
14409 case 'X':
14410 base = 16;
14411 break;
14412 }
14413
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014414 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14415 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014416 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014417 }
14418 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014419 return 1;
14420 }
14421
Ethan Furmanb95b5612015-01-23 20:05:18 -080014422 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014423 Py_DECREF(iobj);
14424 if (res == NULL)
14425 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014426 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014427 return 0;
14428
14429wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014430 switch(type)
14431 {
14432 case 'o':
14433 case 'x':
14434 case 'X':
14435 PyErr_Format(PyExc_TypeError,
14436 "%%%c format: an integer is required, "
14437 "not %.200s",
14438 type, Py_TYPE(v)->tp_name);
14439 break;
14440 default:
14441 PyErr_Format(PyExc_TypeError,
14442 "%%%c format: a number is required, "
14443 "not %.200s",
14444 type, Py_TYPE(v)->tp_name);
14445 break;
14446 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014447 return -1;
14448}
14449
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014450static Py_UCS4
14451formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014452{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014453 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014454 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014455 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014456 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014457 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014458 goto onError;
14459 }
14460 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014461 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014462 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014463 /* make sure number is a type of integer */
14464 if (!PyLong_Check(v)) {
14465 iobj = PyNumber_Index(v);
14466 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014467 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014468 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014469 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014470 Py_DECREF(iobj);
14471 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014472 else {
14473 x = PyLong_AsLong(v);
14474 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014475 if (x == -1 && PyErr_Occurred())
14476 goto onError;
14477
Victor Stinner8faf8212011-12-08 22:14:11 +010014478 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014479 PyErr_SetString(PyExc_OverflowError,
14480 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014481 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014482 }
14483
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014484 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014485 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014486
Benjamin Peterson29060642009-01-31 22:14:21 +000014487 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014488 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014489 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014490 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014491}
14492
Victor Stinnera47082312012-10-04 02:19:54 +020014493/* Parse options of an argument: flags, width, precision.
14494 Handle also "%(name)" syntax.
14495
14496 Return 0 if the argument has been formatted into arg->str.
14497 Return 1 if the argument has been written into ctx->writer,
14498 Raise an exception and return -1 on error. */
14499static int
14500unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14501 struct unicode_format_arg_t *arg)
14502{
14503#define FORMAT_READ(ctx) \
14504 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14505
14506 PyObject *v;
14507
Victor Stinnera47082312012-10-04 02:19:54 +020014508 if (arg->ch == '(') {
14509 /* Get argument value from a dictionary. Example: "%(name)s". */
14510 Py_ssize_t keystart;
14511 Py_ssize_t keylen;
14512 PyObject *key;
14513 int pcount = 1;
14514
14515 if (ctx->dict == NULL) {
14516 PyErr_SetString(PyExc_TypeError,
14517 "format requires a mapping");
14518 return -1;
14519 }
14520 ++ctx->fmtpos;
14521 --ctx->fmtcnt;
14522 keystart = ctx->fmtpos;
14523 /* Skip over balanced parentheses */
14524 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14525 arg->ch = FORMAT_READ(ctx);
14526 if (arg->ch == ')')
14527 --pcount;
14528 else if (arg->ch == '(')
14529 ++pcount;
14530 ctx->fmtpos++;
14531 }
14532 keylen = ctx->fmtpos - keystart - 1;
14533 if (ctx->fmtcnt < 0 || pcount > 0) {
14534 PyErr_SetString(PyExc_ValueError,
14535 "incomplete format key");
14536 return -1;
14537 }
14538 key = PyUnicode_Substring(ctx->fmtstr,
14539 keystart, keystart + keylen);
14540 if (key == NULL)
14541 return -1;
14542 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014543 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014544 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014545 }
14546 ctx->args = PyObject_GetItem(ctx->dict, key);
14547 Py_DECREF(key);
14548 if (ctx->args == NULL)
14549 return -1;
14550 ctx->args_owned = 1;
14551 ctx->arglen = -1;
14552 ctx->argidx = -2;
14553 }
14554
14555 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014556 while (--ctx->fmtcnt >= 0) {
14557 arg->ch = FORMAT_READ(ctx);
14558 ctx->fmtpos++;
14559 switch (arg->ch) {
14560 case '-': arg->flags |= F_LJUST; continue;
14561 case '+': arg->flags |= F_SIGN; continue;
14562 case ' ': arg->flags |= F_BLANK; continue;
14563 case '#': arg->flags |= F_ALT; continue;
14564 case '0': arg->flags |= F_ZERO; continue;
14565 }
14566 break;
14567 }
14568
14569 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014570 if (arg->ch == '*') {
14571 v = unicode_format_getnextarg(ctx);
14572 if (v == NULL)
14573 return -1;
14574 if (!PyLong_Check(v)) {
14575 PyErr_SetString(PyExc_TypeError,
14576 "* wants int");
14577 return -1;
14578 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014579 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014580 if (arg->width == -1 && PyErr_Occurred())
14581 return -1;
14582 if (arg->width < 0) {
14583 arg->flags |= F_LJUST;
14584 arg->width = -arg->width;
14585 }
14586 if (--ctx->fmtcnt >= 0) {
14587 arg->ch = FORMAT_READ(ctx);
14588 ctx->fmtpos++;
14589 }
14590 }
14591 else if (arg->ch >= '0' && arg->ch <= '9') {
14592 arg->width = arg->ch - '0';
14593 while (--ctx->fmtcnt >= 0) {
14594 arg->ch = FORMAT_READ(ctx);
14595 ctx->fmtpos++;
14596 if (arg->ch < '0' || arg->ch > '9')
14597 break;
14598 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14599 mixing signed and unsigned comparison. Since arg->ch is between
14600 '0' and '9', casting to int is safe. */
14601 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14602 PyErr_SetString(PyExc_ValueError,
14603 "width too big");
14604 return -1;
14605 }
14606 arg->width = arg->width*10 + (arg->ch - '0');
14607 }
14608 }
14609
14610 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014611 if (arg->ch == '.') {
14612 arg->prec = 0;
14613 if (--ctx->fmtcnt >= 0) {
14614 arg->ch = FORMAT_READ(ctx);
14615 ctx->fmtpos++;
14616 }
14617 if (arg->ch == '*') {
14618 v = unicode_format_getnextarg(ctx);
14619 if (v == NULL)
14620 return -1;
14621 if (!PyLong_Check(v)) {
14622 PyErr_SetString(PyExc_TypeError,
14623 "* wants int");
14624 return -1;
14625 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014626 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014627 if (arg->prec == -1 && PyErr_Occurred())
14628 return -1;
14629 if (arg->prec < 0)
14630 arg->prec = 0;
14631 if (--ctx->fmtcnt >= 0) {
14632 arg->ch = FORMAT_READ(ctx);
14633 ctx->fmtpos++;
14634 }
14635 }
14636 else if (arg->ch >= '0' && arg->ch <= '9') {
14637 arg->prec = arg->ch - '0';
14638 while (--ctx->fmtcnt >= 0) {
14639 arg->ch = FORMAT_READ(ctx);
14640 ctx->fmtpos++;
14641 if (arg->ch < '0' || arg->ch > '9')
14642 break;
14643 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14644 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014645 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014646 return -1;
14647 }
14648 arg->prec = arg->prec*10 + (arg->ch - '0');
14649 }
14650 }
14651 }
14652
14653 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14654 if (ctx->fmtcnt >= 0) {
14655 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14656 if (--ctx->fmtcnt >= 0) {
14657 arg->ch = FORMAT_READ(ctx);
14658 ctx->fmtpos++;
14659 }
14660 }
14661 }
14662 if (ctx->fmtcnt < 0) {
14663 PyErr_SetString(PyExc_ValueError,
14664 "incomplete format");
14665 return -1;
14666 }
14667 return 0;
14668
14669#undef FORMAT_READ
14670}
14671
14672/* Format one argument. Supported conversion specifiers:
14673
14674 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014675 - "i", "d", "u": int or float
14676 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014677 - "e", "E", "f", "F", "g", "G": float
14678 - "c": int or str (1 character)
14679
Victor Stinner8dbd4212012-12-04 09:30:24 +010014680 When possible, the output is written directly into the Unicode writer
14681 (ctx->writer). A string is created when padding is required.
14682
Victor Stinnera47082312012-10-04 02:19:54 +020014683 Return 0 if the argument has been formatted into *p_str,
14684 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014685 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014686static int
14687unicode_format_arg_format(struct unicode_formatter_t *ctx,
14688 struct unicode_format_arg_t *arg,
14689 PyObject **p_str)
14690{
14691 PyObject *v;
14692 _PyUnicodeWriter *writer = &ctx->writer;
14693
14694 if (ctx->fmtcnt == 0)
14695 ctx->writer.overallocate = 0;
14696
Victor Stinnera47082312012-10-04 02:19:54 +020014697 v = unicode_format_getnextarg(ctx);
14698 if (v == NULL)
14699 return -1;
14700
Victor Stinnera47082312012-10-04 02:19:54 +020014701
14702 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014703 case 's':
14704 case 'r':
14705 case 'a':
14706 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14707 /* Fast path */
14708 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14709 return -1;
14710 return 1;
14711 }
14712
14713 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14714 *p_str = v;
14715 Py_INCREF(*p_str);
14716 }
14717 else {
14718 if (arg->ch == 's')
14719 *p_str = PyObject_Str(v);
14720 else if (arg->ch == 'r')
14721 *p_str = PyObject_Repr(v);
14722 else
14723 *p_str = PyObject_ASCII(v);
14724 }
14725 break;
14726
14727 case 'i':
14728 case 'd':
14729 case 'u':
14730 case 'o':
14731 case 'x':
14732 case 'X':
14733 {
14734 int ret = mainformatlong(v, arg, p_str, writer);
14735 if (ret != 0)
14736 return ret;
14737 arg->sign = 1;
14738 break;
14739 }
14740
14741 case 'e':
14742 case 'E':
14743 case 'f':
14744 case 'F':
14745 case 'g':
14746 case 'G':
14747 if (arg->width == -1 && arg->prec == -1
14748 && !(arg->flags & (F_SIGN | F_BLANK)))
14749 {
14750 /* Fast path */
14751 if (formatfloat(v, arg, NULL, writer) == -1)
14752 return -1;
14753 return 1;
14754 }
14755
14756 arg->sign = 1;
14757 if (formatfloat(v, arg, p_str, NULL) == -1)
14758 return -1;
14759 break;
14760
14761 case 'c':
14762 {
14763 Py_UCS4 ch = formatchar(v);
14764 if (ch == (Py_UCS4) -1)
14765 return -1;
14766 if (arg->width == -1 && arg->prec == -1) {
14767 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014768 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014769 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014770 return 1;
14771 }
14772 *p_str = PyUnicode_FromOrdinal(ch);
14773 break;
14774 }
14775
14776 default:
14777 PyErr_Format(PyExc_ValueError,
14778 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014779 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014780 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14781 (int)arg->ch,
14782 ctx->fmtpos - 1);
14783 return -1;
14784 }
14785 if (*p_str == NULL)
14786 return -1;
14787 assert (PyUnicode_Check(*p_str));
14788 return 0;
14789}
14790
14791static int
14792unicode_format_arg_output(struct unicode_formatter_t *ctx,
14793 struct unicode_format_arg_t *arg,
14794 PyObject *str)
14795{
14796 Py_ssize_t len;
14797 enum PyUnicode_Kind kind;
14798 void *pbuf;
14799 Py_ssize_t pindex;
14800 Py_UCS4 signchar;
14801 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014802 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014803 Py_ssize_t sublen;
14804 _PyUnicodeWriter *writer = &ctx->writer;
14805 Py_UCS4 fill;
14806
14807 fill = ' ';
14808 if (arg->sign && arg->flags & F_ZERO)
14809 fill = '0';
14810
14811 if (PyUnicode_READY(str) == -1)
14812 return -1;
14813
14814 len = PyUnicode_GET_LENGTH(str);
14815 if ((arg->width == -1 || arg->width <= len)
14816 && (arg->prec == -1 || arg->prec >= len)
14817 && !(arg->flags & (F_SIGN | F_BLANK)))
14818 {
14819 /* Fast path */
14820 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14821 return -1;
14822 return 0;
14823 }
14824
14825 /* Truncate the string for "s", "r" and "a" formats
14826 if the precision is set */
14827 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14828 if (arg->prec >= 0 && len > arg->prec)
14829 len = arg->prec;
14830 }
14831
14832 /* Adjust sign and width */
14833 kind = PyUnicode_KIND(str);
14834 pbuf = PyUnicode_DATA(str);
14835 pindex = 0;
14836 signchar = '\0';
14837 if (arg->sign) {
14838 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14839 if (ch == '-' || ch == '+') {
14840 signchar = ch;
14841 len--;
14842 pindex++;
14843 }
14844 else if (arg->flags & F_SIGN)
14845 signchar = '+';
14846 else if (arg->flags & F_BLANK)
14847 signchar = ' ';
14848 else
14849 arg->sign = 0;
14850 }
14851 if (arg->width < len)
14852 arg->width = len;
14853
14854 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014855 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014856 if (!(arg->flags & F_LJUST)) {
14857 if (arg->sign) {
14858 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014859 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014860 }
14861 else {
14862 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014863 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014864 }
14865 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014866 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14867 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014868 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014869 }
14870
Victor Stinnera47082312012-10-04 02:19:54 +020014871 buflen = arg->width;
14872 if (arg->sign && len == arg->width)
14873 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014874 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014875 return -1;
14876
14877 /* Write the sign if needed */
14878 if (arg->sign) {
14879 if (fill != ' ') {
14880 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14881 writer->pos += 1;
14882 }
14883 if (arg->width > len)
14884 arg->width--;
14885 }
14886
14887 /* Write the numeric prefix for "x", "X" and "o" formats
14888 if the alternate form is used.
14889 For example, write "0x" for the "%#x" format. */
14890 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14891 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14892 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14893 if (fill != ' ') {
14894 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14895 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14896 writer->pos += 2;
14897 pindex += 2;
14898 }
14899 arg->width -= 2;
14900 if (arg->width < 0)
14901 arg->width = 0;
14902 len -= 2;
14903 }
14904
14905 /* Pad left with the fill character if needed */
14906 if (arg->width > len && !(arg->flags & F_LJUST)) {
14907 sublen = arg->width - len;
14908 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14909 writer->pos += sublen;
14910 arg->width = len;
14911 }
14912
14913 /* If padding with spaces: write sign if needed and/or numeric prefix if
14914 the alternate form is used */
14915 if (fill == ' ') {
14916 if (arg->sign) {
14917 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14918 writer->pos += 1;
14919 }
14920 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14921 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14922 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14923 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14924 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14925 writer->pos += 2;
14926 pindex += 2;
14927 }
14928 }
14929
14930 /* Write characters */
14931 if (len) {
14932 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14933 str, pindex, len);
14934 writer->pos += len;
14935 }
14936
14937 /* Pad right with the fill character if needed */
14938 if (arg->width > len) {
14939 sublen = arg->width - len;
14940 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14941 writer->pos += sublen;
14942 }
14943 return 0;
14944}
14945
14946/* Helper of PyUnicode_Format(): format one arg.
14947 Return 0 on success, raise an exception and return -1 on error. */
14948static int
14949unicode_format_arg(struct unicode_formatter_t *ctx)
14950{
14951 struct unicode_format_arg_t arg;
14952 PyObject *str;
14953 int ret;
14954
Victor Stinner8dbd4212012-12-04 09:30:24 +010014955 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014956 if (arg.ch == '%') {
14957 ctx->fmtpos++;
14958 ctx->fmtcnt--;
14959 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14960 return -1;
14961 return 0;
14962 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014963 arg.flags = 0;
14964 arg.width = -1;
14965 arg.prec = -1;
14966 arg.sign = 0;
14967 str = NULL;
14968
Victor Stinnera47082312012-10-04 02:19:54 +020014969 ret = unicode_format_arg_parse(ctx, &arg);
14970 if (ret == -1)
14971 return -1;
14972
14973 ret = unicode_format_arg_format(ctx, &arg, &str);
14974 if (ret == -1)
14975 return -1;
14976
14977 if (ret != 1) {
14978 ret = unicode_format_arg_output(ctx, &arg, str);
14979 Py_DECREF(str);
14980 if (ret == -1)
14981 return -1;
14982 }
14983
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014984 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014985 PyErr_SetString(PyExc_TypeError,
14986 "not all arguments converted during string formatting");
14987 return -1;
14988 }
14989 return 0;
14990}
14991
Alexander Belopolsky40018472011-02-26 01:02:56 +000014992PyObject *
14993PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014994{
Victor Stinnera47082312012-10-04 02:19:54 +020014995 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014996
Guido van Rossumd57fd912000-03-10 22:53:23 +000014997 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014998 PyErr_BadInternalCall();
14999 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015000 }
Victor Stinnera47082312012-10-04 02:19:54 +020015001
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015002 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015003 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015004
15005 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020015006 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
15007 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
15008 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
15009 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015010
Victor Stinner8f674cc2013-04-17 23:02:17 +020015011 _PyUnicodeWriter_Init(&ctx.writer);
15012 ctx.writer.min_length = ctx.fmtcnt + 100;
15013 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015014
Guido van Rossumd57fd912000-03-10 22:53:23 +000015015 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020015016 ctx.arglen = PyTuple_Size(args);
15017 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015018 }
15019 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015020 ctx.arglen = -1;
15021 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015022 }
Victor Stinnera47082312012-10-04 02:19:54 +020015023 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040015024 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020015025 ctx.dict = args;
15026 else
15027 ctx.dict = NULL;
15028 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015029
Victor Stinnera47082312012-10-04 02:19:54 +020015030 while (--ctx.fmtcnt >= 0) {
15031 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020015032 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020015033
15034 nonfmtpos = ctx.fmtpos++;
15035 while (ctx.fmtcnt >= 0 &&
15036 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
15037 ctx.fmtpos++;
15038 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015039 }
Victor Stinnera47082312012-10-04 02:19:54 +020015040 if (ctx.fmtcnt < 0) {
15041 ctx.fmtpos--;
15042 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020015043 }
Victor Stinneree4544c2012-05-09 22:24:08 +020015044
Victor Stinnercfc4c132013-04-03 01:48:39 +020015045 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
15046 nonfmtpos, ctx.fmtpos) < 0)
15047 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015048 }
15049 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015050 ctx.fmtpos++;
15051 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000015052 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020015053 }
15054 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020015055
Victor Stinnera47082312012-10-04 02:19:54 +020015056 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015057 PyErr_SetString(PyExc_TypeError,
15058 "not all arguments converted during string formatting");
15059 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015060 }
15061
Victor Stinnera47082312012-10-04 02:19:54 +020015062 if (ctx.args_owned) {
15063 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015064 }
Victor Stinnera47082312012-10-04 02:19:54 +020015065 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015066
Benjamin Peterson29060642009-01-31 22:14:21 +000015067 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015068 _PyUnicodeWriter_Dealloc(&ctx.writer);
15069 if (ctx.args_owned) {
15070 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015071 }
15072 return NULL;
15073}
15074
Jeremy Hylton938ace62002-07-17 16:30:39 +000015075static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015076unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15077
Tim Peters6d6c1a32001-08-02 04:15:00 +000015078static PyObject *
15079unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15080{
Benjamin Peterson29060642009-01-31 22:14:21 +000015081 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015082 static char *kwlist[] = {"object", "encoding", "errors", 0};
15083 char *encoding = NULL;
15084 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015085
Benjamin Peterson14339b62009-01-31 16:36:08 +000015086 if (type != &PyUnicode_Type)
15087 return unicode_subtype_new(type, args, kwds);
15088 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015089 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 return NULL;
15091 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015092 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015093 if (encoding == NULL && errors == NULL)
15094 return PyObject_Str(x);
15095 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015096 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015097}
15098
Guido van Rossume023fe02001-08-30 03:12:59 +000015099static PyObject *
15100unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15101{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015102 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015103 Py_ssize_t length, char_size;
15104 int share_wstr, share_utf8;
15105 unsigned int kind;
15106 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015107
Benjamin Peterson14339b62009-01-31 16:36:08 +000015108 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015109
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015110 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015111 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015113 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015114 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015115 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015116 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015117 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015118
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015119 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015120 if (self == NULL) {
15121 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015122 return NULL;
15123 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015124 kind = PyUnicode_KIND(unicode);
15125 length = PyUnicode_GET_LENGTH(unicode);
15126
15127 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015128#ifdef Py_DEBUG
15129 _PyUnicode_HASH(self) = -1;
15130#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015131 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015132#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015133 _PyUnicode_STATE(self).interned = 0;
15134 _PyUnicode_STATE(self).kind = kind;
15135 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015136 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015137 _PyUnicode_STATE(self).ready = 1;
15138 _PyUnicode_WSTR(self) = NULL;
15139 _PyUnicode_UTF8_LENGTH(self) = 0;
15140 _PyUnicode_UTF8(self) = NULL;
15141 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015142 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015143
15144 share_utf8 = 0;
15145 share_wstr = 0;
15146 if (kind == PyUnicode_1BYTE_KIND) {
15147 char_size = 1;
15148 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15149 share_utf8 = 1;
15150 }
15151 else if (kind == PyUnicode_2BYTE_KIND) {
15152 char_size = 2;
15153 if (sizeof(wchar_t) == 2)
15154 share_wstr = 1;
15155 }
15156 else {
15157 assert(kind == PyUnicode_4BYTE_KIND);
15158 char_size = 4;
15159 if (sizeof(wchar_t) == 4)
15160 share_wstr = 1;
15161 }
15162
15163 /* Ensure we won't overflow the length. */
15164 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15165 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015166 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015167 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015168 data = PyObject_MALLOC((length + 1) * char_size);
15169 if (data == NULL) {
15170 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015171 goto onError;
15172 }
15173
Victor Stinnerc3c74152011-10-02 20:39:55 +020015174 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015175 if (share_utf8) {
15176 _PyUnicode_UTF8_LENGTH(self) = length;
15177 _PyUnicode_UTF8(self) = data;
15178 }
15179 if (share_wstr) {
15180 _PyUnicode_WSTR_LENGTH(self) = length;
15181 _PyUnicode_WSTR(self) = (wchar_t *)data;
15182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015183
Christian Heimesf051e432016-09-13 20:22:02 +020015184 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015185 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015186 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015187#ifdef Py_DEBUG
15188 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15189#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015190 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015191 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015192
15193onError:
15194 Py_DECREF(unicode);
15195 Py_DECREF(self);
15196 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015197}
15198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015199PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015200"str(object='') -> str\n\
15201str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015202\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015203Create a new string object from the given object. If encoding or\n\
15204errors is specified, then the object must expose a data buffer\n\
15205that will be decoded using the given encoding and error handler.\n\
15206Otherwise, returns the result of object.__str__() (if defined)\n\
15207or repr(object).\n\
15208encoding defaults to sys.getdefaultencoding().\n\
15209errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015210
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015211static PyObject *unicode_iter(PyObject *seq);
15212
Guido van Rossumd57fd912000-03-10 22:53:23 +000015213PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015214 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 "str", /* tp_name */
15216 sizeof(PyUnicodeObject), /* tp_size */
15217 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015218 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015219 (destructor)unicode_dealloc, /* tp_dealloc */
15220 0, /* tp_print */
15221 0, /* tp_getattr */
15222 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015223 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015224 unicode_repr, /* tp_repr */
15225 &unicode_as_number, /* tp_as_number */
15226 &unicode_as_sequence, /* tp_as_sequence */
15227 &unicode_as_mapping, /* tp_as_mapping */
15228 (hashfunc) unicode_hash, /* tp_hash*/
15229 0, /* tp_call*/
15230 (reprfunc) unicode_str, /* tp_str */
15231 PyObject_GenericGetAttr, /* tp_getattro */
15232 0, /* tp_setattro */
15233 0, /* tp_as_buffer */
15234 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015235 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015236 unicode_doc, /* tp_doc */
15237 0, /* tp_traverse */
15238 0, /* tp_clear */
15239 PyUnicode_RichCompare, /* tp_richcompare */
15240 0, /* tp_weaklistoffset */
15241 unicode_iter, /* tp_iter */
15242 0, /* tp_iternext */
15243 unicode_methods, /* tp_methods */
15244 0, /* tp_members */
15245 0, /* tp_getset */
15246 &PyBaseObject_Type, /* tp_base */
15247 0, /* tp_dict */
15248 0, /* tp_descr_get */
15249 0, /* tp_descr_set */
15250 0, /* tp_dictoffset */
15251 0, /* tp_init */
15252 0, /* tp_alloc */
15253 unicode_new, /* tp_new */
15254 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015255};
15256
15257/* Initialize the Unicode implementation */
15258
Victor Stinner3a50e702011-10-18 21:21:00 +020015259int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015260{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015261 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015262 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015263 0x000A, /* LINE FEED */
15264 0x000D, /* CARRIAGE RETURN */
15265 0x001C, /* FILE SEPARATOR */
15266 0x001D, /* GROUP SEPARATOR */
15267 0x001E, /* RECORD SEPARATOR */
15268 0x0085, /* NEXT LINE */
15269 0x2028, /* LINE SEPARATOR */
15270 0x2029, /* PARAGRAPH SEPARATOR */
15271 };
15272
Fred Drakee4315f52000-05-09 19:53:39 +000015273 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015274 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015275 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015276 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015277 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015278
Guido van Rossumcacfc072002-05-24 19:01:59 +000015279 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015280 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015281
15282 /* initialize the linebreak bloom filter */
15283 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015284 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015285 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015286
Christian Heimes26532f72013-07-20 14:57:16 +020015287 if (PyType_Ready(&EncodingMapType) < 0)
15288 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015289
Benjamin Petersonc4311282012-10-30 23:21:10 -040015290 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15291 Py_FatalError("Can't initialize field name iterator type");
15292
15293 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15294 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015295
Victor Stinner3a50e702011-10-18 21:21:00 +020015296 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015297}
15298
15299/* Finalize the Unicode implementation */
15300
Christian Heimesa156e092008-02-16 07:38:31 +000015301int
15302PyUnicode_ClearFreeList(void)
15303{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015304 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015305}
15306
Guido van Rossumd57fd912000-03-10 22:53:23 +000015307void
Thomas Wouters78890102000-07-22 19:25:51 +000015308_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015309{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015310 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015311
Serhiy Storchaka05997252013-01-26 12:14:02 +020015312 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015313
Serhiy Storchaka05997252013-01-26 12:14:02 +020015314 for (i = 0; i < 256; i++)
15315 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015316 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015317 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015318}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015319
Walter Dörwald16807132007-05-25 13:52:07 +000015320void
15321PyUnicode_InternInPlace(PyObject **p)
15322{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015323 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015325#ifdef Py_DEBUG
15326 assert(s != NULL);
15327 assert(_PyUnicode_CHECK(s));
15328#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015329 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015330 return;
15331#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015332 /* If it's a subclass, we don't really know what putting
15333 it in the interned dict might do. */
15334 if (!PyUnicode_CheckExact(s))
15335 return;
15336 if (PyUnicode_CHECK_INTERNED(s))
15337 return;
15338 if (interned == NULL) {
15339 interned = PyDict_New();
15340 if (interned == NULL) {
15341 PyErr_Clear(); /* Don't leave an exception */
15342 return;
15343 }
15344 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015346 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015347 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015348 if (t == NULL) {
15349 PyErr_Clear();
15350 return;
15351 }
15352 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015353 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015354 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015355 return;
15356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015357 /* The two references in interned are not counted by refcnt.
15358 The deallocator will take care of this */
15359 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015360 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015361}
15362
15363void
15364PyUnicode_InternImmortal(PyObject **p)
15365{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015366 PyUnicode_InternInPlace(p);
15367 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015368 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015369 Py_INCREF(*p);
15370 }
Walter Dörwald16807132007-05-25 13:52:07 +000015371}
15372
15373PyObject *
15374PyUnicode_InternFromString(const char *cp)
15375{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015376 PyObject *s = PyUnicode_FromString(cp);
15377 if (s == NULL)
15378 return NULL;
15379 PyUnicode_InternInPlace(&s);
15380 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015381}
15382
Alexander Belopolsky40018472011-02-26 01:02:56 +000015383void
15384_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015385{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015386 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015387 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015388 Py_ssize_t i, n;
15389 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015390
Benjamin Peterson14339b62009-01-31 16:36:08 +000015391 if (interned == NULL || !PyDict_Check(interned))
15392 return;
15393 keys = PyDict_Keys(interned);
15394 if (keys == NULL || !PyList_Check(keys)) {
15395 PyErr_Clear();
15396 return;
15397 }
Walter Dörwald16807132007-05-25 13:52:07 +000015398
Benjamin Peterson14339b62009-01-31 16:36:08 +000015399 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15400 detector, interned unicode strings are not forcibly deallocated;
15401 rather, we give them their stolen references back, and then clear
15402 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015403
Benjamin Peterson14339b62009-01-31 16:36:08 +000015404 n = PyList_GET_SIZE(keys);
15405 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015406 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015407 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015408 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015409 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015410 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015412 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015413 case SSTATE_NOT_INTERNED:
15414 /* XXX Shouldn't happen */
15415 break;
15416 case SSTATE_INTERNED_IMMORTAL:
15417 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015418 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015419 break;
15420 case SSTATE_INTERNED_MORTAL:
15421 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015422 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015423 break;
15424 default:
15425 Py_FatalError("Inconsistent interned string state.");
15426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015427 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015428 }
15429 fprintf(stderr, "total size of all interned strings: "
15430 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15431 "mortal/immortal\n", mortal_size, immortal_size);
15432 Py_DECREF(keys);
15433 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015434 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015435}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015436
15437
15438/********************* Unicode Iterator **************************/
15439
15440typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015441 PyObject_HEAD
15442 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015443 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015444} unicodeiterobject;
15445
15446static void
15447unicodeiter_dealloc(unicodeiterobject *it)
15448{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015449 _PyObject_GC_UNTRACK(it);
15450 Py_XDECREF(it->it_seq);
15451 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015452}
15453
15454static int
15455unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15456{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015457 Py_VISIT(it->it_seq);
15458 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015459}
15460
15461static PyObject *
15462unicodeiter_next(unicodeiterobject *it)
15463{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015464 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015465
Benjamin Peterson14339b62009-01-31 16:36:08 +000015466 assert(it != NULL);
15467 seq = it->it_seq;
15468 if (seq == NULL)
15469 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015470 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015472 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15473 int kind = PyUnicode_KIND(seq);
15474 void *data = PyUnicode_DATA(seq);
15475 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15476 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015477 if (item != NULL)
15478 ++it->it_index;
15479 return item;
15480 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015481
Benjamin Peterson14339b62009-01-31 16:36:08 +000015482 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015483 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015484 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015485}
15486
15487static PyObject *
15488unicodeiter_len(unicodeiterobject *it)
15489{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015490 Py_ssize_t len = 0;
15491 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015492 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015493 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015494}
15495
15496PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15497
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015498static PyObject *
15499unicodeiter_reduce(unicodeiterobject *it)
15500{
15501 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015502 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015503 it->it_seq, it->it_index);
15504 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015505 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015506 if (u == NULL)
15507 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015508 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015509 }
15510}
15511
15512PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15513
15514static PyObject *
15515unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15516{
15517 Py_ssize_t index = PyLong_AsSsize_t(state);
15518 if (index == -1 && PyErr_Occurred())
15519 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015520 if (it->it_seq != NULL) {
15521 if (index < 0)
15522 index = 0;
15523 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15524 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15525 it->it_index = index;
15526 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015527 Py_RETURN_NONE;
15528}
15529
15530PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15531
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015532static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015533 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015534 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015535 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15536 reduce_doc},
15537 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15538 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015539 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015540};
15541
15542PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015543 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15544 "str_iterator", /* tp_name */
15545 sizeof(unicodeiterobject), /* tp_basicsize */
15546 0, /* tp_itemsize */
15547 /* methods */
15548 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15549 0, /* tp_print */
15550 0, /* tp_getattr */
15551 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015552 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015553 0, /* tp_repr */
15554 0, /* tp_as_number */
15555 0, /* tp_as_sequence */
15556 0, /* tp_as_mapping */
15557 0, /* tp_hash */
15558 0, /* tp_call */
15559 0, /* tp_str */
15560 PyObject_GenericGetAttr, /* tp_getattro */
15561 0, /* tp_setattro */
15562 0, /* tp_as_buffer */
15563 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15564 0, /* tp_doc */
15565 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15566 0, /* tp_clear */
15567 0, /* tp_richcompare */
15568 0, /* tp_weaklistoffset */
15569 PyObject_SelfIter, /* tp_iter */
15570 (iternextfunc)unicodeiter_next, /* tp_iternext */
15571 unicodeiter_methods, /* tp_methods */
15572 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015573};
15574
15575static PyObject *
15576unicode_iter(PyObject *seq)
15577{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015578 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015579
Benjamin Peterson14339b62009-01-31 16:36:08 +000015580 if (!PyUnicode_Check(seq)) {
15581 PyErr_BadInternalCall();
15582 return NULL;
15583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015584 if (PyUnicode_READY(seq) == -1)
15585 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015586 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15587 if (it == NULL)
15588 return NULL;
15589 it->it_index = 0;
15590 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015591 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015592 _PyObject_GC_TRACK(it);
15593 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015594}
15595
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015596
15597size_t
15598Py_UNICODE_strlen(const Py_UNICODE *u)
15599{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015600 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015601}
15602
15603Py_UNICODE*
15604Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15605{
15606 Py_UNICODE *u = s1;
15607 while ((*u++ = *s2++));
15608 return s1;
15609}
15610
15611Py_UNICODE*
15612Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15613{
15614 Py_UNICODE *u = s1;
15615 while ((*u++ = *s2++))
15616 if (n-- == 0)
15617 break;
15618 return s1;
15619}
15620
15621Py_UNICODE*
15622Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15623{
15624 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015625 u1 += wcslen(u1);
15626 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015627 return s1;
15628}
15629
15630int
15631Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15632{
15633 while (*s1 && *s2 && *s1 == *s2)
15634 s1++, s2++;
15635 if (*s1 && *s2)
15636 return (*s1 < *s2) ? -1 : +1;
15637 if (*s1)
15638 return 1;
15639 if (*s2)
15640 return -1;
15641 return 0;
15642}
15643
15644int
15645Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15646{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015647 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015648 for (; n != 0; n--) {
15649 u1 = *s1;
15650 u2 = *s2;
15651 if (u1 != u2)
15652 return (u1 < u2) ? -1 : +1;
15653 if (u1 == '\0')
15654 return 0;
15655 s1++;
15656 s2++;
15657 }
15658 return 0;
15659}
15660
15661Py_UNICODE*
15662Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15663{
15664 const Py_UNICODE *p;
15665 for (p = s; *p; p++)
15666 if (*p == c)
15667 return (Py_UNICODE*)p;
15668 return NULL;
15669}
15670
15671Py_UNICODE*
15672Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15673{
15674 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015675 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015676 while (p != s) {
15677 p--;
15678 if (*p == c)
15679 return (Py_UNICODE*)p;
15680 }
15681 return NULL;
15682}
Victor Stinner331ea922010-08-10 16:37:20 +000015683
Victor Stinner71133ff2010-09-01 23:43:53 +000015684Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015685PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015686{
Victor Stinner577db2c2011-10-11 22:12:48 +020015687 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015688 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015690 if (!PyUnicode_Check(unicode)) {
15691 PyErr_BadArgument();
15692 return NULL;
15693 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015694 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015695 if (u == NULL)
15696 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015697 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015698 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015699 PyErr_NoMemory();
15700 return NULL;
15701 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015702 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015703 size *= sizeof(Py_UNICODE);
15704 copy = PyMem_Malloc(size);
15705 if (copy == NULL) {
15706 PyErr_NoMemory();
15707 return NULL;
15708 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015709 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015710 return copy;
15711}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015712
Georg Brandl66c221e2010-10-14 07:04:07 +000015713/* A _string module, to export formatter_parser and formatter_field_name_split
15714 to the string.Formatter class implemented in Python. */
15715
15716static PyMethodDef _string_methods[] = {
15717 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15718 METH_O, PyDoc_STR("split the argument as a field name")},
15719 {"formatter_parser", (PyCFunction) formatter_parser,
15720 METH_O, PyDoc_STR("parse the argument as a format string")},
15721 {NULL, NULL}
15722};
15723
15724static struct PyModuleDef _string_module = {
15725 PyModuleDef_HEAD_INIT,
15726 "_string",
15727 PyDoc_STR("string helper module"),
15728 0,
15729 _string_methods,
15730 NULL,
15731 NULL,
15732 NULL,
15733 NULL
15734};
15735
15736PyMODINIT_FUNC
15737PyInit__string(void)
15738{
15739 return PyModule_Create(&_string_module);
15740}
15741
15742
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015743#ifdef __cplusplus
15744}
15745#endif